Algorithms · Safety nets

Token bucket rate limiting

Stripe’s token bucket: saying “slow down” politely. A bucket of tokens that refills over time decides who gets through.

The problem

Picture Stripe's API on a busy day. Thousands of programs are asking it to charge cards, and one of them has a bug that loops and fires requests as fast as it can. Without protection, that single user could slow things down for everyone else.

Stripe's 2017 post, "Scaling your API with rate limiters", describes the fix: a rate limiter that gives each user a budget. Go over it and the API refuses with an HTTP 429 ("too many requests") instead of melting.

The obvious way

Count requests in a fixed window: allow 10 per 5 seconds, and reset the count to zero when a new window starts. It's simple, but it has a hole at the edges. Send 10 requests in the last instant of one window and 10 more in the first instant of the next. The counter never complains, yet 20 requests landed within a fraction of a second, double the limit. Stripe's post points out this same weakness.

The clever idea

Give every user a bucket of tokens. Think of a arcade with a jar of tokens: each game costs one token, and an attendant drops new tokens in at a steady pace. The jar can only hold so many. Empty jar? You wait.

That is the token bucket. It has a maximum size, refills at a steady rate, and every request spends one token. Stripe described building it on Redis, a fast shared store. Because a full bucket can be spent all at once, it allows a short burst, while the refill rate enforces the average.

How the code does it

Both limiters see the same traffic from these two lines: a burst straddling the 5-second mark, then a hammering spree. The fixed window in its counting lines files each request into window 0 (0–5s) or window 1 (5–10s). Each window has its own count, so both bursts of 10 pass, giving 20 in 0.2 seconds.

The bucket works differently. The refill line adds (t - last) * RATE tokens, so after 0.2 seconds it has gained only 0.4 of a token. The first burst spends all 10 tokens, and the second finds an almost empty jar. Compare the two bar charts: the window has two tall bars side by side, while the bucket has one. During the hammering at 30s, the bucket also keeps letting a request through whenever a token trickles in.

Trade-offs

A token bucket needs a little state per user (tokens and last-seen time) that must be shared across every server, which is why Stripe used Redis. It also allows bursts by design, so skip it if you need a hard "never more than N in any instant" rule, or if the extra state isn't worth it for a tiny internal tool, where a plain counter may be fine.

Where else you'll see it

Any API that returns 429s is likely using a token bucket or a close cousin. Network routers use the same idea to shape traffic, and game servers use it to stop spammy clients.

The bucket is empty after the 4.9s burst. At 5.1s, 10 more requests arrive. How many pass?

  • None, only 0.4 tokens refilled
  • All 10, a new window started
  • Exactly 2, the refill rate
Show the answer

None, only 0.4 tokens refilled. Refill is 2 tokens/sec × 0.2s = 0.4 tokens, which is less than the 1 token a request needs. Only a fixed window would reset and let all 10 through.

Change it and see
  • Change CAP to 5 and rerun
  • Set RATE to 10 and compare
  • Move the second burst to 9.9

The code

Python, with what each line means beside it. It compares the clever way with a fixed window counter.

CAP, RATE = 10, 2 # bucket size, tokens per secondBucket holds 10 tokens, refills 2 per second
LIMIT, WINDOW = 10, 5 # fixed window: 10 per 5 secondsWindow allows 10 requests per 5 seconds
requests = [4.9] * 10 + [5.1] * 10 # burst across a window edgeTen requests at 4.9s, ten more at 5.1s
requests += [30 + i * 0.05 for i in range(40)] # then 2s of hammeringThen 40 requests packed into two seconds
def token_bucket(times):Define the token bucket limiter
tokens, last, ok = CAP, 0, []Start with a full bucket, nothing allowed yet
for t in times:Handle each request in time order
tokens = min(CAP, tokens + (t - last) * RATE)Add tokens for time passed, up to the cap
last = tRemember when we last looked
if tokens >= 1:If at least one token is left
tokens -= 1Spend one token
ok.append(t)Let this request through
return okReturn the allowed requests
def fixed_window(times):Define the fixed window limiter
counts, ok = {}, []Keep a count per window
for t in times:Handle each request in order
w = int(t // WINDOW)Work out which window it falls in
if counts.get(w, 0) < LIMIT:If that window still has room
counts[w] = counts.get(w, 0) + 1Count it in this window
ok.append(t)Let this request through
return okReturn the allowed requests
def per_second(ok):Define a per-second tally
return [sum(1 for t in ok if int(t) == s) for s in range(60)]Count allowed requests in each of 60 seconds
bucket, window = token_bucket(requests), fixed_window(requests)Run both limiters on the same traffic
show(per_second(window), "fixed window: allowed per second")Draw the fixed window's bars
show(per_second(bucket), "token bucket: allowed per second")Draw the token bucket's bars
edge = lambda ok: sum(1 for t in ok if 4.9 <= t <= 5.1)Count what slipped through around the edge
print("Let through between 4.9s and 5.1s:")Announce the comparison
print(" fixed window:", edge(window))Print the fixed window's count
print(" token bucket:", edge(bucket))Print the token bucket's count

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on safety nets