0Pricing
API Rate Limiting & Scalability Patterns · درس

آلية عمل خوارزمية دلو الرموز

استكشف خوارزمية دلو الرموز، وافهم مرونتها في السماح بالدفعات وأبرز حالات استخدامها في الأنظمة الحديثة

آلية عمل خوارزمية دلو الرموز درس مجاني في API Rate Limiting & Scalability Patterns على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في API Rate Limiting & Scalability Patterns، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة API Rate Limiting & Scalability Patterns 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Meet the Token Bucket

Welcome to the Token Bucket algorithm! After exploring fixed windows and leaky buckets, we'll now dive into a flexible approach that’s widely used in modern systems.

The Token Bucket is a rate-limiting algorithm that allows for bursts of traffic while still enforcing an average rate limit.

Tokens in a Virtual Bucket

Imagine a virtual 'bucket' that holds a certain number of 'tokens'. Each token represents permission for one API request.

  • When a request arrives, it tries to take a token.
  • If a token is available, the request proceeds, and the token is removed.
  • If no tokens are available, the request is typically denied or queued.

Filling Up the Bucket

Tokens are continuously added to the bucket at a constant, predefined rate. This rate determines the average number of requests allowed over time.

For example, if tokens are added at 5 tokens per second, your API can sustain an average of 5 requests per second.

The Bucket's Maximum Size

Just like a real bucket, our virtual token bucket has a maximum capacity. This means it can only hold a certain number of tokens at any given time.

  • If tokens are generated but the bucket is full, the new tokens are discarded.
  • This capacity limits the maximum size of a 'burst' of requests that can be handled.

Requesting a Token

When an API client makes a request, the rate limiter checks the token bucket:

  • If tokens are available: One token is consumed, and the request is allowed to proceed.
  • If no tokens are available: The request is blocked, rejected (e.g., with HTTP 429 Too Many Requests), or deferred.

The Power of Bursts

The key advantage of the Token Bucket algorithm is its ability to allow bursts. If the bucket has accumulated many tokens (up to its capacity), a sudden rush of requests can be served immediately.

Once the accumulated tokens are used up, the rate limit reverts to the sustained token generation rate.

Token Bucket in Action

Try running this simplified Java example to see how tokens are refilled and consumed. Notice how initial requests can burst, but subsequent requests depend on refills.

public class Main {
  // Simple TokenBucket class for demonstration
  static class TokenBucket {
    private int capacity;
    private int tokens;
    private int refillRate; // tokens per "tick"

    public TokenBucket(int capacity, int refillRate) {
      this.capacity = capacity;
      this.tokens = capacity; // Start full
      this.refillRate = refillRate;
    }

    public void refill() {
      tokens = Math.min(capacity, tokens + refillRate);
      System.out.println("Refill. Tokens: " + tokens);
    }

    public boolean tryConsume(int numTokens) {
      if (tokens >= numTokens) {
        tokens -= numTokens;
        System.out.println("Consume " + numTokens + ". Left: " + tokens);
        return true;
      }
      System.out.println("Fail to consume " + numTokens + ". Left: " + tokens);
      return false;
    }

    public int getTokens() {
      return tokens;
    }
  }

  public static void main(String[] args) {
    // Bucket: capacity 5, refills 1 token per tick
    TokenBucket bucket = new TokenBucket(5, 1);

    System.out.println("Start. Tokens: " + bucket.getTokens());

    // 1. Initial burst
    System.out.println("\n--- Request 1 (cost 3) ---");
    bucket.tryConsume(3); // OK: 5 -> 2

    // 2. Simulate time passing (refill)
    System.out.println("\n--- Tick 1 ---");
    bucket.refill(); // 2 -> 3

    // 3. Another request
    System.out.println("\n--- Request 2 (cost 2) ---");
    bucket.tryConsume(2); // OK: 3 -> 1

    // 4. Simulate time passing (refill)
    System.out.println("\n--- Tick 2 ---");
    bucket.refill(); // 1 -> 2

    // 5. Try to consume more than available
    System.out.println("\n--- Request 3 (cost 3) ---");
    bucket.tryConsume(3); // FAIL: 2 tokens available

    // 6. Simulate time passing (refill)
    System.out.println("\n--- Tick 3 ---");
    bucket.refill(); // 2 -> 3

    // 7. Try again with enough tokens
    System.out.println("\n--- Request 4 (cost 3) ---");
    bucket.tryConsume(3); // OK: 3 -> 0
  }
}

Why Choose Token Bucket?

The Token Bucket algorithm offers several compelling advantages, especially when compared to simpler methods:

  • Allows Bursts: It's perfect for APIs that expect occasional spikes in traffic.
  • Simple to Implement: The core logic is straightforward to code.
  • Smooth Average Rate: While allowing bursts, it still enforces a consistent average request rate over the long term.
  • Flexible: You can tune both the refill rate and bucket capacity to suit different use cases.

Common Use Cases

Token Bucket is widely used in various scenarios where controlled burstiness is desirable:

  • API Gateways: To protect backend services from sudden traffic surges.
  • Network Traffic Shaping: To smooth out data transmission and prevent network congestion.
  • Resource Management: Limiting access to shared resources in distributed systems.
  • Client-Side Rate Limiting: Implementing rate limits within client SDKs to prevent excessive requests.

Token Bucket Check

Let's test your understanding of the Token Bucket algorithm.

Token Bucket Summary

Great job! In this lesson, you've learned about the Token Bucket algorithm, a powerful rate-limiting method.

  • It uses a virtual bucket that accumulates tokens at a fixed rate.
  • Requests consume tokens, and if no tokens are available, requests are denied.
  • Its main strength is allowing controlled bursts of traffic, up to the bucket's capacity.

This flexibility makes it a popular choice for many real-world API and network applications.

الأسئلة الشائعة

هل درس «آلية عمل خوارزمية دلو الرموز» مجاني؟

نعم — نص درس «آلية عمل خوارزمية دلو الرموز» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة API Rate Limiting & Scalability Patterns، انتقل إلى CoddyKit PRO. تتضمن دورة API Rate Limiting & Scalability Patterns 4 دروس في المجموع.

ماذا ستتعلم في «آلية عمل خوارزمية دلو الرموز»؟

استكشف خوارزمية دلو الرموز، وافهم مرونتها في السماح بالدفعات وأبرز حالات استخدامها في الأنظمة الحديثة تتمرن على API Rate Limiting & Scalability Patterns مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ API Rate Limiting & Scalability Patterns؟

لا تُشترط خبرة سابقة. API Rate Limiting & Scalability Patterns على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «آلية عمل خوارزمية دلو الرموز»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس API Rate Limiting & Scalability Patterns هذا؟

نعم. كل درس في API Rate Limiting & Scalability Patterns يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. شرح عدّاد النافذة الثابتة
  2. تعمّق في خوارزمية الدلو المتسرّب
  3. آلية عمل خوارزمية دلو الرموز
  4. اختيار الخوارزمية المناسبة
← العودة إلى API Rate Limiting & Scalability Patterns