Rate limiting: token bucket and sliding window
“At most 100 requests a minute per API key” sounds like it needs a list of every request’s time. It doesn’t. Real limiters keep one or two numbers per client and still answer correctly, or close enough. Here is how, drawn request by request.
01 The question a limiter answers
For every request, the limiter must decide: has this client used up its allowance? The exact answer needs the time of each recent request. That is the sliding log: keep a sorted list of timestamps per client, drop the ones older than a minute, count the rest.
It is precise, and it is expensive. With a limit of 1,000 an hour and a million clients, the log can hold a billion timestamps: 8 GB of raw 8-byte numbers before any data-structure overhead, and a write to it on every request.
02 Fixed window: one counter per minute
The simplest limiter keeps a counter per client per clock minute, for example under the key rl:abc:1201. Each request adds 1; over the limit means 429. When the minute changes, a new key starts at zero.
The weakness is the boundary. The window resets on the clock, not relative to the client, so a client can spend a full allowance at the end of one minute and another at the start of the next.
| Time | Requests | Counter for its minute | Allowed |
|---|---|---|---|
| 12:00:59 | 10 | 12:00 → 10 | All 10 |
| 12:01:00 | 10 | 12:01 → 10 | All 10 |
| Total in 2 seconds | 20 | 20, twice the limit |
03 Token bucket: refill on demand
A token bucket gives each client a bucket of tokens. Each request takes one; tokens drip back in at a steady rate, up to a maximum. The trick that makes it cheap: the server never runs a timer. It stores the token count and the time it last looked, and works out the refill when the next request arrives.
- token
- spent
- taken now
- just changed
- rejected
Client abc may make bursts of up to 3 requests, refilled at 1 token per second. Its bucket starts full. The server stores just two numbers for it.
Two settings, two meanings: the rate is the long-run average a client gets, and the capacity is how big a burst it may make after being quiet. Many API gateways and proxies use this algorithm or close relatives.
That is a real run with Python 3.14, and it matches the trace step for step. The times are passed in so the run is repeatable; a server would use a monotonic clock such as time.monotonic().
04 Sliding window counter: blend two minutes
To fix the fixed window’s boundary burst without a log, keep the counters for this minute and the previous one, and estimate the last 60 seconds by blending them.
- reading now
- just worked out
- the decision
A request from abc arrives at 12:01:15. The server keeps one counter per minute, and only the last two matter.
Try the boundary burst from before: at 12:01:00 the previous minute counts in full, so the client’s 10 requests at 12:00:59 already use up the allowance. The estimate is wrong only when traffic within a minute is very uneven, and then only by a little.
05 Four limiters side by side
| Algorithm | Stores per client | Bursts at window edges | Accuracy |
|---|---|---|---|
| Sliding log | Every request time in the window | No | Exact |
| Fixed window | 1 counter | Up to 2× the limit | Exact per clock window |
| Sliding window counter | 2 counters | Mostly smoothed out | Close estimate |
| Token bucket | Tokens and a time | Allowed up to capacity, by design | Exact for its rule |
Token bucket suits APIs that should tolerate short bursts. Sliding window counter suits a plain “N per minute” promise. Fixed window is fine when a brief double burst does no harm.
07 When the limiter bites
key = client IPLimiting by IP address aloneAn office or a mobile carrier can put thousands of users behind one IPv4 address, while one IPv6 user may control a whole /64. Prefer API keys or user ids; group IPv6 by prefix.a dict in each serverPer-server countersThe real limit becomes the limit times the number of servers, and changes when you scale. Share the state.INCR, crash, no EXPIREA counter that never expiresIf only the first request sets the TTL and that server dies in between, the key lives forever and the client stays blocked. Send EXPIRE … NX every time, or use a script.time.time() on each serverClocks that disagreeA token bucket shared by servers whose clocks differ refills too much or too little. Take the time from one place, such as Redis TIME inside the script.403 with no hintRejecting without saying whenClients cannot tell a limit from a ban and retry at once. Answer 429 with Retry-After, and consider the IETF draft RateLimit headers to show what is left.