Sub topic 8
Token bucket: steady rate with controlled bursts
This chapter assumes you know basic HTTP request and response concepts and can read Python. You should also know what the fixed window counter does and why its boundary burst is a problem. The token bucket avoids that problem by letting you set the burst size and the long-run rate as two separate numbers.
The working model
Picture a bucket that holds tokens. Each request must take tokens from the bucket to proceed. If enough tokens are present, the request is allowed and the tokens are removed. If not, the request is rejected. Tokens flow back into the bucket at a constant rate, and the bucket never holds more than its capacity.
Two parameters define the behavior:
- capacity is the maximum number of tokens. It sets the largest burst a client can send after a quiet period.
- refill_rate is the number of tokens added per second. It sets the average rate a client can sustain over time.
A client that has been idle has a full bucket and can send capacity requests at once. After that, it can only send as fast as tokens arrive.
Lazy refill
You do not need a timer that adds tokens every second. Instead, store the token count and the time of the last update. On each call, compute how many tokens would have arrived since then and add them, capped at capacity. This keeps the state to two numbers per key.
import time
class TokenBucket:
"""Single-process token bucket. Not thread-safe."""
def __init__(self, capacity, refill_rate):
self.capacity = capacity # maximum tokens (burst size)
self.refill_rate = refill_rate # tokens added per second
self.tokens = float(capacity)
self.last = time.monotonic()
def allow(self, cost=1):
now = time.monotonic()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
if self.tokens >= cost:
self.tokens -= cost
return True
return False
bucket = TokenBucket(capacity=5, refill_rate=1)
print([bucket.allow() for _ in range(7)]) # first 5 True, then FalseThe seven calls run almost instantly, so the bucket starts with 5 tokens, spends them, and has almost nothing refilled for calls 6 and 7. The output is five True values followed by two False values.
The code uses time.monotonic() because it never goes backward when the system clock is adjusted. The cost argument lets expensive operations take more than one token.
Choosing parameters
The long-run limit is refill_rate. The burst limit is capacity. Over any period of t seconds, a client can make at most capacity + refill_rate * t requests. For example, capacity 100 with a refill rate of 10 per second allows 100 requests immediately, then 10 per second after that.
A small capacity gives smooth traffic. A large capacity tolerates spiky clients, but lets them hit your backend with a larger burst.
Common errors
- Forgetting the cap. Without
min(capacity, ...), an idle client accumulates unlimited tokens and can send a huge burst later. - Using wall-clock time.
time.time()can jump backward or forward. Use a monotonic clock in one process. - Sharing one instance across threads. The read-modify-write sequence is not atomic. Two threads can spend the same token. Use a lock in one process, or an atomic script when state is shared across servers, as covered in later chapters.
- Never removing idle buckets. One bucket per key grows without bound unless you evict idle keys.
Exercise
A token bucket has capacity 20 and a refill rate of 5 tokens per second. A client has been idle for a long time. What is the most requests it can make in the first 4 seconds?
Show answer
40. It can spend the full bucket of 20 at once, and 4 seconds of refill adds 5 4 = 20 more tokens, so capacity + refill_rate t = 20 + 20 = 40.