Rate Limiter Algorithms
Token bucket and friends.
How does a limiter count? The most popular algorithm is the token bucket. It allows short bursts, but keeps the average rate under control.

- How do we count?
- The token bucket
- Bursts, but a steady average
A token bucket
Each client has a bucket of tokens. Every request takes one token. Tokens drip back in at a fixed rate, up to the bucket's size. If the bucket is empty, the request is refused. Here the bucket holds three tokens, and refills one per second. Run it. A burst of five requests at once gets three through. A second later, one more is allowed.
class TokenBucket:
def __init__(self, size, per_sec):
self.size, self.rate = size, per_sec
self.tokens, self.last = size, 0.0
def allow(self, now):
self.tokens = min(self.size, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
b = TokenBucket(size=3, per_sec=1)
for t in [0, 0, 0, 0, 0, 1.0, 1.0]:
print(f"t={t}s ->", "allowed" if b.allow(t) else "429")t=0s -> allowed t=0s -> allowed t=0s -> allowed t=0s -> 429 t=0s -> 429 t=1.0s -> allowed t=1.0s -> 429
Other algorithms
There are other options. A fixed window counts requests per clock minute, which is simple, but allows double bursts at the edge of two windows. A sliding window fixes that, with a bit more work. And a leaky bucket processes requests at a perfectly steady rate, like water dripping from a hole.
| Algorithm | Behaviour |
|---|---|
| Token bucket | bursts allowed, steady average |
| Fixed window | simple, edge bursts |
| Sliding window | smooth, more memory |
| Leaky bucket | perfectly steady output |
Summary
The token bucket allows short bursts while keeping a steady average. It's the most popular rate limiting algorithm. Next, a quiz on scaling the web tier.
Key takeaways- Tokens drip in
- Each request takes one
- Empty means 429