HLDReliability7 min read

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.

Kshitij SinghKshitij SinghUpdated 2026-12-03
Animated distributed rate limiter system architecture diagram — 1. Traffic tsunami without a rate limiterPictorial system design diagram illustrating traffic spikes hitting an API Gateway rate limiter backed by Redis Token Bucket Lua scripts, protecting downstream microservices and databases.. 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.CLIENT TRAFFICRATE LIMITER TIER (EDGE / GW)PROTECTED BACKENDNormal 2K/sFlood 40K/sEVALSHA LuaLocal RulesAllowed 200Safe WritesLegit Users2K Normal RPSBot / Spike40K Scraper RPS40K RPS FLOODAPI GatewayEnvoy / Kong ProxyRedis BucketAtomic Lua · 0.6msRules StoreConfig · Cached LocalOrder ServiceProtected Go FleetCPU 100%Primary DBSteady Write IOPSPOOL EXHAUSTEDCheckout40K Flood!Overload503 Timeout
Animated distributed rate limiter system architecture diagram — 1. Traffic tsunami without a rate limiter
1 / 5

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.

Inbound Traffic
42,000 RPS
21x Normal
Legit User p99
8,400 ms
503 Failures
DB Connections
500 / 500
Saturated
Error Rate
68%
Outage
Read all 5 diagram steps as text
  1. 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. 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. 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. 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. 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
Distributed rate limiter architecture flow infographic showing legitimate users (2K RPS) and bot spike (40K RPS) hitting an API Gateway backed by a Redis Token Bucket Lua script (0.6ms), passing allowed 200 OK traffic to Order Service and PostgreSQL while blocking bots with HTTP 429 and Retry-After
Distributed API Gateway rate limiter using atomic Redis Token Bucket Lua scripts to block 40K RPS bot floods with HTTP 429.

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.

Atomic Token Bucket script for Redis (EVALSHA)lua
-- 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
Active Redis RAM
500,000 keys × 160 bytes
~80 MB (10M all at once is still only 1.6 GB)
Redis Shards Needed
10,000 ops/s ÷ 70,000 ops/s per shard
1 shard (+ replica); 3 shards for safety
VPC Network Traffic
10,000 ops/s × 180 bytes round trip
~1.8 MB/s (~14.4 Mbps)

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.

AlgorithmMemory / KeyBurstsEdge AccuracyWhen to Pick
Token BucketO(1) (~160 B)Controlled bursts OKExactDefault pick for most APIs
Leaky BucketO(queue)Smoothed to flat dripExactFragile downstream needing steady pace
Fixed WindowO(1) (~80 B)2x burst at edgeLoose at edgesCoarse non-critical quotas only
Sliding Window LogO(N timestamps)Zero burst over window100% ExactLow-RPM strict routes (OTP, login)
Sliding Window CounterO(1) (~160 B)Smoothly damped~99.99% ExactHigh-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.
Redis Lua hop
0.5 – 1.5 ms
Gateway Redis timeout
3 – 5 ms cap
Token Bucket RAM
~160 bytes/key
Throttle HTTP code
429 Too Many Req
1 Redis shard cap
60K – 100K ops/s
Fixed Window bug
Up to 2x burst

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.