System Designmedium•DECEMBER 2026•12 MIN
Design a Distributed Token-Bucket Rate Limiter
Enforce per-tenant RPM and TPM quotas for an AI API gateway without adding a synchronous bottleneck on every request.
token bucketsliding window logatomic lualocal quota leasedistributed systemsapi-gatewayml-systems
1. Clarifying questions & SLO contract
Before choosing Redis Lua vs local quota leasing, pin down the traffic shape and failure budget:
- Scale:
1M RPSacross100Kactive tenants,50stateless API gateway pods behind L7 load balancers. - Latency budget: Rate-limit decision must add
<1 msat p99 (<2 mseven when touching Redis). - Dimensions: Both RPM (1 token per request) and TPM (variable token cost estimated from prompt length +
max_tokens, reconciled after stream completion). - Failure mode: Fail-open on Redis outage (protect availability) with a local per-pod safety ceiling so a downstream LLM cluster never melts.
2. Back-of-envelope sizing
- State per tenant: Only 2 floats (
tokens,last_ts) =16 bytespayload (~64 byteswith Redis key overhead).1Mactive tenants fit in~64 MBof RAM — easily sharded across a small Redis cluster. - Network bottleneck:
1Msynchronous Redis calls/sec saturates gateway connection pools and adds cross-AZ p99 tail latency. Batching10tokens per local lease cuts Redis QPS by90%(100KRPCs/sec).
3. Interactive distributed rate-limiter simulator
Compare Naive GET+SET (lost updates under concurrent gateways), Atomic Redis Lua (exact quota, 1 RTT per request), and Local Quota Lease (exact quota, 0-RTT local fast path):
LOADING DISTRIBUTED RATE LIMITER SIM...
4. Deep dive: atomic Lua vs local quota leasing
- Why naive
GET+SETbreaks: Two gateway pods readremaining = 5, both compute5 - 1 = 4, and both write4. Five concurrent requests consume only 1 token. - Atomic Redis Lua (
EVALSHA): Executes lazy refill (min(cap, tokens + elapsed * rate)) and deduction atomically in Redis's single-threaded event loop. Zero race conditions, 1 RTT per request. - Local Quota Leasing (OpenAI / Stripe scale): Gateways lease small token batches (e.g.
max(10, 100ms_of_quota)) from Redis and deduct locally in RAM. When a tenant's lease runs dry, the pod requests the next lease asynchronously.
5. Failure modes & trade-offs
| Tension | Trade-off & Mitigation |
|---|---|
| Estimated vs actual TPM | Pre-deduct prompt_tokens + max_tokens before calling the GPU; refund max_tokens - actual_completion_tokens on stream close. |
| Redis shard outage | Fail-open to a local per-pod fallback token bucket (global_cap / num_pods) and emit alert telemetry. |
| Retry storms on 429 | Always return Retry-After computed as (cost - tokens) / rate plus full jitter so clients do not synchronize. |
| Hot-tenant shard skew | Shard Redis keys by {tenant_id}:{tier} and keep local lease sizes proportional to recent tenant QPS. |