Token Bucket and Leaky Bucket Rate Limiting: System Design Interview
Work the same request stream through both algorithms, learn the refill arithmetic, and pick between them from the requirement with a rule you can say in one sentence.
Token bucket and leaky bucket rate limiting are two ways to shape traffic. Token bucket refills tokens at a fixed rate and lets a request through only if a token is available, so it allows short bursts up to the bucket size while capping the long-run average. Leaky bucket drains at a fixed rate, so it smooths traffic to a constant output and queues or drops excess. In a token bucket and leaky bucket rate limiting system design interview, define both, give the refill or drain arithmetic, then say which one you would pick for the requirement in front of you and why.
Token bucket in one paragraph and one number line
A token bucket has two parameters. Capacity B is the number of tokens the bucket can hold; refill rate r is how many tokens are added per second. Each request removes one token. If the bucket is empty, the request is rejected or made to wait.
The two parameters control different things. r sets the long-run average rate: over any window long enough to refill, throughput cannot exceed r. B sets the largest burst you will tolerate: a client that has been idle can spend up to B tokens at once.
State the invariant explicitly in the interview: tokens never exceed B, and the bucket refills lazily as min(B, current + r × elapsed). That single line answers most follow-ups before they are asked.
Leaky bucket: fixed drain, smoothed output
A leaky bucket is a queue with capacity B that drains at a constant r per second. Requests enter the queue; if the queue is full, the request is dropped or the sender is told to back off.
What it buys you is a smooth stream at exactly r, never a burst. That matters when the next hop has little buffer, is metered, or is fragile under load spikes.
The cost is latency for anything that waits, and a burst that would have been harmless is delayed or dropped. Say that cost out loud rather than hiding it.
Worked example: the same request stream through both
Assume r = 10 requests/second and B = 20. The stream is idle for 2 seconds, then sends 30 requests at once, then settles at 5 per second.
Token bucket (r = 10/s, B = 20)
After 2 s idle: tokens = min(20, 0 + 2 x 10) = 20
The 30-request burst:
first 20 pass immediately (tokens = 0)
next 10 are rejected or wait about 1 s (10 tokens refill in 1 s)
Then 5/s arrives against a 10/s refill: tokens climb back to 20 and stay capped
Long-run output: at most 10/s, with bursts up to 20
Leaky bucket (queue B = 20, drain r = 10/s)
Same 30-request burst:
20 enter the queue, 10 are dropped
the 20 drain at 10/s over 2 s
Then 5/s arrives against a 10/s drain: queue stays empty
Downstream sees: a flat 10/s, no burst at allSame average, different burst behaviour, and the queue is where the latency lives. That sentence is worth memorising because it shows you understand both mechanisms rather than reciting definitions.
Lazy refill: compute tokens, do not run a timer
You do not need a background job per key. Store the token count and the last-refill timestamp, and compute the current count on each request.
import time
class TokenBucket:
def __init__(self, rate, capacity):
self.rate = rate # tokens per second
self.capacity = capacity # max tokens
self.tokens = capacity
self.last = time.monotonic()
def allow(self, now=None):
now = time.monotonic() if now is None else now
elapsed = max(0.0, now - self.last)
self.tokens = min(self.capacity, self.tokens + self.rate * elapsed)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return FalseTrace it with rate = 10, capacity = 20, starting full. Call allow at t = 0: elapsed is 0, tokens stay 20, one is spent, returns True. Wait 2 seconds and call again: elapsed = 2, tokens = min(20, 19 + 20) = 20, one is spent, returns True. Call 20 times in the same instant: the first 20 pass, the 21st sees tokens = 0 and returns False.
Time complexity is O(1) per request and space is O(1) per key. There is no timer because the arithmetic reconstructs the bucket state from the timestamp; a timer would only add a job per key and a source of drift.
Choosing between them from the requirement
Pick token bucket when the client is allowed short bursts and you want to reject fast rather than queue. A page that fires a handful of API calls on load is the classic case: the burst is legitimate, and a quick 429 is kinder than a two-second wait.
Pick leaky bucket when the downstream is fragile or metered and you must never exceed a rate, and added latency is acceptable.
Name the rejected option: "I am not using leaky bucket here because queueing would add tail latency the user would feel." That one sentence shows the choice was a decision, not a default.
| Attribute | Token bucket | Leaky bucket |
|---|---|---|
| Burst behaviour | Allows bursts up to B | Smooths to exactly r |
| Latency added | None when tokens are available | Waits in the queue until drained |
| When full | New requests rejected or delayed | New requests dropped or sender told to back off |
| Requirement it fits | Burst-tolerant clients, reject-fast | Never exceed a rate, fragile downstream |
The follow-ups interviewers ask next
Distributed counting. Two common options. A single shared counter per user in a store such as Redis with an atomic decrement gives exact global accuracy but adds a network round trip and a hot key. Per-node buckets with the global limit divided across nodes avoids the round trip but each node enforces a fraction, so the aggregate can drift when traffic is uneven. State the trade-off and pick one.
Clock skew. Lazy refill uses elapsed time, so skew between machines affects accuracy. Using a monotonic clock per process and a single source of time for the shared counter keeps the error bounded; say so rather than pretending clocks agree.
Boundary bursts. A client can burst at every window edge if you use fixed windows. Two buckets in series, or a smaller B, tightens it. If you want the wider picture of where the limiter sits, the full rate limiter design walkthrough covers storage and placement.
What to return. A 429 with a Retry-After derived from the refill rate, so the client knows when to try again. That is kinder than a bare rejection and reduces retry storms. For how this interacts with overload, see reasoning about flow control and backpressure.
Where the explanation goes wrong under pressure
Mixing the two: describing a token bucket that "drains at a fixed rate". Fix it by naming the direction first — tokens in, requests out — before any numbers.
Forgetting the cap: saying the bucket refills forever. Fix it by writing min(B, current + r × elapsed) explicitly.
Skipping the decision: defining both and never choosing. Fix it by ending with one sentence tying the choice to the stated requirement.
If you want to practise the surrounding fundamentals, system design interview fundamentals first is the place to start. And when the interviewer pushes on numbers, defending your throughput numbers helps you keep the arithmetic honest.
The one rule to carry into the room
Decide from the requirement, not the algorithm's reputation: burst-tolerant and reject-fast means token bucket; smooth and never-exceed means leaky bucket. Then give the arithmetic for the parameters you chose, because the numbers are what show you understand the mechanism. Say the rule in one sentence, then work the trace. That is the whole answer to the token bucket and leaky bucket rate limiting system design interview question.
Frequently asked questions
Is a token bucket the same as a fixed window counter?
No. A fixed window counter resets on a clock boundary, so a client can send a full allowance just before the reset and another just after, doubling the effective burst. A token bucket refills continuously with no boundary, so the burst is capped by B at any moment. That difference is usually the reason an interviewer asks the question.
How do I pick the bucket size B in an interview?
Tie B to the largest burst the downstream can absorb without harm, then check it against the client's real behaviour. If a page load fires ten calls, B of about ten to twenty is defensible. State it as an assumption, and say what you would measure in production to revise it.
What status code and headers should a rate limiter return?
Return 429 Too Many Requests, and include Retry-After computed from the refill rate so the client knows when capacity returns. Many designs also expose the remaining allowance in a header. Name the header you would use and say why the client needs it: it prevents blind retries that make the overload worse.
Can I combine token bucket and leaky bucket in one design?
Yes, and it is a reasonable answer. Put a token bucket at the edge to absorb legitimate bursts cheaply, then a leaky bucket in front of a fragile downstream to guarantee a smooth rate. Say what each layer protects and what extra latency the second layer adds.
How does this change if the limit is per API key rather than per user?
The mechanism is identical; only the key changes. The counter is keyed by API key, and the parameters may vary per tier. The distributed trade-offs stay the same, but a shared counter per key can become a hot spot if one key sends most of the traffic, so mention sharding or per-node fractions.
Practising rate limiter answers? See how AI Interview assistant works.