Token Bucket vs Leaky Bucket Rate Limiting
A token bucket rate limiter passes a burst until its credits run out, then drops the rest; a leaky bucket turns the same burst into a smooth queue. One extra request, repeated, builds a long staircase of drops.
Level: Intermediate
Stocks and Flows
Learn about the foundational concepts of Stocks and Flows in systems thinking and how they interact to create system behavior.
Take the QuizToken bucket vs leaky bucket
A burst of requests hits two rate limiters every few seconds. The token bucket spends a stock of credits all at once, so the burst passes until the stock is empty and the extra request is dropped. The leaky bucket never emits faster than its drain, so the same burst is spread out instead of spiking. The default burst is one request over the credit stock; shrink only that size and a hundred small rejections become none.
from tys import probe, progress
def simulate(cfg: dict):
import simpy
env = simpy.Environment()
One knob
The burst fits in the token bucket only while burst_size is within
capacity. The bucket refills to full between bursts, so each burst
is an independent test of that line. One request over is rejected
every time; repeated bursts turn that single rejection into a long
staircase of drops.
sim_time = int(cfg["sim_time"])
burst_size = int(cfg["burst_size"])
burst_period = int(cfg["burst_period"])
capacity = int(cfg["capacity"])
refill_rate = int(cfg["refill_rate"])
drain_rate = int(cfg["drain_rate"])
buffer = int(cfg["buffer"])
if sim_time <= 0 or burst_period <= 0:
raise ValueError("sim_time and burst_period must be positive")
if burst_size < 0:
raise ValueError("burst_size cannot be negative")
if refill_rate <= 0 or drain_rate <= 0:
raise ValueError("refill_rate and drain_rate must be positive")
if capacity < 1 or buffer < 1:
raise ValueError("capacity and buffer must hold at least one request")
Whole requests, once per second. The bucket starts full. Later seconds refill first, then spend, so a burst always meets a full stock when the quiet gap is long enough to refill.
tokens = capacity
leaky_queue = 0
token_dropped = 0
leaky_dropped = 0
done = env.event()
def dynamics():
nonlocal tokens, leaky_queue, token_dropped, leaky_dropped
for t in range(sim_time):
if t > 0:
tokens = min(capacity, tokens + refill_rate)
arrivals = burst_size if t % burst_period == 0 else 0
Token bucket: admit up to the credits on hand, drop the rest.
admitted = min(arrivals, tokens)
tokens -= admitted
token_dropped += arrivals - admitted
Leaky bucket: the comparison line. Arrivals join a queue and
leave at most drain_rate per second, so a burst cannot spike.
room = buffer - leaky_queue
accepted = min(arrivals, room)
leaky_dropped += arrivals - accepted
leaky_queue += accepted
released = min(leaky_queue, drain_rate)
leaky_queue -= released
probe("token_drops_total", t, token_dropped)
probe("token_credits", t, tokens)
probe("token_bucket_output", t, admitted)
probe("leaky_bucket_output", t, released)
if t % burst_period == 0:
progress(
int(100 * t / sim_time),
f"Burst of {burst_size} against {capacity} credits",
)
else:
progress(int(100 * t / sim_time))
yield env.timeout(1)
progress(100)
done.succeed(
{
"burst_clipped": token_dropped > 0,
"token_dropped": token_dropped,
"leaky_dropped": leaky_dropped,
}
)
env.process(dynamics())
env.run(until=done)
return done.value
def requirements():
return {"external": ["simpy==4.1.1"]}
# clips.yaml — default, one request past the edge.
# The bucket refills to capacity between bursts, so the burst fits only
# while burst_size <= capacity. 17 is one over 16. The burst repeats every
# 3 seconds, and each one drops that single extra request.
# fits.yaml changes only burst_size, to 16.
sim_time: 300
burst_size: 17
burst_period: 3
capacity: 16
refill_rate: 8
drain_rate: 8
buffer: 64
Cumulative requests the token bucket rejected: a staircase to 100 when each burst is one over capacity, and a flat zero when the burst fits.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 1.00, mean 50.50, median 50.50, max 100.00, σ 28.87 |
Credits left after each second, full between bursts and empty the moment a burst spends the stock.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.00, mean 8.00, median 8.00, max 16.00, σ 6.53 |
Requests the token bucket admitted this second, spiking to capacity on a burst and silent in between.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.00, mean 5.33, median 0.00, max 16.00, σ 7.54 |
| Metric | Value |
|---|---|
| burst_clipped | true |
| token_dropped | 100.00 |
| leaky_dropped | 0.00 |
# fits.yaml — the contrast. Every other knob matches clips.yaml.
# burst_size equals capacity, so nothing is dropped and the cumulative
# drops chart stays on zero.
sim_time: 300
burst_size: 16
burst_period: 3
capacity: 16
refill_rate: 8
drain_rate: 8
buffer: 64
Cumulative requests the token bucket rejected: a staircase to 100 when each burst is one over capacity, and a flat zero when the burst fits.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.00, mean 0.00, median 0.00, max 0.00, σ 0.00 |
Credits left after each second, full between bursts and empty the moment a burst spends the stock.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.00, mean 8.00, median 8.00, max 16.00, σ 6.53 |
Requests the token bucket admitted this second, spiking to capacity on a burst and silent in between.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.00, mean 5.33, median 0.00, max 16.00, σ 7.54 |
| Metric | Value |
|---|---|
| burst_clipped | false |
| token_dropped | 0.00 |
| leaky_dropped | 0.00 |
- When does a token bucket start dropping requests?
- When one burst is bigger than the credits on hand. The bucket starts full and refills to capacity before the next burst, so the line is burst_size > capacity. The default is 17 against 16: one request over. Burst Fits sets burst_size to 16, the burst equals the stock, and nothing is dropped.
- Why do one extra request and a hundred drops go together?
- Each burst is its own test of the same line, because the quiet seconds refill the bucket to full before the next one. One request over is rejected every time; one request under never is. The burst repeats every 3 seconds for 300 seconds, so that single-request gap compounds to 100 drops against 0. token_drops_total is the chart that shows it: a staircase to 100, or a flat zero.
- Why does the leaky bucket stay smooth while the token bucket spikes?
- The leaky bucket is a queue with a fixed drain. It never releases more than drain_rate requests in a second, so a burst of 17 leaves as 8, then 8, then 1, and the output line never spikes. The token bucket spends all 16 credits in the arrival second, so its output jumps to capacity and the leftover request is an error, not a wait. The drain is the comparison; the tipping point is still the credit stock.
- Where are token buckets and leaky buckets used?
- API gateways such as NGINX, Envoy, and AWS API Gateway use a token bucket so a client may burst and then receive HTTP 429 once the credits are spent. Network shapers, video pacers, and hardware that cannot absorb jitter use a leaky bucket when a smooth departure matters more than an instant answer. A token bucket can be switched to queue the overflow instead of rejecting it; that trades the error for a short wait, which is the leaky bucket's bargain.
- Does the same rate limit mean clients see the same thing?
- No. Refill and drain are both 8 per second, and a burst of 17 every 3 seconds averages under that, so both limiters keep up with the long-run load. The limit only bites inside the burst. There the token bucket turns the extra request into an error and everyone else waits zero time, while the leaky bucket turns the burst into a short queue and drops nobody. Matching the average rate does not match the burst.