API Rate Limiting & Scalability Patterns · Ders

Genel ve Hizmet Başına Hız Sınırlama

Uçta uygulanan genel hız sınırları ile tek tek mikro hizmetlere yönelik özel sınırlar arasındaki farkları ve etkileşimi anlayın.

2. ders / 411 adım

Genel ve Hizmet Başına Hız Sınırlama, CoddyKit'te ücretsiz bir API Rate Limiting & Scalability Patterns dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, API Rate Limiting & Scalability Patterns öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. API Rate Limiting & Scalability Patterns kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Global vs. Per-Service Limits

APIs often handle diverse traffic, from general users to specific internal systems. To manage this, we need different rate limiting strategies.

Today, we'll explore two key approaches: global rate limiting and per-service rate limiting. Understanding their differences helps build robust and fair APIs.

Guarding the Gates Globally

Global rate limiting is applied at the very edge of your system, before requests even reach individual services. Think of it as a bouncer at the club entrance.

  • It protects your entire infrastructure.
  • Often implemented in API Gateways, load balancers, or edge proxies.
  • Focuses on overall request volume to prevent system overload or DDoS attacks.

Global Limit Configuration

Here's a simplified example of how a global rate limit might be configured in an API Gateway like Nginx. It limits requests across all endpoints.

http {
  limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

  server {
    location / {
      limit_req zone=mylimit burst=20 nodelay;
      proxy_pass http://backend_services;
    }
  }
}

Why Global Limits Matter

Implementing global rate limits offers several advantages:

  • DDoS Protection: Blocks malicious traffic before it impacts your services.
  • Overall Stability: Ensures your entire system isn't overwhelmed by sudden traffic spikes.
  • Centralized Control: Easy to manage and modify limits for the whole API landscape.
  • Resource Efficiency: Less work for individual services to do for basic filtering.

Fine-Grained Service Control

Per-service rate limiting happens inside a specific microservice. It's like individual rules for different rooms within the club.

  • It applies to particular endpoints or operations within that service.
  • Implemented directly in the service's code or via a sidecar proxy.
  • Focuses on protecting specific service resources and enforcing business logic.

Per-Service Limit Code

Here's a tiny Java example illustrating a basic per-service rate limit for a specific endpoint. This uses a simple in-memory counter for demonstration.

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.time.Instant;

public class Main {
  private static final int MAX_REQUESTS_PER_MINUTE = 3;
  private static final long WINDOW_MILLIS = 60 * 1000; // 1 minute
  private static ConcurrentHashMap<String, Long> lastResetTime =
    new ConcurrentHashMap<>();
  private static ConcurrentHashMap<String, AtomicInteger> requestCounts =
    new ConcurrentHashMap<>();

  public static boolean allowRequest(String userId) {
    long currentTime = Instant.now().toEpochMilli();
    lastResetTime.computeIfAbsent(userId, k -> currentTime);
    requestCounts.computeIfAbsent(userId, k -> new AtomicInteger(0));

    // Reset if window passed
    if (currentTime - lastResetTime.get(userId) > WINDOW_MILLIS) {
      lastResetTime.put(userId, currentTime);
      requestCounts.get(userId).set(0);
    }

    if (requestCounts.get(userId).get() < MAX_REQUESTS_PER_MINUTE) {
      requestCounts.get(userId).incrementAndGet();
      return true;
    }
    return false;
  }

  public static void main(String[] args) {
    String userA = "user123";
    System.out.println("User A requests:");
    for (int i = 0; i < 5; i++) {
      System.out.println("Request " + (i + 1) + ": " +
        (allowRequest(userA) ? "Allowed" : "Denied"));
    }
    System.out.println("\nUser B requests:");
    String userB = "user456";
    for (int i = 0; i < 2; i++) {
      System.out.println("Request " + (i + 1) + ": " +
        (allowRequest(userB) ? "Allowed" : "Denied"));
    }
  }
}

Why Per-Service Limits are Key

Per-service rate limits provide more granular control:

  • Resource Protection: Prevents one endpoint from exhausting a service's specific resources (e.g., database connections).
  • Business Logic: Enforces limits based on specific user tiers or API functionality (e.g., "premium users get 1000 calls/min to this endpoint").
  • Isolation: A limit breach in one service doesn't necessarily bring down others.

Working Together: Layered Defense

The most robust systems use both global and per-service rate limits. They act as a layered defense:

  • Global limits: Act as a first line of defense, filtering out bulk traffic and protecting the entire system's entry point.
  • Per-service limits: Provide fine-tuned control within individual services, protecting specific resources and enforcing business rules.

Think of it as multiple checkpoints, each with a different purpose.

When to Use Which?

When designing your rate limiting strategy, consider:

  • Global: Best for broad protection, anonymous traffic, and preventing DDoS. Easy to implement at the infrastructure level.
  • Per-service: Ideal for protecting specific backend resources, enforcing user-specific quotas, or handling authenticated traffic with distinct access levels. Requires more application-level logic.

Often, a combination is the best approach.

Test Your Knowledge

Consider an API with a global rate limit of 1000 requests/second and a specific microservice endpoint that has a per-user limit of 10 requests/minute. A user makes 50 requests in 30 seconds to this specific endpoint.

Global vs. Per-Service Recap

We've explored the critical differences and synergy between global and per-service rate limiting:

  • Global limits: Act at the system's edge, protecting overall infrastructure from high-volume attacks.
  • Per-service limits: Provide fine-grained control within microservices, protecting specific resources and enforcing business rules.

Combining both strategies creates a robust, multi-layered defense for your APIs. Next, we'll dive into handling rate limit exceedance gracefully.

Başlamak ücretsiz

Yapay zeka eğitmeniyle API Rate Limiting & Scalability Patterns öğren — ücretsiz

Tarayıcında gerçek kod yaz ve çalıştır, 7/24 yapay zeka eğitmeninden anında yardım al; web'de ya da uygulamada kaldığın yerden devam et.

Kurslar
12
Dersler
48

Sıkça Sorulan Sorular

“Genel ve Hizmet Başına Hız Sınırlama” dersi ücretsiz mi?

Evet — “Genel ve Hizmet Başına Hız Sınırlama” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve API Rate Limiting & Scalability Patterns kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. API Rate Limiting & Scalability Patterns kursu toplamda 4 dersten oluşur.

“Genel ve Hizmet Başına Hız Sınırlama” dersinde ne öğreneceğim?

Uçta uygulanan genel hız sınırları ile tek tek mikro hizmetlere yönelik özel sınırlar arasındaki farkları ve etkileşimi anlayın. API Rate Limiting & Scalability Patterns ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

API Rate Limiting & Scalability Patterns öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te API Rate Limiting & Scalability Patterns, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Genel ve Hizmet Başına Hız Sınırlama” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu API Rate Limiting & Scalability Patterns dersinde kod yazıp çalıştırabilir miyim?

Evet. Her API Rate Limiting & Scalability Patterns dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. API Ağ Geçidi Entegrasyon Kalıpları
  2. Genel ve Hizmet Başına Hız Sınırlama
  3. Dinamik Hız Sınırı Yapılandırması
  4. Redis ile Dağıtık Hız Sınırlama
← API Rate Limiting & Scalability Patterns Sayfasına Dön