Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Token
Bucket Rate Limiter.

A distributed Token Bucket rate limiter handles 400,000 req/s across 40 stateless gateways using Redis Cluster EVALSHA Lua scripts for atomic lazy refill, keeping p99 overhead <= 2 ms.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Rate Limiting Algorithms, Token Buckets & Redis Lua
Rate limiting enforces caps on request or resource consumption per caller, tenant, or endpoint over time to protect downstream capacity, ensure fair multi-tenant sharing, and blunt abuse.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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:

  1. TOCTOU Overshoot: Two gateways concurrently GET tokens=1, both allow the request, and both SET tokens=0—letting bursts bypass limits.
  2. Timer Storm: Running background cron jobs to refill 10,000,000 keys every second saturates Redis CPU with millions of wasted writes for idle keys.
Atomic Lazy Refill

40 Gateways -> Redis Cluster EVALSHA (Single Round-Trip)

Gateway Node 1Gateway Node 2Redis Shard (Key)1. EVALSHA bucket.lua (key,now_ms)2. Lazy refill + atomic decrement3. Allowed=1, remaining=04. EVALSHA bucket.lua (concurrent)5. Allowed=0 -> HTTP 429 +Retry-After

Redis executes the Lua script atomically in one RTT, eliminating TOCTOU races and background refill timers.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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 (800k GET+SET commands/s) overwhelms a single Redis thread.
  • Cascading Failure: If Redis times out and the gateway fails closed, all 400k req/s of legitimate API traffic get 500/429.
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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): Compute tokens = min(cap, tokens + (now - last) * rate / 1000) inside a single Redis Lua script and set PEXPIRE so idle keys auto-evict.
  • Redis Cluster Sharding: Hash {api_key} across 16+ Redis Cluster primaries so each shard handles ~25k req/s in < 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.
Sharded Rate-Limit Architecture

Stateless Gateways -> Local Fallback / Sharded Redis Cluster

40 Gateways400k req/s totalLocal FallbackIf Redis CB OpenRedis ClusterEVALSHA per shardOrigin APIsProtected + 429

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}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How does lazy refill inside a Redis EVALSHA Lua script solve both TOCTOU races and the 10M-key timer problem?

Recommended Learning Flow