Designing a Distributed API Rate Limiter: Token Bucket, Redis and Multi-Region Scaling

Cartoon illustrated rate limiter architecture and token bucket flow
A token bucket permits bursts up to its capacity and refills continuously; 100 tokens per minute is a sustained rate, not a strict rolling-window maximum. The gateway enforces the Redis decision.

System Design Daily · Intermediate–Advanced

A flash sale that almost takes down checkout

In this fictional but realistic scenario, Ananya runs an online shop’s checkout API. A flash sale brings thousands of customers and aggressive retrying clients. Ravi, the SRE, sees database saturation. They introduce a distributed rate limiter that protects checkout while giving legitimate customers a fair chance. The goal is to reject excess work early, not to guarantee that every admitted request succeeds.

Meet the participants: who does what?

📱 Client

Sends authenticated requests and respects retry guidance.

🚪 API gateway

Identifies the caller, selects a policy and enforces the decision.

🪣 Token bucket

Tracks available request credits and refills over time.

🗄️ Redis

Atomically updates bucket state on the owning shard.

⚙️ Backend

Processes admitted requests; still needs concurrency limits.

📊 Ravi, SRE

Monitors denials, latency, store errors and saturation.

Requirements and capacity

Support per-user and per-tenant policies, configurable burst capacity, low-latency decisions, HTTP 429 responses and explicit failure behavior. Assume 50,000 incoming requests per second at peak, 1 million active identities and 200 bytes of raw state per identity: about 200 MB before Redis object overhead, replicas and allocator overhead. At 50,000 decisions/s, a 2 ms average decision latency implies about 100 concurrent in-flight decisions by Little’s Law. Benchmark real scripts, network latency and hot keys before selecting shard counts. These are illustrative assumptions.

Choose the algorithm

AlgorithmStrengthTrade-off
Fixed windowSimple countersBoundary bursts
Sliding logExact rolling countMemory proportional to requests
Sliding counterCompact approximate rolling limitApproximation error
Token bucketControlled bursts and sustained rateNot a strict rolling-window cap
Leaky bucketSmooth outputQueueing delay or rejection

Architecture and request flow

Client → Gateway → Rate-limit service → Redis shard
              ↑           ↓
              └──── allow / deny decision
              ├── allow → Backend → Response
              └── deny  → HTTP 429 + Retry-After

The gateway, not Redis, forwards or rejects requests. A policy service distributes versioned limits; the decision service uses a stable key such as tenant:user:route-class. Authenticate before using a trusted identity, and apply a separate coarse pre-authentication limit. Never trust arbitrary forwarded IP headers.

Token bucket: the mathematics

For capacity B, refill rate r tokens/second, elapsed time Δt and request cost c, compute available = min(B, previous + r × Δt). Admit if available ≥ c and subtract c. Otherwise reject and calculate ceil((c − available)/r) seconds until enough credits exist. With B=100 and r=100/60, a full bucket permits 100 immediate requests and then approximately 1.67 requests per second. This is not a guarantee of at most 100 requests in every rolling minute.

Atomic Redis implementation

A Lua script prevents two gateways from reading the same remaining balance and both spending it. The following example assumes positive capacity, refill rate and cost, validated by the caller, and cost no greater than capacity. Use the Redis server clock, clamp backward time, and expire idle buckets only after enough time to refill.

-- KEYS[1]: bucket key; ARGV: capacity, rate/sec, cost
local cap = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2])/1000000
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or cap
local last = tonumber(s[2]) or now
now = math.max(now, last)
tokens = math.min(cap, tokens + (now-last)*rate)
local allowed = 0
local wait = 0
if tokens >= cost then
  tokens = tokens-cost
  allowed = 1
else
  wait = math.ceil((cost-tokens)/rate)
end
redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'ts', tostring(now))
redis.call('EXPIRE', KEYS[1], math.max(1, math.ceil(cap/rate)+1))
return {allowed, wait}

This is a teaching implementation, not a benchmarked production library. Test clock jumps, fractional arithmetic, policy changes and Redis failover. For strict financial quotas use an appropriately durable accounting system rather than assuming asynchronous Redis replication is lossless.

API contract and client behavior

HTTP/1.1 429 Too Many Requests
Retry-After: 3
Content-Type: application/json

{"error":"rate_limit_exceeded","retry_after_seconds":3}

Retry-After is guidance, not a reservation. Clients should back off with jitter. A rate limiter does not replace checkout idempotency; an admitted retry can still duplicate an order unless the business operation protects against it.

Scaling across regions

🌍 Central authority

Route each identity to its owning region for tighter global enforcement, at the cost of cross-region latency and availability.

⚡ Regional budgets

Allocate portions of a global budget to regions. Fast local decisions, but unused credits can be stranded.

🔄 Approximate global limit

Use local buckets with periodic coordination. Accept and quantify possible overshoot during partitions.

Shard by stable identity; a single extremely hot tenant may need hierarchical budgets or local credit leases. Do not assume Redis Cluster makes a single hot key parallel. Multi-key atomic scripts require keys in the same cluster slot. Avoid silently granting every region the entire global quota.

Failure recovery and operational decisions

FailureResponse
Redis timeoutChoose fail-open for low-risk reads or fail-closed for sensitive operations; use bounded local emergency budgets where appropriate.
Primary failoverExpect possible lost recent updates with asynchronous replication; measure overshoot.
Retry stormReturn 429 with guidance; clients back off with jitter.
Hot keyUse hierarchical quotas or allocated local credits.
Backend saturation despite limitsAdd concurrency limits, load shedding and circuit breakers.

Security, monitoring and cost

Protect Redis with private networking, authentication and TLS where supported. Avoid storing raw personal identifiers in keys or logs. Bound key cardinality to prevent memory exhaustion. Measure decision p95/p99 latency, allow/deny rates, store errors, evictions, hot keys, backend saturation and policy versions. Avoid high-cardinality per-user metric labels. Costs include memory, replication, cross-region traffic and decision-service CPU.

Test the design

Run concurrent requests against a single identity and verify token conservation; test refill boundaries, expiration, different request costs, clock regression, failover and regional partitions. Load-test realistic identity distributions rather than only uniform random traffic. Verify that denial responses do not reach checkout.

Frequently asked questions

Does a token bucket enforce an exact rolling-minute limit?

No. It permits bursts up to capacity plus credits refilled over the interval. Use a sliding log if exact rolling-window enforcement is required.

Why not use an in-memory counter?

It is useful for local protection, but independent replicas multiply the effective quota unless they coordinate or receive allocated budgets.

Should every Redis failure reject requests?

No universal policy fits every endpoint. Choose based on abuse risk, availability requirements and downstream capacity.

Interview challenge and knowledge check

Design a 100,000 request/s limiter across three regions with a strict global quota. Explain the latency and partition trade-offs. Quick check: why is Lua useful? It makes the read-refill-consume update atomic on the owning Redis server. Why does rate limiting not prevent duplicate orders? It controls admission, not business idempotency.

Key takeaways

Choose the algorithm from the actual quota semantics. Keep decisions atomic, make failure behavior explicit, and distinguish local protection from global enforcement. Monitor both the limiter and the backend.

References and related reading

Redis scripting · RFC 6585: HTTP 429 · Cloudflare rate limiting engineering · Envoy global rate limiting · Production-ready REST API design

Scroll to Top