Design a Rate Limiting Service for a Multi-Region API Platform
System DesignModel answerLast updated
Design a low-latency, distributed rate limiter that enforces per-key request quotas across a fleet of servers handling millions of requests per second.
Rate Limiting Service for a Multi-Region API Platform
Your platform exposes APIs consumed by millions of clients. Without traffic controls, a single misbehaving client can starve everyone else. Your job is to design a service that enforces quotas such as "500 requests per minute per API key" across a horizontally scaled gateway layer.
Functional requirements
- A caller presents an identifier (e.g.,
api_key,user_id, or a composite liketenant_id + endpoint) and the system decides: allow or deny. - Limits are configurable per tier (e.g., free = 60/min, pro = 1,000/min) and can be overridden per key.
- Denied requests receive enough metadata to know when to retry.
Non-functional requirements
- Latency: the rate-limiting decision must add less than 10 ms at p99.
- Scale: the system must sustain millions of requests per second spread across three or more geographic regions.
- Availability: a failure in the rate-limiting layer must never take down the API itself.
- Accuracy: a small overshoot (roughly 1–5%) is acceptable in the common case; some limit categories (e.g., authentication attempts) require strict enforcement.
What to cover
- Client-facing API — what does the gateway call, and what does it return?
- Algorithm selection — compare at least two approaches and justify your choice, including memory and accuracy trade-offs.
- Storage and architecture — where does per-key state live, how is it sharded, and how does the gateway access it within the latency budget?
- Atomicity — how do you prevent two gateway nodes from both approving a request when only one token remains?
- Clock skew — how do you ensure refill calculations are consistent across nodes?
- Failure modes — what happens when the backing store is unreachable?
- Cross-region enforcement — how would you handle a user who hammers the API from two continents simultaneously?
Hints
Hint 1
Start by estimating the per-key state size and total memory footprint. 100 million active keys at ~100 bytes each is only about 10 GB — that changes which storage options are viable.
Hint 2
A naive GET → compute → SET is a race condition the moment two gateway nodes act on the same key concurrently. Think about what Redis primitive lets you make that whole sequence atomic without a distributed lock.
Hint 3
A central store that every request must hit is a single point of latency. Consider how a local in-process cache on each gateway node can absorb already-denied traffic before it ever reaches Redis.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and size before designing anything
Strong candidates open with a few targeted questions rather than jumping straight to boxes and arrows.
- What is the limit key? A bare
api_key, auser_id, an IP, or a composite like(tenant_id, endpoint)? Each adds cardinality. - Hard or soft limit? Billing and authentication flows need strict enforcement. General API traffic can tolerate a small overshoot if it buys latency.
- Scale: assume 5M RPS globally, 100M active keys, 3 regions. Per-key state (token count + timestamp + Redis overhead) is roughly 100 bytes, so total working set is about 10 GB — comfortable in a sharded in-memory store.
- Latency budget: under 10 ms at p99. A same-AZ Redis round trip is 0.5–1 ms, so one network hop per decision is fine. Two hops or any cross-region synchronous call breaks the budget.
2. Client-facing API
Expose the limiter as an embedded library or sidecar, not a standalone RPC service. An extra hop to a rate-limit microservice would burn half the latency budget before any work is done.
allow(key: str, rule_id: str, cost: int = 1) -> Decision
Decision {
allowed: bool
remaining: int
retry_after_ms: int
reset_at: timestamp
}
On denial the gateway returns HTTP 429 plus headers:
X-RateLimit-Limit/X-RateLimit-Remaining/Retry-After
Rules are managed out-of-band via an admin API and pushed to gateways through a config store (etcd, ZooKeeper, or a pub/sub channel).
3. Algorithm comparison
| Algorithm | Memory per key | Burst accuracy | Notes |
|---|---|---|---|
| Fixed window counter | 1 integer | Allows up to 2× burst at window boundary | Simplest; INCR + EXPIRE |
| Sliding window log | O(limit) timestamps | Exact | Memory explodes at high limits |
| Sliding window counter | 2 integers | ~Exact (weighted approximation) | Good default for strict "N per minute" |
| Token bucket | 2 values | Exact for rate + burst | Industry standard |
Use the token bucket. Each key stores (tokens, last_refill_ts). On each request: lazily refill with elapsed time, check whether enough tokens remain, subtract and allow or deny. It is O(1) in both time and memory, handles burst naturally, and maps directly to "100/min with a burst of 20".
If the requirement is a strict rolling window with no burst semantics, the sliding window counter is the alternative: current_estimate = prev_count × (1 − overlap) + curr_count.
4. Architecture
Request
→ API Gateway (embedded limiter client + local deny cache)
│ one atomic Redis call (Lua script)
↓
Redis Cluster (sharded by hash(key), primary + replica per shard)
↑
Config service (rule definitions, pushed on change)
Sharding: Redis Cluster consistent-hashing (hash slots) on the limit key. All state for one key lives on exactly one shard, so every decision is a single-shard atomic operation — no cross-shard coordination.
TTL: set PEXPIRE on every key to roughly 2× the refill window. Inactive keys are evicted automatically, keeping memory bounded.
Local cache on the gateway: when a key is already denied, cache that denial until retry_after expires. Abusive traffic is rejected in microseconds without touching Redis, which also protects against hot-key concentration on a single shard.
Token leasing for hot keys: a gateway can lease a batch of tokens (say 10% of remaining) and spend them locally between Redis syncs. This trades a bounded overshoot for a significant reduction in Redis calls.
5. Atomicity — the critical detail
A read-modify-write sequence (GET → compute → SET) is a race condition: two gateway nodes can both read tokens = 1, both approve, and both decrement to 0, effectively allowing two requests when only one should pass.
The correct fix is a Lua script executed on the Redis shard. Redis runs scripts single-threaded, so the entire check-and-update is atomic with no interleaving.
-- KEYS[1] = bucket key
-- ARGV: capacity, rate_per_ms, cost
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
-- refill, but never go below 0 elapsed (clock jitter guard)
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
return { allowed and 1 or 0, math.floor(tokens) }
Alternatives: WATCH/MULTI optimistic locking retries badly under contention; distributed locks (Redlock) add too much latency. Lua is the right answer here.
6. Clock skew
If each gateway computes now independently, a node with a fast clock refills tokens early while a node with a slow clock may compute negative elapsed time. The fix is to source now from the Redis shard itself via redis.call('TIME') inside the Lua script. All updates to a key then observe the same monotonic clock regardless of which gateway initiated the call. Clamping elapsed time to ≥ 0 provides a safety net during shard failovers where a replica's clock may lag by a few milliseconds.
7. Failure handling
Wrap every Redis call in a short timeout (~5 ms) and a circuit breaker.
- Default: fail open. The rate limiter must never cause an API outage. If Redis is unreachable, allow traffic through.
- Degraded mode: instead of no limit at all, fall back to a local-only limit of
global_limit / node_count. This is approximate but better than nothing. - Fail closed for security-critical limits (login attempts, password resets). Here a Redis failure should block the request, not allow it.
Document which rules are in which category; this is an operational decision, not a technical one, and interviewers appreciate calling it out explicitly.
8. Cross-region enforcement
Synchronous global consensus would add 50–150 ms per request — that breaks the latency budget immediately. Practical options, in order of preference:
- Home-region pinning: route each key's limit state to one designated region based on a hash of the key. Works well when traffic is already geo-routed per account. Adds one extra hop only for out-of-region requests.
- Per-region quota allocation: give each region a fraction of the global limit (e.g., 40% / 40% / 20% based on traffic share). Fast and consistent within a region; accepts small global overshoot at region boundaries.
- Async reconciliation: regions exchange count deltas every few hundred milliseconds. Eventual consistency with a bounded overshoot proportional to the sync interval.
The right choice depends on how strict the cross-region accuracy requirement is. Stating the trade-off clearly matters more than picking one answer.
Common mistakes to avoid
- Designing a separate rate-limit microservice — this doubles the network hops and almost certainly breaks the latency budget.
- Using
GET+SETwithout atomicity — always ask "what happens if two threads execute this simultaneously." - Ignoring clock skew — computing elapsed time on the client when multiple clients have independent clocks leads to subtle over- or under-counting.
- Treating availability and accuracy as binary — the most useful answer is to name the knobs (fail open vs. closed, local leasing vs. central truth) and explain when to turn each one.