Skip to content

Rate limiting: token bucket and sliding window

Working knowledgeUnder the hood

“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.

Sliding logOne entry per requestExact, but memory grows with the limit times the number of clients.
Counters and buckets1–2 numbers per clientMemory depends only on the number of clients. The price is a little precision.

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.

Limit 10 per minute, fixed windows
TimeRequestsCounter for its minuteAllowed
12:00:591012:00 → 10All 10
12:01:001012:01 → 10All 10
Total in 2 seconds2020, 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 bucket: capacity 3, refill 1 per second
Step 1 of 9
Bucket for key abc (capacity 3)
●
●
●
Stored for key abc
tokens 3.0
last 0.0s
Decisions
Empty
  • 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.

t = 0.0 s time

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.

token_bucket.py
class TokenBucket:
"""Per client: two numbers, however many requests it sends."""
def __init__(self, capacity: float, per_second: float):
self.capacity = capacity
self.rate = per_second
self.tokens = capacity
self.last = 0.0
def allow(self, now: float) -> bool:
# Refill for the time since the last request, never above capacity.
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
Text
$ python3 token_bucket.py
t=0.0s allow tokens left 2.0
t=0.0s allow tokens left 1.0
t=0.0s allow tokens left 0.0
t=0.0s 429 tokens left 0.0
t=1.5s allow tokens left 0.5
t=2.0s allow tokens left 0.0

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.

Sliding window counter: limit 10 per minute
Step 1 of 5
Counters for key abc (limit 10 per minute)
previous12:00 → 8
current12:01 → 3
Estimate at 12:01:15
Empty
  • 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.

Text
estimate = current + previous × (60 − seconds into this minute) / 60

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

Per-client cost and behaviour
AlgorithmStores per clientBursts at window edgesAccuracy
Sliding logEvery request time in the windowNoExact
Fixed window1 counterUp to 2× the limitExact per clock window
Sliding window counter2 countersMostly smoothed outClose estimate
Token bucketTokens and a timeAllowed up to capacity, by designExact 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.

06 Counting across many servers

Behind a load balancer, each server sees only part of a client’s traffic. A limit of 100 per minute enforced separately on 4 servers lets through up to 400. The counters have to live in one shared place, commonly Redis, and each update has to be atomic.

A fixed window in Redis is two commands per request. INCR creates the key at 1 or adds 1, atomically, so two servers can never both read 99 and both write 100. EXPIRE … NX sets a lifetime only if the key has none yet.

Text
> INCR rl:abc:1201
(integer) 1
> EXPIRE rl:abc:1201 60 NX
(integer) 1
> INCR rl:abc:1201
(integer) 2
> EXPIRE rl:abc:1201 60 NX
(integer) 0
> TTL rl:abc:1201
(integer) 60

That is a real run against Redis 8 (EXPIRE gained NX in Redis 7.0). The second EXPIRE returns 0 because the key already has a timer, so the window is not pushed back by each request. The counter is compared with the limit in your code: allow if INCR returned 10 or less.

Read-then-write is the classic bug: GET the count, check it in your code, then SET it. Two servers can read the same value and both allow. For a token bucket, which reads and writes two fields, run the whole update as one Lua script with EVAL so Redis does it atomically.

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.

08 Check yourself

Question

A token bucket has capacity 3 and refills 1 token per second. It is empty at t = 0. How many requests at t = 10 can pass at once?

Question

With fixed one-minute windows and a limit of 10, what is the most a client can send in any 2-second span?

Question

Sliding window counter, limit 10 per minute. Previous minute: 6. This minute: 4. A request comes 30 s into the minute. Allowed?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?