Rate limiter algorithms
medium 30 minToken bucket, leaky bucket, fixed window, sliding log and sliding counter: how each one counts, what it lets through, what it stores, and which to choose.
Video lesson · Chapter 1 of 5
A ten-token bucket refills by the second
Five limiter algorithms in 80 seconds
1:20Reel coming soon
More reels
One idea each, a minute or less.
Token bucket rate limiter
1:17Reel
Theory
Read or listen first. About 1 min.
What it is
A rate limiting algorithm answers one question: may this request pass now, given the earlier ones? It must answer quickly and store little for each caller.
There are two families. Buckets model a supply that fills or drains at a steady rate. Windows count requests in a stretch of time.
In one line: token bucket for bursts, leaky bucket for an even flow, sliding windows for a steady count.
Why it exists
Two limits that both say 100 a minute can behave very differently. One lets 200 through in two seconds, another makes calls wait, a third stores every call.
The choice decides what a caller notices, how much memory ten million callers need, and whether the service behind sees waves or a smooth flow.
A short history
1986
Jonathan Turner is credited with the original description of the leaky bucket: a counter that rises with each packet and falls steadily.
1995
The ATM Forum publishes its User-Network Interface specification 3.1, which describes the generic cell rate algorithm, a leaky bucket as a meter.
1999
RFC 2697 describes a traffic marker built from two token buckets.
2017
Cloudflare describes the sliding window counter and measures it on 400 million requests.
Words to know
- Token
- Permission for one request, or for one unit of work.
- Capacity
- The most tokens a bucket holds: the largest burst.
- Refill rate
- Tokens added each second: the lasting average.
- Lazy refill
- Compute the tokens when a request comes, instead of with a timer.
- Shaping
- Delaying requests so that they leave evenly.
- Policing
- Refusing what is too much, without delay.
- Boundary problem
- Twice the limit around the edge of two fixed windows.
- GCRA
- A leaky bucket kept as one time: when the next call is expected.
How it works
Step through the idea, or press Play.
Read state. A few numbers for this caller
Understand it
Start here
A carousel and a leaking bucket
One bucket stores permission, the other stores work.
All five at a glance
| Algorithm | Bursts | Stored for each caller | Exactness | Best for |
|---|---|---|---|---|
| Token bucket | Up to the capacity | 2 numbers | Exact for its own rule | APIs |
| Leaky bucket (queue) | Smoothed | The waiting requests | Exact rate out | Protecting something that needs an even rate |
| Fixed window | Double at the edge | 1 number | Low near the edge | Long quotas, simple counts |
| Sliding log | Up to the limit | 1 time per request | Exact | Small strict limits |
| Sliding counter | Nearly the limit | 2 numbers | Close estimate | General use |
Bucket 1
Token bucket
- 1
Fill
Tokens are added at a fixed rate, for example 2 a second.
- 2
Hold
At most the capacity, for example 10. The rest is lost.
- 3
Take
A request takes one token, or more if it costs more. Not enough tokens: refused.
Lazy refill
The most that can pass
Good
- Allows honest bursts
- Two numbers for each caller
- Little work
- A costly call can take several tokens
Not so good
- A burst can hit a weak service
- Says nothing about gaps between calls
- Two numbers to choose
- Needs one atomic step when shared
Bucket 2
Leaky bucket
- 1
Join
A request joins a queue, the bucket.
- 2
Leak
Requests leave the queue at a constant rate.
- 3
Overflow
If the queue is full, a new request is refused.
Token or leaky?
| Token bucket | Leaky queue | |
|---|---|---|
| Output | Can come in bursts | Even |
| Controls | The average, and the largest burst | The exact rate out |
| Extra waiting | None | Up to queue length divided by rate |
| Idle time | Saved as tokens | Not saved |
| Use | API limits | Shaping traffic to a fixed-rate system |
Window 1
Fixed window
One counter for each caller and minute. It starts again at each full minute. Very cheap, and easy to explain: it suits quotas per day or month.
The boundary problem
Window 2
Sliding log
Store the time of each passed request. On a new one, drop those older than 60 seconds and count the rest. Exact, at the price of one entry for each request. Count only what passed: if refused calls are stored as well, a caller who keeps trying is never let in again.
Memory of a log
Window 3
Sliding counter
Keep two counters: the current window and the one before. Assume the previous requests were spread evenly, and count the part that still lies inside the last 60 seconds.
The estimate
A sliding counter decides
Cloudflare measured it on 400 million requests from 270,000 sources: 0.003% were wrongly allowed or limited, and the estimated rate differed from the real one by 6% on average.
Bonus
GCRA: one number
The generic cell rate algorithm keeps only the theoretical arrival time: when the next call is expected if calls come evenly. A call may be early by at most the burst allowance. One number for each caller, no timer, and the waiting time comes for free.
def gcra(tat, now, T, burst): """Returns (allowed, new tat, seconds to wait).""" tat = max(tat, now) early = tat - now if early > (burst - 1) * T + 1e-9: return False, tat, early - (burst - 1) * T return True, tat + T, 0.0tat = 0.0for now in (0, 0, 0, 0, 1): # one a second, burst of 3 ok, tat, wait = gcra(tat, now, 1.0, 3) print(now, ok, wait)Place
Where the state lives
The gateway decides, the store remembers
A token bucket decides
A leaky queue in time
Compare
The same traffic, four answers
Limit 100 a minute. 100 calls at 00:59, 100 calls at 01:01
| Algorithm | First 100 | Second 100 | Together |
|---|---|---|---|
| Fixed window | 100 pass | 100 pass | 200 |
| Sliding log | 100 pass | 0 pass | 100 |
| Sliding counter | 100 pass | 2 pass | 102 |
| Token bucket, capacity 100, 100 a minute | 100 pass | 3 pass | 103 |
Choosing
One sentence each
Token bucket
Save up, then spend.
Leaky queue
Whatever comes in, the same goes out.
Fixed window
A new page each minute.
Sliding log
Remember everything.
Sliding counter
Remember two pages and estimate.
Implement
Details that go wrong
Do
- Refill lazily
- Keep the fraction of a token or a leak
- Use one clock, the store's
- Expire state of idle callers
- Return the waiting time
Do not
- Run a timer for each caller
- Set the last time to now after rounding down
- Read and write in two calls
- Let time go backwards: use a later-of rule
- Store refused calls in the log
Summary
The whole topic in one minute.
Token bucket is the usual default for APIs: bursts up to the capacity, a steady average, two stored numbers. A leaky queue sends at an even rate and adds waiting.
Fixed windows are the cheapest and allow twice the limit at the edge. A sliding log is exact and large. A sliding counter is nearly as good with two numbers.
- Token bucket: capacity is the burst, refill is the average, at most C + r × t pass.
- Leaky queue: even output, extra waiting, refuses when full.
- Fixed window: cheap, up to double at the edge.
- Sliding log: exact, one entry for each request. Sliding counter: two numbers and a good estimate.
- Whatever you choose, one atomic step and one clock.