Rate limiting algorithms
Token bucket, leaky bucket and windowed counters: how to cap usage per client fairly and cheaply.
15 min readWhy rate limit
Load shedding protects the server from total demand; rate limiting protects it, and other customers, from any single client. It enforces quotas (1 000 requests per hour per API key), blocks abuse such as credential stuffing, and keeps one noisy tenant from consuming shared capacity. A limiter answers one question per request, allow or reject, and it must answer within a millisecond or two because it sits on every request.
Token and leaky buckets
A token bucket holds up to B tokens and refills at R tokens per second; each request spends one, and requests are rejected when the bucket is empty. It allows short bursts of up to B while enforcing an average of R, which suits most APIs. A leaky bucket instead queues requests and releases them at a fixed rate, smoothing output completely; it suits protecting a downstream that cannot take bursts, at the cost of added latency.
Window counters
Window-based limiters count requests per time period.
- Fixed window: one counter per minute; simple, but a client can send 2x the limit across a boundary (the end of one minute and the start of the next)
- Sliding window log: store every timestamp; exact, but memory grows with the limit
- Sliding window counter: weight the previous window's count by how much of it overlaps; close to exact with two counters per key
Distributed limiting
With many gateway instances, counters must be shared, usually in Redis with an atomic increment or a small Lua script per check. That adds a network hop and a dependency, so decide how the limiter fails: most public APIs fail open when the counter store is down, accepting brief over-limit traffic over a total outage. At very high volume, instances can keep local counters and sync periodically, trading a little accuracy for latency. Always return 429 with a Retry-After header so well-behaved clients back off.
Key takeaways
- Token buckets allow bursts while enforcing an average rate; they are the common default
- Fixed windows allow 2x bursts at boundaries; sliding window counters fix this cheaply
- Shared counters need atomic operations and an explicit fail-open or fail-closed decision
- Return 429 with Retry-After so clients can back off correctly
Sign in to track lessons and earn badges.