Design a Distributed Rate Limiter (100K+ RPM)
Block traffic tsunamis, bots, and noisy neighbors using API Gateways, atomic Redis Lua Token Buckets, and HTTP 429 headers.
1. Traffic tsunami without a rate limiter
A scraper surge hits 40,000 RPS alongside 2,000 RPS of real buyers. With no limiter at the API Gateway, every call flows straight into Order Service and Postgres. Connection pools hit 100%, p99 passes 8 seconds, and paying users see 503 errors.
Without edge throttling, a scraper and a paying checkout compete for the same DB connections.
Read all 5 diagram steps as text
1. Traffic tsunami without a rate limiter
A scraper surge hits 40,000 RPS alongside 2,000 RPS of real buyers. With no limiter at the API Gateway, every call flows straight into Order Service and Postgres. Connection pools hit 100%, p99 passes 8 seconds, and paying users see 503 errors.
2. Gateway checks token quota atomically in Redis
Quota rules (burst = 20 tokens, refill = 10/sec per user_id) stay in local gateway RAM for zero-latency reads. On each request, the gateway runs one atomic Redis Lua script (EVALSHA) that refills elapsed tokens and subtracts 1 without race conditions.
3. Legitimate shoppers pass cleanly at 28ms p99
User uid:4821 stays under 10 req/s (with burst room up to 20 for page loads). Redis returns allowed = 1 with 19 tokens remaining. The gateway forwards the call to Order Service and sets X-RateLimit-Remaining: 19.
4. Bot drains its bucket and gets HTTP 429 at the edge
The scraper burns all 20 tokens in milliseconds. Every excess request gets rejected immediately at the API Gateway with HTTP 429 Too Many Requests and a Retry-After header. Order Service and Postgres never even see the flood.
5. Resilience when Redis itself times out
A rate limiter should never become a single point of failure. Put a strict 5ms timeout on Redis. If Redis stalls, fail-open to a coarse in-memory per-pod bucket for revenue routes like /checkout, and fail-closed on high-cost security routes like /send-otp.
Architecture Flow Summary
Save image
Why Atomic Redis Lua Scripts Are Required Across Pods
With 20 stateless gateway pods handling 100K+ RPM, separate GET and SET calls race constantly. Two pods read tokens = 1 at the same microsecond, both allow the call, and both write tokens = 0. Under heavy bursts, this race condition lets 3–10x extra traffic slip through.
Redis runs Lua scripts single-threaded and atomically. Packing refill math, quota check, token decrement, and TTL expiry into one EVALSHA call eliminates the race condition in a single network hop. Use Redis server TIME inside Lua (instead of client wall clocks) so clock skew between gateway pods never corrupts refill math.
-- KEYS[1] = "rl:user:4821", ARGV = {capacity, refill_per_sec, requested}
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local requested = tonumber(ARGV[3])
-- Use Redis server TIME to avoid clock skew across gateway pods
local t = redis.call("TIME")
local now_ms = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000)
local data = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(data[1]) or capacity
local last_ts = tonumber(data[2]) or now_ms
local elapsed_sec = math.max(0, (now_ms - last_ts) / 1000.0)
tokens = math.min(capacity, tokens + (elapsed_sec * rate))
local allowed = 0
if tokens >= requested then
tokens = tokens - requested
allowed = 1
end
local ttl = math.ceil((capacity / rate) * 2)
redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", now_ms)
redis.call("EXPIRE", KEYS[1], ttl)
return { allowed, math.floor(tokens) }Picking the Right Algorithm in Practice
Textbooks list five algorithms. Most real production teams settle on two: Token Bucket or Sliding Window Counter.
Token Bucket (Stripe, AWS API Gateway, Envoy)
Stores just two numbers per key (tokens and timestamp, ~160 bytes in Redis). Allows short user bursts up to capacity while capping the steady rate.
Fixed Window Counter (Watch the 2x Edge Bug)
Cheap to implement (INCR + EXPIRE 60), but a client can fire 100 calls at 12:00:59 and 100 more at 12:01:01, pushing 200 calls in 2 seconds.
Sliding Window Counter (Cloudflare)
Weights the previous and current window counts to approximate a rolling window. Kills boundary bursts while keeping O(1) memory per key.
Multi-Region, Clock Skew & 500K+ RPS Scaling Tricks
Never make a Mumbai gateway wait on a US-East Redis cluster (180ms RTT kills your latency SLA). Keep a Redis cluster per region with GeoDNS sticky routing, or sync coarse global counters asynchronously every 1–2 seconds.
Past 500K RPS, even local Redis calls can bottleneck on a hot key. Batch-lease 50 tokens at a time from Redis into local gateway RAM so 49 out of 50 checks happen locally in nanoseconds.
Redis Sizing for 100K+ RPM (10M Daily Users)
Protect an API doing 120,000 RPM (2,000 avg RPS, 10,000 burst RPS) across 10M daily active users using Redis Token Buckets.
- Peak checks: 10,000 EVALSHA calls/sec
- Active keys within a 5-min TTL window: 500,000 keys
- Redis Hash overhead per key: ~160 bytes
- Single Redis shard handles 60K–100K simple Lua ops/sec
Token Bucket rate limiting uses very little memory. A small 3-shard Redis cluster handles hundreds of thousands of RPM with under 1ms overhead.
Rate Limiting Algorithms Compared
Trade off burst allowance, edge accuracy, and per-key RAM.
| Algorithm | Memory / Key | Bursts | Edge Accuracy | When to Pick |
|---|---|---|---|---|
| Token Bucket | O(1) (~160 B) | Controlled bursts OK | Exact | Default pick for most APIs |
| Leaky Bucket | O(queue) | Smoothed to flat drip | Exact | Fragile downstream needing steady pace |
| Fixed Window | O(1) (~80 B) | 2x burst at edge | Loose at edges | Coarse non-critical quotas only |
| Sliding Window Log | O(N timestamps) | Zero burst over window | 100% Exact | Low-RPM strict routes (OTP, login) |
| Sliding Window Counter | O(1) (~160 B) | Smoothly damped | ~99.99% Exact | High-volume edge/WAF protection |
Quick Check
1. Your API uses a Fixed Window limit of 100 req/min. A client sends 100 calls at 12:00:58 and 100 more at 12:01:02. How many succeed in those 4 seconds?
2. Your rate-limiter Redis cluster drops packets for 30 seconds during peak dinner rush. What is the safest policy for /api/checkout vs /api/send-otp?
Cheat Sheet
When to use it
- Guard public APIs, OTP/login endpoints, LLM inference, and flash sales from bots and retry loops.
- Enforce limits at the API Gateway or edge so dropped traffic never touches app pods or DB pools.
- Return HTTP 429 with Retry-After and X-RateLimit-Remaining headers so SDKs back off cleanly.
When to skip it
- Avoid limiting consumer mobile apps purely by IP. Carrier NAT (CGNAT) puts thousands of real users behind one IPv4 address.
- Avoid Sliding Window Log (Redis Sorted Sets of every timestamp) on high-RPS endpoints because RAM grows linearly with traffic.
Common mistakes
- Doing separate GET + INCR in app code instead of an atomic Redis Lua script.
- Passing gateway pod wall-clock timestamps instead of Redis TIME, causing clock skew bugs.
- Forgetting a Fail-Open vs Fail-Closed policy when Redis degrades.
FAQ
- Where should a distributed rate limiter sit?
- Put it inside the API Gateway or edge proxy (Envoy, Kong, NGINX, Cloudflare) backed by Redis. Rejecting abusive traffic at the edge keeps bad requests off your app servers and database pools.
- Why use a Redis Lua script instead of separate GET and SET calls?
- Separate GET and SET calls from multiple gateway pods create race conditions where concurrent requests bypass the quota. One Redis Lua script (EVALSHA) runs atomically in a single round trip.
- How do you handle clock skew in a distributed rate limiter?
- Never trust individual gateway pod clocks for refill timestamps. Read Redis server TIME inside the Lua script so all pods share one monotonic time source per shard.
- What is the difference between Token Bucket and Leaky Bucket?
- Token Bucket allows short bursts up to bucket capacity while capping the average rate, which feels snappy for users. Leaky Bucket drains a FIFO queue at a strictly constant outflow rate to protect fragile downstream systems.
- Should a rate limiter fail-open or fail-closed if Redis goes down?
- Fail-open with a coarse local in-memory cap on revenue paths like browsing and checkout so buyers are not blocked. Fail-closed on security or paid paths like OTP SMS, password reset, and costly AI endpoints.