Skip to main content
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 RPS across 100K active tenants, 50 stateless API gateway pods behind L7 load balancers.
  • Latency budget: Rate-limit decision must add <1 ms at p99 (<2 ms even 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 bytes payload (~64 bytes with Redis key overhead). 1M active tenants fit in ~64 MB of RAM — easily sharded across a small Redis cluster.
  • Network bottleneck: 1M synchronous Redis calls/sec saturates gateway connection pools and adds cross-AZ p99 tail latency. Batching 10 tokens per local lease cuts Redis QPS by 90% (100K RPCs/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

  1. Why naive GET + SET breaks: Two gateway pods read remaining = 5, both compute 5 - 1 = 4, and both write 4. Five concurrent requests consume only 1 token.
  2. 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.
  3. 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

TensionTrade-off & Mitigation
Estimated vs actual TPMPre-deduct prompt_tokens + max_tokens before calling the GPU; refund max_tokens - actual_completion_tokens on stream close.
Redis shard outageFail-open to a local per-pod fallback token bucket (global_cap / num_pods) and emit alert telemetry.
Retry storms on 429Always return Retry-After computed as (cost - tokens) / rate plus full jitter so clients do not synchronize.
Hot-tenant shard skewShard Redis keys by {tenant_id}:{tier} and keep local lease sizes proportional to recent tenant QPS.

Related Lab Entries