Token bucket, leaky bucket, fixed and sliding windows
Learn how the token bucket, the leaky bucket, the fixed window and the two sliding windows decide, and compare them on bursts, memory per key and accuracy.
Contentsand lesson path
On this page
- Why it matters
- Token bucket and leaky bucket
- Fixed window, sliding log and sliding counter
- Side by side
- Check your understanding
- Apply it
- Review prompt
Lessons of Rate Limiting
- Why limit: abuse, fairness, cost and overload Concept · 15 min
- Token bucket, leaky bucket, fixed and sliding windows Concept · 20 min
- Implementing token-bucket and sliding-window limiters Lab · 30 min
- Going distributed: atomic counters, races and store outages Worked example · 25 min
- Where to enforce limits and how clients should react Concept · 15 min
- Rate limiter check Knowledge check · 6 questions
What you will learn
- Implement token-bucket and sliding-window rate limiters and compare their burst behavior, memory and accuracy.
01. Why it matters
"100 requests per minute" sounds like one rule, but it can mean several different promises. It can mean on average 100 a minute, with short bursts allowed. It can mean never more than 100 in any 60 seconds. It can mean 100 per calendar minute, counted from :00 to :59. Each rate-limiting algorithm keeps one of these promises, and they differ in three ways that matter in production:
- Bursts: how many requests can pass at once, after a quiet period or around a boundary.
- Memory per key: how much state the limiter stores for each user, tenant or API key. With millions of keys, a few extra numbers per key add up.
- Accuracy: whether the limiter enforces its promise exactly, or estimates it.
This lesson explains the five common designs: the token bucket, the leaky bucket (in two forms), the fixed window, the sliding log and the sliding counter. In lesson 03 you implement four of them and measure the differences on the same traffic.
02. Token bucket and leaky bucket
A token bucket gives each key a bucket that holds at most capacity tokens. Tokens drip in at a steady rate, for example 2 per second. Each request takes one token; a request that finds no token is rejected. The two parameters map to two promises: capacity is the largest burst a quiet client can send at once, and rate is the long-run average. A client that has been quiet for a while finds a full bucket and can spend it all at once.
An implementation does not need a timer that adds tokens. It stores two numbers per key, the token count and the time of the last update, and computes the refill when the next request arrives: tokens = min(capacity, tokens + elapsed × rate). This lazy refill is why a token bucket is cheap even for millions of keys. Requests can also cost more than one token, so an expensive operation can take five tokens while a cheap one takes one.
Burst size and window size interact in a way that surprises many teams. In any span of W seconds, a token bucket can admit up to capacity + rate × W requests: everything saved up, plus everything that drips in. A bucket with capacity 100 refilled at 100 per minute therefore admits up to 200 within one minute. If your promise is "at most 100 in any minute", either shrink the capacity and the rate so that the sum stays at 100, or use a sliding window. AWS describes a third option: check two buckets, one with a large capacity and a low rate and one with a small capacity and a high rate, to allow bursts but limit how fast they arrive.
A leaky bucket appears in two forms. As a meter, the bucket fills by one unit per request and drains at a fixed rate; a request that would overflow it is rejected. Described this way it makes the same decisions as a token bucket with the same size and rate; the two are mirror images. As a queue, which is what most people picture, requests are placed in a queue of limited size and leave it at a fixed rate. Nothing is rejected while there is room: excess requests wait. Only when the queue is full are new arrivals dropped. NGINX describes its limit_req module as the leaky bucket method: requests above the rate are delayed, up to a configurable burst of waiting requests, and the rest are rejected.
The script simulates the queue form. It forwards one request every 0.5 seconds and lets at most 5 wait. Eight requests arrive at once, and two more arrive later.
"""A leaky bucket used as a queue: requests wait their turn or are dropped."""
INTERVAL = 0.5 # forward one request every 0.5 seconds (2 per second)
MAX_WAITING = 5 # at most 5 requests may wait; one more arriving is dropped
def leaky_queue(arrivals: list[float]) -> list[float | None]:
leaves: list[float | None] = []
last = float('-inf') # when the previous accepted request was forwarded
for t in arrivals:
waiting = sum(1 for d in leaves if d is not None and d > t)
if waiting >= MAX_WAITING:
leaves.append(None) # bucket full: drop (a 429 or 503 at a gateway)
continue
last = max(t, last + INTERVAL) # wait for the next free slot
leaves.append(last)
return leaves
arrivals = [0.0] * 8 + [3.0, 3.1] # a burst of 8, then two late requests
print('request arrives leaves waited')
for n, (t, d) in enumerate(zip(arrivals, leaky_queue(arrivals)), start=1):
if d is None:
print(f'{n:>7} {t:>7.1f} dropped')
else:
print(f'{n:>7} {t:>7.1f} {d:>6.1f} {d - t:>7.1f}')request arrives leaves waited
1 0.0 0.0 0.0
2 0.0 0.5 0.5
3 0.0 1.0 1.0
4 0.0 1.5 1.5
5 0.0 2.0 2.0
6 0.0 2.5 2.5
7 0.0 dropped
8 0.0 dropped
9 3.0 3.0 0.0
10 3.1 3.5 0.4The first request leaves at once and five wait, so six of the eight get through, each later than the one before; the last two are dropped. Request 10 shows the other side of a queue: even a single request can wait (0.4 s here), because the output never goes faster than the fixed rate. That makes the queue form a good shaper for traffic you send to a fragile system, and a costly one for interactive users, who feel every queued second. A token bucket with capacity 5 and the same rate would have let five requests through at once and rejected the others immediately.
A queue is not a fair waiting room, though. Requests that arrive while the queue is full are dropped, not given a place in line, so a token bucket or a leaky bucket alone cannot run something like a ticket sale, where people expect first come, first served. That needs a separate admission design with explicit ordering.
03. Fixed window, sliding log and sliding counter
A fixed window limiter cuts time into windows, for example calendar minutes, and keeps one counter per key per window. A request is admitted while the counter is below the limit. It is the simplest design to build on a shared store: one atomic increment and an expiry time per key. Its weakness is the boundary. A client can use the whole limit in the last second of one window and the whole limit again in the first second of the next, so up to twice the limit passes in a short span. A longer window does not fix this; it only makes the double burst larger.
A sliding log stores the time of every admitted request for each key. To decide, it drops times older than the window and compares the number left with the limit. It enforces the promise exactly: no span of W seconds ever holds more than the limit. The price is memory. Each key can hold up to limit timestamps, so a limit of 1,000 per hour can mean 1,000 stored numbers for every active key.
A sliding counter keeps the fixed window's counters but also looks at the previous window. It estimates the count over the last W seconds as current + previous × (share of the previous window still inside the last W seconds). If you are 45 seconds into a one-minute window, 15 seconds of the previous minute are still in view, so the previous count is weighted by 0.25. It stores three numbers per key and smooths the boundary burst. It is an estimate: it assumes the previous window's requests were spread evenly. If they all came in its last few seconds, the estimate is too low and a few extra requests get through. Cloudflare reported in 2017 that on 400 million requests of its own traffic, this approximation wrongly allowed or limited 0.003% of requests; your traffic may behave differently.
"""The sliding-window counter's estimate, for a limit of 60 per minute."""
LIMIT, WINDOW = 60, 60
def estimate(previous: int, current: int, seconds_into_window: float) -> float:
still_covered = 1 - seconds_into_window / WINDOW # share of last window in view
return current + previous * still_covered
for previous, current, into in [(48, 21, 45), (48, 21, 10), (0, 59, 50)]:
e = estimate(previous, current, into)
verdict = 'admit' if e < LIMIT else 'reject'
print(f'previous {previous:>2}, current {current:>2}, {into:>2} s in: '
f'estimate {e:4.1f} -> {verdict}')previous 48, current 21, 45 s in: estimate 33.0 -> admit
previous 48, current 21, 10 s in: estimate 61.0 -> reject
previous 0, current 59, 50 s in: estimate 59.0 -> admitThe same counts give opposite answers at different moments. Early in a window, most of the busy previous minute is still in view, so the request is rejected; late in the window, only a quarter of it counts. The third line shows that the estimate never goes beyond the counts you have: with an empty previous window, it behaves like a fixed window.
04. Side by side
The table sums up the trade-offs. "Exact" means the limiter keeps its own rule precisely, which is not the same as keeping every rule you might want: a token bucket is exact about its bucket, yet admits capacity + rate × W in a window.
algorithm bursts state per key accuracy
token bucket up to capacity, then the rate 2 numbers exact (own rule)
leaky, queue none: excess waits or drops a queue of requests exact output rate
fixed window up to 2x the limit at a border 2 numbers exact per window
sliding log never above the limit 1 time per request exact for any span
sliding counter close to the limit 3 numbers estimateSome rules of thumb follow from the table. Token buckets are the common default for API limits, because they allow natural bursts, store little and take extra cost per request easily; Stripe and the Envoy proxy both use them. Sliding counters suit "N per minute" promises across many keys when a small error is acceptable. Sliding logs suit small, strict limits, such as five password-reset emails per hour for one account. Fixed windows are fine for long quotas, such as a daily allowance, where a boundary burst does no harm. Leaky-bucket queues suit traffic you send to a system that must not see bursts.
05. Check your understanding
06. Apply it
Go back to the three operations you listed in lesson 01. For each, write the promise in one sentence ("on average", "never more than", or "per calendar day"), then pick an algorithm and its parameters. For every token bucket, also write capacity + rate × W for your window and check that the worst case is acceptable.
Then estimate memory: number of active keys × numbers stored per key × about 8 bytes per number, before the overhead of your store. Lesson 03 lets you check the burst and accuracy claims on real traffic, and lesson 04 moves the token bucket into a shared store.
07. Review prompt
Without looking back: explain what the capacity and the rate of a token bucket each control, and why a bucket can admit capacity + rate × W in a window. Describe the two meanings of "leaky bucket" and when queueing is the wrong behaviour. Then explain the fixed window's boundary burst, why the sliding log is exact but memory-hungry, and which assumption makes the sliding counter an estimate.
References
- Cloudflare blog (2017): How we built rate limiting capable of scaling to millions of domains
- NGINX documentation: ngx_http_limit_req_module
- Wikipedia: Leaky bucket (as a meter and as a queue)
- Envoy documentation: local rate limit filter (token bucket)
- AWS Builder Center: Fairness in multi-tenant systems
- Stripe Engineering: Scaling your API with rate limiters
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.