Rate Limiting Algorithms
| Algorithm | Idea | Pros / cons |
|---|---|---|
| Token bucket | bucket refills at rate r up to capacity b; each request takes a token | allows bursts up to b; tiny state (tokens, last_refill) — most common |
| Leaky bucket | queue drains at fixed rate | smooth output; bursts get queued/dropped |
| Fixed window counter | count per minute window | simple; 2× burst at window edges |
| Sliding window log | store timestamps, count last 60 s | exact; memory heavy |
| Sliding window counter | weighted current + previous window | good approximation, cheap |
def allow(key, rate, capacity, now):
tokens, last = store.get(key, (capacity, now))
tokens = min(capacity, tokens + (now - last) * rate) # refill
if tokens < 1:
return False
store[key] = (tokens - 1, now)
return True
Distributed: keep counters in Redis with an atomic Lua script (or INCR + EXPIRE); return HTTP 429 with Retry-After.