Rate-Limiting Service with Token Buckets at Global Scale
System DesignModel answerLast updated
Design a distributed rate limiter that enforces per-user request quotas across multiple regions with low latency and no single point of failure.
Scenario
Your team operates a public API gateway that serves traffic from clients around the world. Product wants to enforce per-user request quotas — for example, "a Free-tier user may make at most 100 requests per minute" — to protect backend services and enforce monetization tiers. You need to design the rate-limiting service that sits in the request path to make the allow/deny decision.
The gateway runs on dozens of application servers spread across several geographic regions. Any rate-limiting solution must work correctly even when many servers handle requests from the same user concurrently.
Functional Requirements
- Enforce a configurable request quota per user ID (requests per time window).
- Expose a check interface the gateway calls on every incoming request.
- Support multiple user tiers, each with its own quota (e.g., Free, Pro, Enterprise).
Non-Functional Requirements
- Latency: the rate-check call should add under 10 ms to the request path (p99).
- Availability: a failure in the rate-limiting layer must not take down the main API.
- Accuracy: small, bounded overshoot is tolerable; large-scale limit violations are not.
What Your Design Should Cover
- API — what does the interface between the gateway and the rate limiter look like?
- Storage strategy — centralized, local, or hybrid? Justify your choice.
- State management — how is the token-bucket state (token count and last-refill timestamp) stored and updated?
- Concurrency — how do you prevent race conditions when multiple servers update the same bucket simultaneously?
- Fault tolerance — what happens when a storage node or an entire region is unavailable?
Feel free to ask clarifying questions before diving in. State your assumptions, and call out the trade-offs in your choices.
Hints
Hint 1
Start by sizing the problem: estimate requests per second, number of active users, and bucket state size. These numbers dictate whether a single Redis node, a cluster, or a more complex topology is needed.
Hint 2
Think through the read-modify-write race condition carefully. What primitive guarantees atomicity for a multi-field update in Redis without introducing lock contention on hot keys?
Hint 3
Global consistency (one shared counter across all regions) and low latency are fundamentally at odds. Enumerate the options — home-region routing, split quotas, async gossip — and state the accuracy bound each one gives you.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and Size the Problem
Before drawing any boxes, pin down the numbers that constrain every later decision.
- Traffic: ~1 M requests/sec at global peak, roughly 200 k RPS per region across five regions.
- Users: ~50 M active user IDs. Tiers: Free (100 req/min), Pro (1 000 req/min), Enterprise (custom, up to ~100 k/min).
- Latency budget: p99 < 10 ms for the rate check; realistically target 1–2 ms when the rate-limit store is co-located in the same region.
- Accuracy: a few percent overshoot is acceptable. Losing availability on the main API is not.
- Scope clarification to ask: is the quota global (shared across all regions) or per-region? Global is the harder case. Design for global, then note the simplification if per-region is acceptable.
Back-of-envelope: each bucket holds a token count (float) and a last-refill timestamp (int64), about 100 bytes including key overhead. 50 M × 100 B ≈ 5 GB, which fits comfortably in a sharded Redis cluster. A Redis shard handles roughly 100 k simple ops/sec, so 200 k RPS per region needs about four to six primaries — fewer if local token leasing is used.
2. API Interface
Expose a lightweight gRPC call from the gateway to the rate-limit service (or embed it as an in-process library):
CheckQuota(user_id: string, resource: string, cost: int = 1)
→ { allowed: bool, remaining: int, retry_after_ms: int }
- The gateway translates
allowed = falseinto an HTTP 429 withRetry-AfterandX-RateLimit-*headers. cost > 1lets expensive endpoints consume multiple tokens per call.
A separate admin interface manages policies:
PUT /policies/{tier} { capacity, refill_rate_per_sec }
PUT /overrides/{user_id} { capacity, refill_rate_per_sec, expires_at }
3. Storage Strategy: Hybrid
Pure local (in-process counters): simple and zero-latency, but with N gateway servers each running its own bucket, users can exceed the limit by a factor of N. Load balancers don't pin users to a single server, so this doesn't work.
Pure centralized across regions: accurate, but a cross-region round trip is 70–150 ms, which blows the latency budget immediately.
Hybrid (recommended): one Redis cluster per region is the authoritative store for bucket state in that region. Each gateway maintains a small in-memory cache for policies (which change rarely) and optionally leases a batch of tokens for high-volume users to reduce round trips.
Data split:
- Policy store (Postgres or etcd, replicated): tier → capacity and refill rate, user → tier, and per-user overrides. Gateways cache this in memory and refresh it on change events.
- Bucket state (Redis hash, ephemeral): key
rl:{user_id}:{resource}, fieldstokensandts_ms. Set TTL to roughly2 × capacity / refill_rate; an expired bucket is simply treated as full, which is safe.
4. Atomic State Updates: Lua Script on Redis
The naive GET → compute → SET sequence is a read-modify-write race. Two servers reading the same stale value both see one token remaining and both allow the request.
The fix is to run the entire operation as a server-side Lua script, which Redis executes atomically on a single shard:
-- KEYS[1] = bucket key
-- ARGV: capacity, refill_rate_per_ms, cost, ttl_ms
local cap = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local ttl = tonumber(ARGV[4])
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000) -- milliseconds, Redis clock
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
-- lazy refill: add tokens proportional to elapsed time
tokens = math.min(cap, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], ttl)
return { allowed, math.floor(tokens) }
Key design choices to call out explicitly:
- Lazy refill — no background timer. Tokens are computed from elapsed time on each access, keeping cost O(1) per check and eliminating any scheduler dependency.
- Use the Redis clock, not the application server clock. Gateway clocks drift relative to each other. The Redis clock is consistent for all operations on the same shard.
- Pass capacity and rate as arguments rather than storing them in the hash. A policy change then takes effect on the very next request with no migration step.
- Why not Redlock? A distributed lock adds two or more round trips and creates contention on hot keys. Single-shard atomicity via Lua is strictly better here.
5. Handling Hot Keys: Local Token Leasing
For high-volume Enterprise users, a Redis round trip on every request can still be a bottleneck. The gateway can lease a batch of tokens — say, 10 % of the user's capacity — in one Lua call, serve requests locally from that lease, and asynchronously refresh when the lease runs low.
The trade-off: unused tokens on one gateway are temporarily unavailable to others. Maximum overshoot is bounded by num_gateways × lease_size. Keep leases small (or disabled) for Free-tier users where accuracy matters relatively more per request.
6. Global Limits Across Regions
Three options, each with a different accuracy/latency trade-off:
- Home-region routing: each user's bucket lives in one designated region; other regions make a cross-region call for that user. Accurate, but adds 70–150 ms latency for non-home traffic. Only viable for low-volume APIs.
- Split quotas: divide the limit across regions in proportion to observed traffic, rebalancing every few seconds. Checks remain local, but accuracy suffers when a user's traffic shifts regions faster than the rebalance interval.
- Local buckets with async gossip (recommended): each region enforces a local bucket. Regions exchange consumption counts roughly every one second and subtract remote usage. Overshoot is bounded by approximately one sync interval worth of traffic. This is the right default for most APIs; state the bound explicitly when presenting it.
7. Fault Tolerance
- Redis redundancy: each shard has a primary and at least one replica with automatic failover. Async replication may lose a few milliseconds of decrements on failover — acceptable given the accuracy budget already established.
- Tight timeouts on the hot path: set a client-side timeout of ~5 ms with no automatic retry. Wrap each shard in a circuit breaker so a single slow shard doesn't cascade.
- Fail-open with local fallback: if the Redis call times out or the circuit is open, allow the request rather than rejecting everyone. Fall back to an in-memory token bucket capped at
user_limit / num_gateways_in_region. This provides coarse protection and keeps the main API alive. Document this behavior explicitly so the team knows that a full Redis outage means degraded (not absent) rate limiting.
Common Mistakes to Avoid
- Using application-server timestamps inside the Lua script — clock skew causes incorrect refill amounts.
- Forgetting to set a TTL on bucket keys — 50 M keys for inactive users will exhaust memory.
- Treating fail-open as optional — the rate limiter must never become a SPOF for the API it protects.
- Conflating per-region limits with global limits without stating the accuracy implications of the choice.