Your API is fine at 100 requests per second average. Then a deploy script somewhere retries aggressively, or a flash sale hits, and 4,000 requests land in 300 milliseconds. Your database doesn’t care about averages. It cares about right now.
That’s what rate limiting is for: a bouncer between chaos and your shared resources. But here’s the part most explanations skip: “100 requests per second” is not a specification. It’s a vibe. The algorithm you use to count decides what that sentence even means — and three common algorithms give three different answers to the same burst.
This post puts all three under fire: fixed window, sliding window, and token bucket. Correct pseudocode for each, the exact failure mode of each, and a lab where you can watch them disagree in real time.
Fixed window: the one everyone writes first
The simplest possible limiter. Pick a window — say, one minute. Keep a counter and a window start. Every request: if we’re in a new window, reset the counter; if the counter is under the limit, increment and admit; otherwise reject.
window = 60 # seconds, aligned to the clock
limit = 100
count = 0
window_start = floor(now() / window) * window
def allow():
w = floor(now() / window) * window
if w != window_start:
window_start, count = w, 0 # reset — the flaw lives here
if count < limit:
count += 1
return True
return False
O(1) memory, trivially correct-looking, and the default in half the tutorials on the internet. Its flaw is geometric: windows have edges, and the reset is amnesia. Send 100 requests at 11:00:59 and 100 more at 11:01:00 — each window counted alone looks legal, and your “100 per minute” limiter just admitted 200 requests in two seconds. That’s 2× your provisioned capacity at exactly the worst moment: the instant everyone retries at once.
Is this a theoretical nit? Do the math for your own system: if your limit is 1,000 requests per minute and your p99 latency budget assumes at most ~17 concurrent requests per second, a boundary stampede hands you 2,000 in a two-second span — 60× the steady rate your capacity planning assumed. The stampede doesn’t even need malice. Cron jobs, deploy health-checks, and retry storms all synchronize on clock boundaries naturally.
Sliding window: precise counting, no edges
The fix is to stop aligning windows to the clock and anchor the window to now. Keep the timestamps of recent admitted requests. On each request, evict everything older than N seconds, then count what’s left:
window = 60 # seconds, slides with "now"
limit = 100
log = [] # admitted request timestamps
def allow():
cutoff = now() - window
while log and log[0] <= cutoff:
log.pop(0)
if len(log) < limit:
log.append(now())
return True
return False
This is the sliding window log, and it’s exact: at every instant, it answers “how many requests were admitted in the last 60 seconds?” There is no boundary because there is no boundary — the window is a property of the current moment, not of the clock. The 11:00:59 burst is still inside the window at 11:01:00, so the second burst gets rejected. No double-spend is possible, ever.
Precision has a price: memory proportional to request volume. You’re storing a timestamp per admitted request — fine at 100/minute, a real data structure at 100k/second. In production this is a Redis sorted set per key with a Lua script: ZADD the timestamp, ZREMRANGEBYSCORE the expired entries, count the rest, EXPIRE the key — all atomically, because two app servers must not both see “99” and both admit.
There’s a cheaper middle ground worth knowing: the sliding window counter. Instead of storing every timestamp, keep the previous window’s count and blend it with the current one, weighted by how far into the current window you are:
# estimate = prev_count * (1 - elapsed/window) + current_count
It’s an approximation — it slightly over-counts near boundaries — but it’s O(1) memory and it’s what several CDNs and API gateways actually run. Exact when you need billing-grade fairness; approximate when you need cheap.
Token bucket: a different philosophy entirely
Fixed and sliding windows both count requests. Token bucket doesn’t count requests at all — it spends tokens. The bucket holds up to capacity tokens and refills at a fixed rate. Each request spends one token; no token, no entry:
capacity = 20 # max burst the bucket can absorb
refill = 10 # tokens per second — the sustained rate
tokens = 20 # bucket starts full
last = now()
def allow():
tokens = min(capacity, tokens + (now() - last) * refill)
last = now()
if tokens >= 1:
tokens -= 1
return True
return False # bucket empty
Notice what the two knobs mean, because they’re beautifully separated: capacity is how big a burst you tolerate; refill rate is your sustained throughput. A burst of 15 against a full bucket of 20? All admitted — the bucket absorbs it. A sustained 30 requests/second against a 10/second refill? Exactly 10/second get through; the rest are rejected. The bucket is a shock absorber with a governed leak.
This is the right shape when bursts are legitimate: CI runners fanning out, a deploy pushing a burst of health checks, a webhook batch. Stripe famously documents token-bucket-style limits for exactly this reason — they want your burst to succeed and your average to stay sane. The classic Redis implementation is the “cell” Lua script (its stricter cousin, GCRA, is what some gateways use under the hood). Same atomicity requirement as the sliding window: refill math and the spend must happen in one script, or two servers will double-spend the bucket.
One subtlety people get wrong: the bucket refills continuously, not in chunks. tokens + (now() - last) * refill means a request arriving 100ms after the last one finds 1 more token (at 10/s) — there’s no “refill tick” where 10 tokens drop in at once. If you implement refill as a periodic cron adding tokens, you’ve built a fixed window with extra steps, boundary stampede included.
Head to head
| Fixed window | Sliding window (log) | Token bucket | |
|---|---|---|---|
| Burst handling | 2× limit at boundaries | exact: ≤ limit per window | absorbs bursts ≤ capacity |
| Memory | O(1) | O(requests in window) | O(1) |
| Precision | coarse at edges | exact | exact for the token economy |
| Distributed | trivial counter | sorted set + Lua | counter + timestamp + Lua |
| Best for | internal tools, coarse limits | billing-adjacent, auth endpoints | bursty-but-legitimate traffic |
Under fire: the lab
Enough theory. Below is a deterministic 12-second traffic storm — the same stream, three algorithms. Teal ticks are admitted, red are rejected. The bursty pattern hides a burst pair straddling t≈5s: two bursts 0.14 seconds apart, each legal-looking in isolation.
Three experiments, in order:
- Reproduce the stampede. Fixed window, 5s window, bursty traffic, intensity 1.5×. Look at the second around t=5s: the limiter admits nearly the entire 50-request window allowance twice — once per side of the boundary. The per-second bars show it as a teal tower.
- Switch to sliding window, change nothing else. The 5.07s burst turns red. The 4.93s burst is still inside the window anchored to now, so the window is full. Same traffic, same limit — different answer.
- Switch to token bucket and drag the capacity slider. Capacity 20: the first burst drains the bucket and the tail is rejected. Capacity 5: the limiter behaves like a strict 10/s gate. Capacity is literally “how big a burst may I absorb.”
Then flip to the steady pattern and notice the punchline: under steady traffic, all three algorithms agree. Bursts are where counting philosophies diverge. If your traffic is genuinely smooth, pick the simplest one and move on.
Picking one in practice
The algorithm is maybe a third of a real rate limiter. The rest:
- Atomicity. Every algorithm here has a read-modify-write race. In a multi-instance service, the check and the increment must be one atomic step — a Redis Lua script, not two round trips. This is non-negotiable; without it you don’t have a limiter, you have a suggestion.
- Key cardinality. Limit per what? Per API key is standard; per IP invites NAT-sharing pain; per endpoint × key is the refined version. Each key is state — the sliding window log’s memory cost multiplies by your key count.
- Headers and status codes. Return
429 Too Many Requestswith aRetry-Afterheader, and ideallyX-RateLimit-Limit/X-RateLimit-Remainingon successes. Clients can’t back off politely if you don’t tell them the rules. - Fail open or fail closed? If Redis is down, do you admit everyone (fail open — availability) or reject everyone (fail closed — protection)? There is no universally right answer; there’s only the answer you chose deliberately and wrote down. Most public APIs fail open with alerting. Most auth endpoints fail closed.
- Fixed window’s honest niche. It’s not always wrong. For coarse internal limits — “this batch job may poll at most 1,000 times an hour” — the boundary stampede is harmless and the O(1) simplicity is worth it. The mistake is using it where the boundary matters and not knowing.
The durable idea
“N requests per T seconds” is underspecified — the algorithm is the spec. Fixed window says “N per clock-aligned T, edges be damned.” Sliding window says “N per trailing T, exactly.” Token bucket says “spend N tokens per T, burst if you’ve saved up.” Once you’ve watched a boundary stampede happen on a timeline, you can’t unsee it — and you’ll never again accept a rate limit described without its counting rule.