To keep the architecture evolvable without sacrificing reliability, replace GET-then-SET with a single-round-trip Redis Lua script (EVALSHA) using lazy refill, shard across Redis Cluster by api_key, and fail-open with a local fallback limiter if Redis partitions.
TL;DR30-second simplified summary▾
Core Mechanics: Across 40 stateless API gateway nodes serving 400,000 req/s and 10M active API keys (2M hot keys), per-node in-memory counters allow a client to exceed its limit by 40× via round-robin routing.
Visual & Structural Flow: Depicts 40 Gateways -> Redis Cluster EVALSHA (Single Round-Trip) (Gateway Node 1 -> Gateway Node 2 -> Redis Shard (Key)); Stateless Gateways -> Local Fallback / Sharded Redis Cluster (40 Gateways -> Local Fallback -> Redis Cluster -> Origin APIs).
Trade-Offs & Production: A naive implementation uses GET + SET against a single Redis instance: Race Condition: Non-atomic read-modify-write overshoots burst limits under concurrent requests. Production rate limiters (Stripe, Envoy, Kong) combine three techniques: Atomic Lazy Refill (EVALSHA): Compute tokens = min(cap, tokens + (now - last) * rate / 1000).
Failure Modes & Application: Distributed token buckets are the standard throttling primitive across API infrastructure: Multi-Tenant API Gateways: Enforcing per-key burst and sustained quotas with 429 + Retry-After.
Why distributed Token Bucket rate limiting matters at 400k req/s.
Why this matters: The mechanism: understand how Why distributed Token Bucket rate limiting matters at 400k req/s works from first principles.
Think of Why distributed Token Bucket rate limiting matters at 400k req/s as the intuition layer for Design a Token Bucket Rate Limiter: The mechanism: understand how Why distributed Token Bucket rate limiting matters at 400k req/s works from first principles.
Across 40 stateless API gateway nodes serving 400,000 req/s and 10M active API keys (2M hot keys), per-node in-memory counters allow a client to exceed its limit by 40× via round-robin routing. A distributed Token Bucket must enforce burst capacity B and sustained rate R accurately across all nodes within a <= 2 ms p99 latency budget.
What happens with TOCTOU races and background refill timers.
Why this matters: The problem: see what breaks without What happens with TOCTOU races and background refill timers under real concurrency or scale.
Two classic bugs break distributed rate limiters at scale:
- TOCTOU Overshoot: Two gateways concurrently
GETtokens=1, both allow the request, and bothSETtokens=0—letting bursts bypass limits. - Timer Storm: Running background cron jobs to refill
10,000,000keys every second saturates Redis CPU with millions of wasted writes for idle keys.
40 Gateways -> Redis Cluster EVALSHA (Single Round-Trip)
Redis executes the Lua script atomically in one RTT, eliminating TOCTOU races and background refill timers.
- Problem
- How to implement Design a Token Bucket Rate Limiter without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- To keep the architecture evolvable without sacrificing reliability, replace GET-then-SET with a single-round-trip Redis Lua script (EVALSHA) using lazy refill, shard across Redis Cluster by api_key, and fail-open with a local fallback limiter if Redis partitions.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Design a Token Bucket Rate Limiter experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive solution (and why GET/SET or single-node Redis breaks).
Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.
A naive implementation uses GET + SET against a single Redis instance:
- Race Condition: Non-atomic read-modify-write overshoots burst limits under concurrent requests.
- Single-Core Saturation: 400k req/s (
800kGET+SET commands/s) overwhelms a single Redis thread. - Cascading Failure: If Redis times out and the gateway fails closed, all
400k req/sof legitimate API traffic get500/429.
Enterprise solution: Sharded Redis Cluster + EVALSHA + Local Fallback.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Production rate limiters (Stripe, Envoy, Kong) combine three techniques:
- Atomic Lazy Refill (
EVALSHA): Computetokens = min(cap, tokens + (now - last) * rate / 1000)inside a single Redis Lua script and setPEXPIREso idle keys auto-evict. - Redis Cluster Sharding: Hash
{api_key}across 16+ Redis Cluster primaries so each shard handles~25k req/sin< 1 ms. - Fail-Open Local Fallback: If a Redis shard is unreachable (circuit breaker open), fall back to an in-memory local token bucket (
cap / N_nodes) so origin services remain protected without a total outage.
Stateless Gateways -> Local Fallback / Sharded Redis Cluster
1.EVALSHA Script: Pre-cached Lua executes lazy refill + decrement atomically in 1 RTT.
2.TTL Auto-Eviction: Sets key TTL to full-refill window so 10M idle keys don't leak RAM.
3.Cluster Sharding: Distributes 400k req/s across 16+ shards to avoid single-thread CPU cap.
4.429 Headers: Returns X-RateLimit-Remaining and Retry-After for well-behaved clients.
Sharded EVALSHA keeps hot-path overhead <= 2 ms p99 while local fallback buckets prevent Redis outages from taking down the API.
-- Redis EVALSHA atomic lazy-refill Token Bucket
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate_per_ms = tonumber(ARGV[2])
local now_ms = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])
local data = redis.call('HMGET', key, 'tokens', 'last_ms')
local tokens = tonumber(data[1])
local last_ms = tonumber(data[2])
if tokens == nil then
tokens = capacity
last_ms = now_ms
else
local elapsed = math.max(0, now_ms - last_ms)
tokens = math.min(capacity, tokens + elapsed * refill_rate_per_ms)
last_ms = now_ms
end
local allowed = 0
local retry_after_ms = 0
if tokens >= requested then
tokens = tokens - requested
allowed = 1
else
retry_after_ms = math.ceil((requested - tokens) / refill_rate_per_ms)
end
local ttl_ms = math.ceil(capacity / refill_rate_per_ms) * 2
redis.call('HMSET', key, 'tokens', tokens, 'last_ms', last_ms)
redis.call('PEXPIRE', key, ttl_ms)
return {allowed, math.floor(tokens), retry_after_ms}
Where Distributed Token Buckets are used in System Design.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Distributed token buckets are the standard throttling primitive across API infrastructure:
- Multi-Tenant API Gateways: Enforcing per-key burst and sustained quotas with
429+Retry-After. - LLM Token & RPM Limiters: Throttling both requests/min and tokens/min by passing
requested = estimated_tokens. - Downstream Partner Protection: Capping outbound webhook or PSP calls to stay within third-party SLAs.
Practice: Make the trade-off yourself.
How does lazy refill inside a Redis EVALSHA Lua script solve both TOCTOU races and the 10M-key timer problem?