A token bucket holds 5 tokens. Which of these requests pass?
Question
An API limits each user with a token bucket:
- the bucket holds at most 5 tokens and starts full;
- it refills smoothly at 1 token a second, so half a token after 0.5 seconds;
- each request takes 1 whole token. A request that finds less than 1 token is rejected.
One user sends requests at these times:
| time (s) | requests |
|---|---|
| 0 | 6 |
| 0.5 | 1 |
| 1 | 1 |
| 10 | 6 |
Which requests pass? How many tokens are left after each time?
Show hints (3)
- "START FULL"
At time 0 the bucket holds 5 tokens, and six requests arrive together. How many find a token?
- "REJECTED TAKES NOTHING"
Between two times, add 1 token for each second that passed. A rejected request takes nothing, so what it found is still there for the next request.
- "THE CAP"
After 9 quiet seconds the bucket would hold 9 tokens, but it can never hold more than 5. Now count the requests at 10.
Show checked explanation
11 of the 14 requests pass. At 0, five pass and the sixth finds the bucket empty. At 0.5 there is only half a token: rejected. At 1 the half has become a whole token: it passes. At 10 the bucket holds 5, not 9, because 5 is its cap: five pass and one is rejected.
class TokenBucket: def __init__(self, capacity, rate): self.capacity = capacity # most tokens it holds: the biggest burst self.rate = rate # tokens added per second self.tokens, self.last = capacity, 0.0 # full at time 0 def allow(self, now, cost=1): added = (now - self.last) * self.rate self.tokens = min(self.capacity, self.tokens + added) self.last = now if self.tokens < cost: return False # rejected: takes nothing self.tokens -= cost return True bucket = TokenBucket(capacity=5, rate=1) for now, count in [(0, 6), (0.5, 1), (1, 1), (10, 6)]: passed = sum(bucket.allow(now) for _ in range(count)) print(f"t={now}: {passed} of {count} pass, {bucket.tokens:g} left")
t=0: 5 of 6 pass, 0 left t=0.5: 0 of 1 pass, 0.5 left t=1: 1 of 1 pass, 0 left t=10: 5 of 6 pass, 0 left
Code run on CPython 3.12 against the trace above. Checked by an editor other than the author.
Walkthrough
Two numbers define a token bucket. The capacity, 5, is the biggest burst a user can send at once. The rate, 1 a second, sets the average speed over a longer time. Here is the trace:
| time | tokens before | requests | pass | tokens after |
|---|---|---|---|---|
| 0 | 5 | 6 | 5 | 0 |
| 0.5 | 0.5 | 1 | 0 | 0.5 |
| 1 | 1 | 1 | 1 | 0 |
| 10 | 5 | 6 | 5 | 0 |
Two moments matter.
At 0.5 the request needs a whole token and finds half. It is rejected and takes nothing. So the half token is still there at 1, and another half second makes it whole.
At 10, nine seconds have passed. Without a cap the bucket would hold 9 tokens, and all 6 requests would pass. The cap keeps it at 5, so a quiet user can't save up a huge burst. In any T seconds, at most 5 + T requests pass: a full bucket plus what refills.
The code needs no timer. When a request arrives, it adds the refill for the time since the last request, then applies the cap. Each user costs two numbers: the tokens and the last time. Adding one whole token at each full second gives the same answers on this trace.
Common mistakes
- Giving each server its own bucket. Behind 3 servers a user can get 3 buckets: up to 15 requests at once, not 5. Keep one bucket per user in a shared store.
- Adding tokens with a timer for each bucket. With a million users, that is a million timers. Compute the refill from the time since the last request instead.
- Reading "5 tokens, 1 a second" as "5 a second". It allows 5 at once, but at most 65 in a minute: the full bucket plus 60 refilled.
Follow-up questions
- "Two API servers share one bucket in Redis. What can go wrong?" A race. With 1 token left, both servers read 1, decide "pass" and write 0. Two requests pass on one token. Do the refill, the check and the take in one atomic step. In Redis, send all three as one Lua program with
EVAL: Redis runs it atomically. Take the time from Redis (TIME) too, so all servers share one clock. - "Some calls cost more than others. How do you limit that?" Give each call a cost in tokens: a search costs 3, a simple read costs 1. A call passes only if the bucket holds its whole cost. With capacity 5, a call that costs 6 never passes, however long it waits. Raise the capacity or limit that call separately.
What a strong answer covers
Traces the bucket request by request: refill from the time that passed, cap at the capacity, then take a token or reject. Explains capacity as the burst and rate as the speed over time. Knows a shared bucket needs an atomic refill, check and take.
Open in interactive practice deck →