skip to content
jaeaeichsysdes

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

clock1.0s
allowed10
429 rejected0
peak / 1s10 / 5
window 1 · 0.0–1.0s
window 2 · 1.0–2.0s
0.0s0.5s1.0s boundary1.5s2.0s

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:

  1. 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.
  2. Sliding Window Log: store every allowed request timestamp in a sorted set (e.g. Redis ZSET), prune entries older than now - window, and check cardinality. Exact to the millisecond, but memory scales linearly with request volume (O(R) per user).
  3. Sliding Window Counter: keep only the previous and current fixed window counts and compute a weighted estimate: estimate = prevCount × (1 − elapsed / window) + currCount. Uses O(1) memory like Fixed Window while eliminating the 2× boundary spike (Cloudflare measured <0.003% error vs an exact log).
  4. Token Bucket / Leaky Bucket: a bucket holds up to B tokens and refills at R tokens/sec. Each request consumes 1 token (or N tokens for weighted cost like LLM input/output tokens). Allows short bursts up to B while enforcing long-term average rate R. A Leaky Bucket is the dual: a fixed-size FIFO queue drained at a constant rate R, 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_id or ip, 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.

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).

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.

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme