Build a Distributed API Rate Limiter with Per-User Quotas
System DesignModel answerLast updated
Design a low-latency distributed rate limiter that enforces different token budgets for different users across a fleet of stateless API gateway nodes.
The Problem
You're building the rate-limiting layer for a large API platform. The wrinkle that shapes the whole design: every user can have a different quota. A free-tier user might be allowed 100 tokens per second. A premium enterprise customer might get 10,000. Each request can also cost more than one token — a lightweight read might cost 1, while a compute-heavy export might cost 50.
Your system must decide allow or deny on every incoming request, add minimal latency to the critical path, and enforce limits correctly even when requests from the same user land on different gateway machines.
Walk through your design end to end: the algorithm you'd use, where quota definitions live and how they reach the enforcement point, how live counter state is stored and updated atomically, the full request-time decision flow, and how the system handles scale and partial failures.
Constraints and assumptions
- Tens of millions of registered users. Most fall into a small set of tiers (free, pro, enterprise). A few thousand have per-user quota overrides.
- Peak load is in the range of hundreds of thousands to roughly 1 million rate-limit checks per second across the entire fleet.
- The rate-limit check must add no more than 1–2 ms to request latency.
- Quotas are expressed as tokens per second; each request specifies how many tokens it costs.
- Quota changes (e.g., a user upgrading their plan, an operator applying a manual override) must take effect within seconds, with no redeploy.
- The API gateway is stateless and horizontally scaled; any node can receive any user's request.
Clarifying questions worth raising
Before designing, discuss these with your interviewer:
- Is the limit a hard guarantee, or is small bounded over-admission acceptable in exchange for lower latency?
- What should the system do when the backing counter store is unreachable — admit traffic (fail open) or reject it (fail closed)?
- Should users be allowed short bursts above their sustained rate, or should the rate be smoothed strictly per second?
- Is this enforced at a shared API gateway, as a per-service sidecar, or inside each microservice?
- Is enforcement single-region, or must a user's quota be shared across multiple geographic regions?
- What does a rejected caller receive — an HTTP 429 with retry guidance, a queue, or gracefully degraded service?
What's expected
Explain your algorithm choice and why it fits variable costs and burst semantics. Describe the separation between quota configuration and live counter state, and how each reaches the enforcement path. Provide rough numbers to justify your shard count and memory estimates. Address atomicity, clock consistency, hot keys, and failure handling. Call out the trade-offs you're making.
Hints
Hint 1
Think of per-user quotas as parameters to a single algorithm, not as separate algorithms per user. Which algorithm naturally accepts a per-user rate and capacity, handles variable request costs with no extra logic, and keeps only a tiny amount of state per user?
Hint 2
Split the problem into two distinct planes: one that holds quota definitions (slow-changing, read-constantly) and one that holds live counter state (fast-changing, needs atomic updates). Design each plane independently, then connect them at request time.
Hint 3
A Redis round trip on the hot path costs roughly 0.2–0.5 ms in-region, which fits in your 1–2 ms budget. But what happens when a single high-throughput user hammers one shard? And what happens when Redis is temporarily unreachable? Have a concrete answer for both before you call the design done.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the Contract First
Nail down a few decisions before drawing any boxes:
- Accuracy: small, bounded over-admission (a few percent) is acceptable. Latency wins over perfection.
- Failure mode: fail open with a local fallback. The limiter protects capacity; it is not a billing ledger.
- Bursts: yes, users get burst headroom above their sustained rate.
- Enforcement layer: a stateless API gateway tier, horizontally scaled.
- Rejection response: HTTP 429 with
Retry-AfterandX-RateLimit-Remainingheaders.
2. Back-of-Envelope Sizing
Pin numbers early so shard counts and memory estimates feel grounded rather than arbitrary.
- Throughput: 1M checks/s. A Redis shard handling a small Lua script can sustain roughly 50–100k ops/s. You need about 20–40 shards with a comfortable headroom buffer.
- State size: 10M active users × ~64 bytes per bucket ≈ 640 MB. Trivially fits in memory.
- Config size: a handful of tiers plus a few thousand overrides — a few MB at most. Every gateway node can hold all of it in process.
- Latency budget: 1–2 ms total. An in-region Redis round trip is 0.2–0.5 ms, leaving room for one and only one network hop on the hot path.
3. Algorithm: Token Bucket with Lazy Refill
Each user has a bucket described by two parameters: rate (tokens per second, sustained) and capacity (the burst ceiling). On each request costing c tokens:
now = clock()
tokens = min(capacity, tokens + (now - last_ts) * rate)
if tokens >= c:
tokens -= c
allow
else:
deny, retry_after = (c - tokens) / rate
last_ts = now
Why this fits the problem well:
- Heterogeneous quotas are just different
(rate, capacity)pairs. The code is the same for every user. - Variable request cost is native — a request simply subtracts
ctokens. No special-casing needed. - No background timer or scheduled refill job. Tokens are computed at read time.
- State per user is minimal:
{tokens, last_ts}— two numbers.
Why not the alternatives:
- Fixed window allows up to 2× the intended rate at window boundaries.
- Sliding log stores every timestamp, so memory scales linearly with request rate — fatal for high-volume users.
- Sliding window counter is a reasonable alternative but handles weighted costs and burst semantics less cleanly.
4. Config Plane vs. Data Plane
This separation is the central design decision.
Config plane — who gets what quota
Quota definitions change rarely but are read on every request.
- Source of truth: a Quota Service backed by a relational database. Schema:
tiers(tier_id, rate, capacity)anduser_overrides(user_id, rate, capacity, updated_at). - Resolution order: per-user override → tier default → global default.
- Hot path lookup: each gateway loads the full tier table and all overrides into an in-process hash map at startup. Resolution is a microsecond memory lookup with no network call.
- Update propagation: quota changes are published to a pub/sub channel (Redis pub/sub or a lightweight Kafka topic). Gateways apply them within about a second. A periodic full resync (every 30–60 s, keyed by version number) backstops any missed messages.
Data plane — live counter state
- Store: Redis Cluster, sharded by
user_id. - Key and value: key
rl:{user_id}holds a hash{tokens, ts}. - Expiry: TTL ≈
capacity/rateplus a small slack. An idle bucket would be full anyway, so evicting it is safe. - Atomicity: the read-refill-check-decrement sequence runs as a single Lua script via
EVALSHA. Without this, two concurrent requests on different gateways can both readtokens = 5, both spend 5, and collectively over-admit by 5. - Clock: the script calls Redis
TIME, not the gateway's local clock. This eliminates drift between nodes. - Parameters: the gateway passes
rate,capacity, andcostas arguments. Redis has no knowledge of tiers.
5. Request-Time Decision Flow
- Request arrives at a gateway node. Auth middleware extracts
user_idand determines requestcost(from the endpoint definition or a cost model). - Gateway does an in-process hash lookup for
(rate, capacity). - Gateway calls
EVALSHA bucket.lua rl:{user_id} rate capacity costagainst the owning Redis shard. Timeout: ~1 ms. - Script returns
(allowed, remaining, retry_after). - If allowed, the request is forwarded upstream. If denied, 429 is returned immediately. Rate-limit headers are set either way.
- On Redis timeout or error: the gateway falls back to an in-process token bucket running at
rate / N_gateways. It records a metric and triggers an alert. Traffic continues flowing at a capped rate rather than being fully blocked.
6. Handling Hot Keys and Heavy Users
A user at 10k tokens/s is one request to one shard — fine. A cluster of heavy users landing on the same shard, or a single 100k/s customer, creates a bottleneck.
Local token leasing (preferred approach):
A gateway atomically claims a batch of tokens from the central bucket — for example min(rate/10, 500) — and spends them locally until the batch runs out, then fetches another. Redis traffic for that user drops proportionally to batch size.
Trade-off: if a gateway goes idle before exhausting its lease, those tokens are temporarily unavailable to other gateways. Bounded over-admission is also possible if multiple gateways hold leases simultaneously. Mitigations: give leases a short TTL (~100 ms) and apply leasing only for users above a rate threshold.
Bucket sharding:
Split rl:{user_id} into rl:{user_id}:0..k-1, each holding rate/k and capacity/k. Each request picks a random shard. On a deny, retry one other shard before returning 429. This spreads write load but can produce false denials when distribution is uneven.
7. Key Trade-offs to State Explicitly
| Decision | Option A | Option B | Choice |
|---|---|---|---|
| Accuracy vs. latency | Central store, exact | Local leasing, bounded error | Leasing for heavy users |
| Failure behavior | Fail closed | Fail open with local cap | Fail open; limiter protects capacity, not billing |
| Config freshness | Push (sub-second) | TTL poll (eventual) | Push + periodic resync as backstop |
8. Common Mistakes to Avoid
- Running the refill computation on multiple gateways and then writing back without a lock. This is a classic TOCTOU race. Use an atomic Lua script or a conditional write.
- Using gateway wall clocks inside the Redis script. Clock skew between nodes mints or destroys tokens. Always use
Redis TIME. - Storing per-request logs or timestamps in the counter. Sliding-log approaches blow up in memory for high-rate users.
- Forgetting the failure mode. Every design review will ask: what happens when Redis is down? Have a specific, bounded answer.
Follow-up: Multi-Region Quotas
Don't synchronously cross regions on the hot path — the latency would kill the budget. Instead, give each region a fixed fraction of the global quota (e.g., proportional to traffic share). Use async replication to reconcile counters and periodically rebalance allocations. Accept a small window of global over-admission as the cost of low latency.