Design a Per-User API Rate Limiter Service
System DesignModel answerLast updated
Design a distributed rate limiting service that enforces per-user request quotas across a fleet of API gateway nodes at high throughput.
Background
You are a senior engineer at a company that runs a public REST API used by thousands of third-party developers. The API is served by a horizontally-scaled fleet of gateway nodes (stateless, ~50 nodes today, up to 200 nodes in two years). Each developer account gets a plan-based quota, for example:
- Free tier: 100 requests / minute
- Pro tier: 5,000 requests / minute
- Enterprise tier: custom limits, negotiated per account
A request that exceeds the quota must be rejected with HTTP 429 Too Many Requests before it reaches the backend. The decision must be made within the gateway, adding no more than 5 ms p99 latency overhead to any request.
Scale
- 200 M API requests per day at peak (~2,300 req/s average, 15,000 req/s burst)
- ~500,000 registered developer accounts; ~20,000 active per minute
- Multi-region deployment (US-East, EU-West, AP-Southeast)
- SLA: 99.9% uptime for the rate-limiter decision path
What is expected
- Clarify requirements — identify the key axes (accuracy, latency, failure mode).
- Choose and justify an algorithm — compare at least two options.
- Design the data model and API — what is stored, where, and in what shape.
- Sketch the architecture — how gateway nodes interact with the limiter.
- Address failure modes — what happens when the rate-limit store is unavailable.
- Discuss trade-offs — consistency vs. latency, local vs. global counting.
Hints
Hint 1
Think about what happens when 50 gateway nodes each maintain a local counter — how do they stay consistent, and does exact consistency actually matter?
Hint 2
A pure centralized Redis counter is simple but creates a bottleneck and a single point of failure; how can you reduce the blast radius while keeping latency low?
Hint 3
The sliding-window log is accurate but memory-intensive at scale; the token-bucket and sliding-window counter are cheaper — what is each one bad at?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements Clarification
Before diving in, confirm the following with the interviewer:
- Accuracy tolerance: Is off-by-5% acceptable? (Almost always yes — burstiness makes exact enforcement impossible anyway.)
- Failure mode: If the rate-limit store is unreachable, should we fail open (allow traffic) or fail closed (deny traffic)? For most APIs, fail open is preferred to avoid self-inflicted outages.
- Granularity: Per-user only, or also per-IP, per-endpoint, or per-plan globally?
- Quota window: Rolling 60-second window or fixed calendar minute? Rolling is fairer.
Assume: rolling window, per-user, ~5% over-count acceptable, fail open.
2. Algorithm Choice
Option A — Fixed Window Counter
Increment a counter keyed to user_id:window_start. Reset each minute.
- Pro: O(1) space, trivial to implement.
- Con: Boundary burst problem — a user can fire 100 req at 00:59 and 100 req at 01:00, sending 200 req in 2 seconds. Rejected for production use.
Option B — Sliding Window Log
Store a sorted set of timestamps per user. Count entries in the last 60 s.
- Pro: Perfectly accurate.
- Con: O(requests per window) memory per user. At 5,000 req/min per Pro user × 20,000 active users = 100 M entries. Too expensive.
Option C — Token Bucket
Each user has a bucket refilled at a constant rate. Requests consume tokens.
- Pro: Naturally handles bursts up to bucket capacity; intuitive for clients (Retry-After is easy to compute).
- Con: Requires storing
(tokens, last_refill_ts)and doing a floating-point refill calculation atomically. Harder to distribute.
Option D — Sliding Window Counter (chosen)
Blend the last full window and the current partial window:
effective_count = prev_window_count * (1 - elapsed_fraction) + cur_window_count
- Pro: O(2) keys per user, ~5% max error vs. true sliding window (proven mathematically), very low memory.
- Con: Slight inaccuracy. Acceptable given our requirement.
Decision: Sliding Window Counter. Best memory/accuracy balance at this scale.
3. Data Model
Store two keys per user in Redis:
rl:{user_id}:2024011412 -> integer (count in the 12:00 window)
rl:{user_id}:2024011413 -> integer (count in the 13:00 window)
Each key is given a TTL of 2 × window_size (i.e., 120 seconds for a 60-second window) at the moment it is first created, so stale windows self-expire. The TTL is set unconditionally on every write — never only on the first write — so a key can never be stranded without an expiry.
User plan limits live in a separate low-churn store (Postgres or a config service), cached in each gateway node's local memory with a 30-second TTL. This avoids hitting Redis for the limit value on every request.
4. Architecture
Client Request
|
v
[API Gateway Node] (one of 50–200 stateless nodes)
|
|-- local plan cache (in-process, 30 s TTL)
|
v
[Redis Cluster] (3 shards × 2 replicas, one cluster per region)
|
|-- Lua script: atomic read-increment-check
v
Decision: allow / deny (429)
The Atomic Lua Script
Running the check-and-increment as a single Lua script inside Redis ensures atomicity without a distributed lock. Both the previous window key and the current window key receive an explicit EXPIRE on every invocation, guaranteeing that neither key can ever exist without a TTL regardless of which code path created it:
local prev_key = KEYS[1] -- previous window key
local cur_key = KEYS[2] -- current window key
local limit = tonumber(ARGV[1])
local elapsed = tonumber(ARGV[2]) -- fraction of current window elapsed (0.0–1.0)
local ttl = tonumber(ARGV[3]) -- 2 × window_size in seconds
local prev = tonumber(redis.call("GET", prev_key) or 0)
local cur = tonumber(redis.call("GET", cur_key) or 0)
local effective = prev * (1 - elapsed) + cur
if effective >= limit then
-- Refresh TTL on both keys even on deny, so they always carry an expiry.
if prev > 0 then redis.call("EXPIRE", prev_key, ttl) end
return 0 -- deny
end
redis.call("INCR", cur_key)
-- Always set EXPIRE on both keys so no key is ever left without a TTL.
if prev > 0 then redis.call("EXPIRE", prev_key, ttl) end
redis.call("EXPIRE", cur_key, ttl)
return 1 -- allow
Key correctness point: EXPIRE is called on prev_key whenever that key holds a non-zero value, covering the case where an earlier invocation created prev_key via INCR but a crash or early return skipped the EXPIRE call. This ensures no key is stranded without an expiry.
One round-trip to Redis per request. At p99 ~1–2 ms for an in-region Redis call, well within the 5 ms budget.
Local Buffering (optional, for very high-volume accounts)
For Enterprise accounts hitting 50,000+ req/min, each gateway node can pre-fetch a token batch (e.g., 500 tokens) from Redis in a single INCRBY. The node spends locally until the batch is exhausted, then fetches another. This reduces Redis calls by ~500×. Trade-off: up to one batch-size of over-count in failure scenarios.
5. Failure Modes
| Scenario | Behavior |
|---|---|
| Redis shard unreachable | Fail open — allow request, log warning. Avoids cascading outage. |
| Redis slow (> 4 ms) | Local fallback: each node tracks a rough local counter; deny only if clearly over-limit. |
| Gateway node crash mid-batch | Tokens in the batch are lost (under-counted). Acceptable — conservative. |
| Clock skew between nodes | Window keys use wall-clock minute. Up to 1 s skew → at most 1.6% window boundary error. Acceptable. |
For the Redis cluster itself: use Redis Sentinel or Redis Cluster with automatic failover (< 30 s). During failover, fail open.
6. Trade-offs Summary
| Dimension | Choice | Alternative |
|---|---|---|
| Algorithm | Sliding window counter (cheap, ~5% error) | Token bucket (exact bursts, harder to distribute) |
| Store | Redis Cluster (fast, simple atomics) | Cassandra (more durable, higher latency) |
| Consistency | ~5% over-count tolerated | Exact — requires distributed locking, too slow |
| Failure mode | Fail open | Fail closed — risks self-outage |
| Topology | Central Redis per region | Fully local per-node — simple but easy to circumvent by spreading load across nodes |
Common Mistakes to Avoid
- Forgetting the boundary burst of fixed windows — always use a sliding approach.
- One Redis instance with no replication — single point of failure that violates the SLA.
- Storing timestamps in a sorted set at this scale — memory explodes for high-volume users.
- Doing two round-trips (GET then INCR) outside a Lua script — introduces a race condition; the entire check-and-increment must be atomic.
- Setting EXPIRE only on the current window key — the previous window key must also receive an EXPIRE on every write, or it may persist indefinitely if an earlier code path created it without one.
- Not caching plan limits locally — hitting the plan store on every request adds latency and creates a second critical dependency.