Predict the output
Capacity 5, refill 2 per tick. A client sends nothing for two ticks, then 8 requests in tick 3. How many are rejected in tick 3?
cap, refill = 5, 2
tokens = cap
for arrive in (0, 0, 8):
tokens = min(cap, tokens + refill)
allowed = min(tokens, arrive)
tokens -= allowed
print(arrive - allowed)Hint 1 of 1
Can tokens go above the capacity?
Choose an answer, then open Show answer below to check it.
Run on Redis 7
Text version
| Tick | Arrive | Tokens before | Allowed | Rejected |
|---|---|---|---|---|
| T1 | 2 | 5 | 2 | 0 |
| T2 | 2 | 5 | 2 | 0 |
| T3 | 2 | 5 | 2 | 0 |
| T4 | 2 | 5 | 2 | 0 |
| T5 | 2 | 5 | 2 | 0 |
| T6 | 2 | 5 | 2 | 0 |
| Tick | Arrive | Tokens before | Allowed | Rejected |
|---|---|---|---|---|
| T1 | 0 | 5 | 0 | 0 |
| T2 | 0 | 5 | 0 | 0 |
| T3 | 8 | 5 | 5 | 3 |
| T4 | 1 | 2 | 1 | 0 |
| T5 | 6 | 3 | 3 | 3 |
| T6 | 2 | 2 | 2 | 0 |
Show answer
Answer: A 3
Correct. The bucket is capped at 5, so 5 of 8 pass and 3 are rejected.
A token bucket refills over time but never above its capacity, which caps how big a burst can be. After the quiet ticks there are 5 tokens; 5 of the 8 requests take one each and the other 3 find it empty.
Why not the others?
- B
0. Tokens never exceed the capacity, however long the client is quiet. - C
1. That assumes 7 tokens built up; the cap is 5. - D
8. The quiet ticks left a full bucket.