skip to content
jaeaeichsysdes

Design a Distributed Rate Limiter

End-to-end architecture for a 1M peak RPS rate limiter across 500 stateless API gateways: decoupled rule control plane, atomic Lua token buckets on 20 Redis shards, and fail-open/closed policies.

The whiteboard

Toggle between the control plane, data plane, and Redis outage policy below — building on Rate Limiting and Sharding & Hotkeys.

whiteboard · press 1–4 to trace flows

CONTROL PLANE (RULES · ~10 MB)DATA PLANE (1M PEAK RPS · <5ms)OUTCOME & POLICYcreatewritesyncpoll every ~5s (~10 MB)reqLua evaltimeoutallow (200) / fail-open429 / fail-closed (auth/pay)Admin / CIPOST /rulesdynamic configRule Servicevalidate & saveno app deployRules DB100K rulessource of truthRules Cache~10 MB snapshotpolled by gatewaysClients100M DAU1M peak RPSAPI Gateway500 stateless nodeslocal rules RAMRedis Cluster20 shards · Luakey: rule:entityUpstream App200 OKallow / fail-open429 RejectedRetry-Afteror fail-closed

Full rate limiter: rules propagate asynchronously to gateway RAM; live 1M RPS checks execute atomic Lua token buckets on 20 Redis shards.Enforcing at the API Gateway avoids app redeploys and sidecar sprawl while keeping overhead under 5ms.

Scale & APIs

1M RPS

peak traffic · 20 Redis shards

< 5ms

added gateway latency overhead

~10 MB

100K rules cached in gateway RAM

Entity: Rule { id, scope (url | user | api_key), capacity T, refillRate k }
POST /rules
body: { "on": "api_key", "capacity": 100, "refillRate": 10 }
-> 201 Created { "ruleId": "rl_94" }
GET /request/:url
-> 200 OK
-> 429 Too Many Requests
Retry-After: 2
X-RateLimit-Remaining: 0

How it works

1. Gateway placement & decoupled control plane

  • Single edge choke point: Enforcing at 500 stateless API Gateways avoids redeploying app services on every limit tweak and skips sidecar fleet management.
  • Zero-hop rule lookup: 100K rules occupy only ~10 MB, so gateways poll Rules Cache into local RAM every few seconds with zero control-plane latency on the hot path.

2. Token Bucket in O(1) memory

  • Burst-friendly & compact: Token Bucket absorbs legitimate bursts up to T, refills at rate k, and stores just two numbers ({ quota, last_time }) per key in O(1) space.
  • Beats alternatives at 1M RPS: Fixed windows allow 2x boundary spikes, while Sliding Window Logs (O(log N) sorted sets) blow up Redis memory and CPU at 1M RPS.

3. Atomic Lua script across 20 Redis shards

  • No lost updates: Each gateway invokes one Redis Lua script (HMGET → compute refill → HMSET + EXPIRE), executing atomically on Redis’s single thread across 500 concurrent gateways.
  • Composite shard key: Keying Redis by rule_id:entity_id (e.g. rule_login:user_42) spreads a single popular rule evenly across all 20 shards (~50K ops/sec each).

4. Failure policy: fail open vs fail closed

  • Generic traffic → fail open: If a Redis shard times out, allow catalog/read traffic so a cache blip never causes a site-wide outage.
  • Sensitive routes → fail closed: On /login, password reset, and payments, reject or enforce a strict local per-gateway cap (with a circuit breaker on dead shards) to stop credential stuffing.

lesson

Interview differentiator: At 1M RPS, even a 1ms Redis round-trip per request burns massive network budget. Offer local token leasing (gateways lease 10–50 tokens at a time from Redis) to cut Redis QPS 10x in exchange for tiny burst slack.

Check yourself

interactive · stress-test this architecture against common interview probes

01 · Sharding key hotkey trap

20 Redis shards · 300k RPS on 1 rule · 100k users

You shard your 20-node Redis cluster on rule_id alone. Traffic spikes to 300k RPS on the global 'api_read' rule across 100k different users. What happens?

02 · Redis shard outage during peak traffic

availability > consistency · security · 30s Redis blip

Shard #7 of your Redis cluster dies for 30 seconds. How should the 500 API gateways respond for product catalog browsing vs the /login endpoint?

03 · Why Lua instead of GET + SET from the gateway?

500 gateways · 1 token left · read-modify-write

Two API gateways receive requests for the same user at the exact same millisecond when 1 token remains. Why does running HMGET then HMSET from the gateway fail?

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