Rate Limiting
Deriving production rate limiters from first principles: why naive counters allow 2× boundary spikes, how token buckets and sliding counters bound bursts, and how Redis Lua fixes distributed race conditions.
Every service has a hard ceiling on CPU, database connections, and downstream quotas. Without a gate at the edge, one buggy retry loop or credential-stuffing bot can exhaust worker pools and knock out every healthy tenant.
A rate limiter turns unbounded traffic into explicit backpressure:
allowed requests proceed, excess requests receive HTTP 429 Too Many Requests
with a Retry-After header.
Why naive counters break
The simplest limiter stores a single counter per user per second:
INCR user:42:1700000001. If the count exceeds 5, reject.
That works until traffic clusters near a window edge. Suppose a client sends
5 requests at 0.9s and 5 more at 1.0s. Both windows stay at 5/5, yet
your backend just absorbed 10 requests in 100ms — a 2× boundary spike.
Try it yourself below. The lab starts with a 2× boundary spike in fixed
window mode (5 at 0.5s, 5 at 1.0s). Switch to token bucket or
sliding counter, or fire your own bursts across the 1.0s line.
interactive · switch algorithms or fire bursts across the 1.0s boundary
2× BOUNDARY SPIKE · 10 reqs passed in 1s (limit 5)switch to sliding counter to stop the spike
The four core algorithms
Every production rate limiter is one of four mechanisms trading off memory per key, burst tolerance, and boundary accuracy:
- Fixed Window Counter: bucket time by
floor(now / window). Cost is one integer per key (O(1)RAM), but traffic straddling a boundary can hit 2× the configured rate. - Sliding Window Log: store every allowed request timestamp in a sorted
set (e.g. Redis
ZSET), prune entries older thannow - window, and check cardinality. Exact to the millisecond, but memory scales linearly with request volume (O(R)per user). - Sliding Window Counter: keep only the previous and current fixed
window counts and compute a weighted estimate:
estimate = prevCount × (1 − elapsed / window) + currCount. UsesO(1)memory like Fixed Window while eliminating the 2× boundary spike (Cloudflare measured <0.003% error vs an exact log). - Token Bucket / Leaky Bucket: a bucket holds up to
Btokens and refills atRtokens/sec. Each request consumes 1 token (orNtokens for weighted cost like LLM input/output tokens). Allows short bursts up toBwhile enforcing long-term average rateR. A Leaky Bucket is the dual: a fixed-size FIFO queue drained at a constant rateR, smoothing bursts into a flat outflow.
O(1)
memory for token bucket & sliding counter
2×
worst-case burst in fixed window
429
HTTP status + Retry-After header
Distributed trap: the read-modify-write race
Moving a rate limiter from one server’s RAM to a fleet of 20 API gateways requires shared state (typically Redis). A naive implementation does two network round-trips:
Gateway A: GET user:42 → 4 (under limit 5)Gateway B: GET user:42 → 4 (under limit 5)Gateway A: SET user:42 5 (ALLOW)Gateway B: SET user:42 5 (ALLOW — limit silently exceeded!)Under concurrency, two gateways read the same stale count and both admit the request.
The fix: execute the check, refill, and decrement inside a single Redis
Lua script (or atomic EVALSHA). Because Redis executes Lua scripts
single-threaded and atomically, no other gateway can interleave between read
and write, and the whole check completes in one network round-trip.
note
If your Redis cluster itself degrades, decide explicitly between fail-open (allow traffic so a cache blip does not become a global outage) and fail-closed (reject traffic on auth/payment endpoints to stop brute-force attacks). Pair fail-open with a local in-memory fallback limiter and a circuit breaker so a slow Redis never stalls gateway threads.
Production trade-offs
| Algorithm | Memory / key | Burst behavior | Best fit |
|---|---|---|---|
| Fixed Window | O(1) — 1 int | Allows 2× at boundary | Coarse per-day billing caps |
| Token Bucket | O(1) — 2 numbers | Controlled burst up to B |
Public REST APIs, LLM token quotas |
| Leaky Bucket | O(B) queue | Strictly flat outflow | Protecting fragile downstream DBs |
| Sliding Counter | O(1) — 2 ints | Smooth rolling cap | Strict QPS enforcement at scale |
| Sliding Log | O(R) timestamps | Exact rolling cap | Low-volume sensitive endpoints (login) |
- Avoid a Redis SPOF: shard rate-limit keys across a Redis Cluster
by
tenant_idorip, and use local batching (leasing 10–50 tokens per gateway) when a single hot tenant exceeds one Redis shard’s throughput. - Avoid clock skew across gateways: compute timestamps inside
Redis (
redis.call("TIME")) rather than trusting each gateway’s wall clock.
Where this shows up in system design
- API Gateway (Cloudflare / Envoy)Edge per-IP and per-API-key Sliding Window Counters shed abusive traffic before it reaches origin microservices.
- Stripe APIMulti-layered Token Buckets enforce per-account read/write QPS, concurrent request limits, and load shedding under spikes.
- Login & OTP Brute-Force ProtectionStrict Sliding Window Log or Counter per `(account, IP)` caps failed attempts to 5 per 15 minutes and fails closed.
- LLM Token Quotas (RPM + TPM)Weighted Token Buckets deduct prompt + completion tokens rather than 1 per request, reconciling actual usage after streaming ends.
Check yourself: system design scenarios
interactive · pick an architecture for each prompt to test your intuition
1. Public developer REST API (100 req/s steady, short bursts ok)
burst-friendly · O(1) memory · 40 gateways
Developers run CI scripts that fire 20 requests in 100ms, then stay quiet for a second. You want to allow short bursts without punishing legitimate scripts, while capping sustained load at 100 req/s per API key across 40 gateways.
Select an option to check the trade-off.
2. Login endpoint brute-force defense
strict cap · tiny count/key · security critical
Attackers try credential stuffing against `/v1/login`. You must strictly enforce at most 5 failed attempts per account per 15 minutes with zero 2× boundary loopholes. Volume per key is tiny (at most 5 entries).
Select an option to check the trade-off.
3. LLM API with 60 RPM and 100,000 tokens/min per tenant
variable cost · weighted deduction · multi-dimension
A single prompt can cost 200 tokens or 30,000 tokens. Counting every HTTP request as 1 lets a caller saturate GPU inference with huge prompts while staying under 60 requests/min.
Select an option to check the trade-off.
backpressuretraffic
Signaling upstream producers to slow down or shed load when downstream consumers cannot keep up, preventing unbounded queues.
circuit breakerresilience
A state machine (closed, open, half-open) that trips to fail fast when a downstream dependency is failing, avoiding cascading stalls.
SPOFreliability
Single Point of Failure: any component whose failure stops the whole system because there is no independent fallback.
clock skewdistributed systems
Difference between physical clocks on separate machines, or a local clock stepping backward during NTP synchronization.