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.
See it run
Follow tokens, queues and windows call by call, with every number worked out.
Operations
Token bucket
Capacity 10, refill 2 a second.
Step 1 of 8
Full
- Tokens of 10
- 10
calls
The bucket starts with 10 tokens.
Step 1: Full
def allow(n, now): tokens = min(10, tokens + (now - last) * 2) last = now if tokens >= n: tokens -= n return True return False- Stored
- 2 numbers
- Bursts
- Up to 10
Refill first, then decide.
In the real world
The same rate limiter algorithms doing real jobs. Pick one and step through it.
100 calls at 00:59 and 100 at 01:01, limit 100 a minute.
Step 1 of 4
Fixed window
| 00:59 | 01:01 | |
|---|---|---|
| Fixed window | 100 | 100 |
All 200 pass.
Step 1: Fixed window
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Check, then count
criticalTwo calls read the same number and both pass.
Wrongn = get(key)if n < limit: set(key, n + 1)Rightone atomic step in the storeLosing the fraction
majorUnder steady load a bucket that rounds down never leaks or refills.
Wrongleaks = int(elapsed * rate)last = nowRightleaks = int(elapsed * rate)last += leaks / rateCounting refused calls
majorA caller who keeps trying stays blocked for ever.
Wronglog.append(now)return len(log) <= limitRightif len(log) >= limit: return Falselog.append(now)Forgetting the idle gap
minorAfter an hour of silence the count of an hour ago is treated as the previous minute.
Wrongprevious = currentRightprevious = current if window == last + 1 else 0
Interview tips
Explain it in one line
- Buckets model a supply, windows count in a stretch of time.
BLAST
- Buckets, Leaky is smooth.
- Allow bursts with tokens, Sliding, Token as default.
Good numbers
- At most C + r × t.
- Edge of a fixed window: 2 × limit.
- Counter: prev × (1 - part) + cur.
Expect these questions
- Why not a fixed window?
- How much memory for ten million?
- How long must the caller wait?