Rate limiting algorithms explained: token bucket, leaky bucket and sliding windows
Rate limiting caps how many requests a client can make in a period. It protects services from abuse, accidental overload and runaway scripts, and it's central to fair use of shared APIs.
Fixed window
- Count requests per client in each window, like each minute.
- Simple, but allows bursts at window boundaries: a client could send a full quota at 0:59 and again at 1:00.
Sliding window
- Looks at the last N seconds continuously, often approximated by weighting the previous window.
- Smoother than fixed windows with modest extra cost.
Token bucket
- A bucket fills with tokens at a steady rate up to a maximum. Each request spends a token.
- Allows short bursts (up to the bucket size) while enforcing an average rate.
- Very common in APIs and network equipment.
Leaky bucket
- Requests enter a queue that drains at a fixed rate.
- Produces a very smooth outflow, useful for protecting a fragile downstream system.
Design questions that matter as much as the algorithm:
- What's the key? Per user, per API key, per IP address, or per endpoint?
- Where is it enforced? At an API gateway, a load balancer, or in the app with a shared store like Redis.
- How do clients find out? Returning HTTP 429 with a
Retry-Afterheader helps clients back off politely. - Distributed accuracy: with many servers, counts need to be shared or approximate.
Which algorithm do you use, and where do you enforce it? Have you had to tune limits after legitimate users hit them?
Comments · 3
Great explanation. For a beginner: token bucket is like a jar that refills coins at a steady rate. Each request spends a coin, and you can save up for short bursts.
Sliding window counter is the usual sweet spot: cheap to run and avoids the burst-at-the-boundary problem of fixed windows.
Business angle: tiered limits per plan are also a pricing lever, so it's worth deciding limits with product, not just ops.