Token bucket vs sliding window: choosing a rate limiter
A rate limiter is a promise about fairness under pressure. The algorithm you choose decides whether a client that has been quiet can burst, whether the boundary of a window is a cliff, and how much state you must keep per key. Two algorithms cover most production needs, and they fail in different ways.
Token bucket in one paragraph
A bucket holds up to a capacity of tokens and refills at a fixed rate. Each request takes one token; if the bucket is empty the request is rejected with 429. Because tokens accumulate while the client is idle, a bucket allows a burst up to its capacity and then settles to the refill rate. Two numbers describe it completely: capacity and refill rate.
| Property | Token bucket | Sliding window |
|---|---|---|
| State per key | Two numbers | Timestamps or weighted counters |
| Burst allowed | Yes, up to capacity | Limited to the window size |
| Boundary behaviour | Smooth | Spike at window edges if fixed |
| Sustained rate | Exactly the refill rate | The window limit per period |
Sliding window and the boundary problem
A fixed window counts requests per calendar second or minute and resets at the boundary. That creates a well-known artefact: a client can send the full quota at the end of one window and again at the start of the next, achieving double the intended rate in a short interval. A sliding window fixes this by counting over the last N seconds, at the cost of keeping more state or approximating with weighted buckets.
What clients experience
Under a token bucket, a well-behaved client that pauses and resumes is rewarded with a short burst, which suits batch jobs and interactive clients. Under a sliding window, the rate is stricter and more predictable, which suits untrusted clients where fairness matters more than burst tolerance.
In both cases the response matters as much as the algorithm. A 429 must carry Retry-After and, ideally, headers that expose the remaining quota so clients can pace themselves instead of retrying blindly. A limiter that rejects without guidance simply moves the load to the retry path.
Choosing and testing
Use a token bucket when you want to allow burstiness and guarantee a long-run average, which is most public APIs. Use a sliding window or sliding log when the contract is a hard count per period, which is common in billing and quota systems. Distributed limiters usually implement an approximation of one of these with a shared counter and a short cache, so expect some drift between nodes.
Before shipping, simulate the arrival pattern you expect. A bucket with capacity 200 and refill 100 per second behaves very differently at 150 requests per second than at 300, and the difference is visible in the retry timeline rather than in the configuration.
Running a limiter in a distributed system
A single-process limiter is exact. A fleet of twenty instances sharing one logical bucket is not, unless the state is centralised. Most teams approximate with a shared counter and a short expiry, which introduces a small amount of drift: a client can sometimes exceed the limit by one instance's share. That is usually acceptable; documenting it is what makes it acceptable rather than surprising.
Two practical rules reduce the drift. Keep the window short enough that stale counters expire quickly, and key the limiter by the identity that matters — an API key, a tenant, an IP — rather than by a combination that fragments the state. Also decide explicitly what happens when the limiter's own store is unavailable: failing open admits traffic you meant to reject; failing closed rejects traffic you meant to admit. Neither is universally right, but the choice should be written down.
- Choose fail-open or fail-closed per endpoint before launch.
- Expose remaining quota so clients can self-throttle.
- Alert when the limiter rejects more than a small fraction of traffic.
Open the calculators and put these numbers to work on your own API.
Open API BenchFrequently asked questions
Which algorithm should a public API use?
A token bucket is the usual choice: it allows short bursts, enforces a clear long-run rate, and needs only two numbers of state per key.
How should the limiter tell clients the limit?
Return 429 with Retry-After and expose the remaining quota in response headers, so clients can slow down before they are rejected.
Does a rate limiter protect against a retry storm?
Only partly. It caps accepted traffic but rejected traffic still consumes connection and CPU. Pair the limiter with client-side backoff and server-side load shedding.
Sources
Related guides
- Capacity planning with Little's LawTurn a target request rate and three latency percentiles into the concurrency, threads and instances an API actually needs.
- Tail latency: why P95 and P99 decide your timeoutAverages hide the requests that hurt. How to read percentiles, calculate what they cost, and set timeouts that do not cut off healthy traffic.
- Retry storms: how a 1% error becomes 300% loadRetries are new traffic. Calculate the amplification, recognise the cliff, and design retry budgets that fail politely.
- REST vs GraphQL: measuring the payload differenceOver-fetching, under-fetching and query text all show up in the bytes. A practical way to compare the transfer volume of both designs.