“Design a distributed rate limiter for a public API.”
A rate limiter decides whether to admit work under a defined policy. Before drawing a shared counter, clarify what is limited, whether bursts are allowed, and what guarantee must survive failures.
For this walkthrough, assume limits per authenticated tenant and route group, a sustained allowance of 10 requests per second with a burst capacity of 20, and 100,000 total requests per second at peak. We initially require an authoritative per-key decision within one region. Global strictness is a separate trade-off. These numbers are illustrative.
01. Define the contract
Authenticate before applying tenant-specific quotas. Derive tenant identity from trusted authentication context, not an arbitrary header. A separate coarse control can protect unauthenticated endpoints; IP-based limits alone can unfairly group users behind shared networks.
| Question | Proposed answer |
|---|---|
| What consumes quota? | An admitted API request, with a fixed cost of one in the initial design. |
| Can callers burst? | Yes, up to the current token balance, capped at 20. |
| What happens on rejection? | Return HTTP 429 with a useful retry delay when it can be computed. |
| What about service failure? | Use an explicitly configured route-specific fallback and monitor it. |
RFC 6585 defines 429 Too Many Requests and permits a Retry-After header. The header is guidance, not a reservation of future capacity.
A token bucket with rate 10 and capacity 20 does not mean “never more than 10 requests in every one-second interval.” An initially full bucket can spend 20 immediately and refill during the interval. Use a different policy if the contract requires a strict rolling-window maximum.
02. Choose the algorithm that matches the promise
| Algorithm | Useful property | Trade-off |
|---|---|---|
| Fixed-window counter | Small state and simple accounting. | Traffic can cluster on both sides of a window boundary. |
| Sliding-window log | Tracks individual admissions in the active interval. | Memory grows with admitted events in that interval. |
| Sliding-window counter | Lower state cost using weighted windows. | Approximates the rolling count. |
| Token bucket | Separates sustained rate from permitted burst. | Does not enforce a strict count in every rolling interval. |
Choose a token bucket for the assumed contract. For each key, store its token balance and last refill time. On a request, refill up to capacity and atomically consume the request cost if enough tokens remain.
allow if tokens ≥ cost; then tokens = tokens − cost
At 10 tokens per second, a bucket with 3 tokens and 0.5 seconds of elapsed time refills to 8. A cost-one request leaves 7. With zero tokens, the earliest nominal wait for a cost-one request is 0.1 seconds, assuming no other caller consumes the refill.
03. Make admission atomic
A client-side read–check–write sequence races: two gateways can both see the last token and both admit work. Perform refill, eligibility check, consumption, and state update in one atomic operation at the state owner.
A Redis script is one implementation option. Redis guarantees atomic script execution, but long scripts block other work on that server. Keep the operation short and bounded. Atomic execution on a primary does not by itself guarantee no state loss during failover.
Use time supplied by the state authority where practical, prevent negative elapsed time, and define what happens on clock jumps. Partition independent tenant keys across owners. If a policy requires atomic updates to multiple keys, account for the storage system's cross-shard limitations.
04. Bound state, latency, and hot keys
Track active keys rather than provisioning a permanent record for every possible tenant-route combination. Expire idle buckets only after enough time has passed for them to be full; recreating a bucket too early can grant extra tokens.
A 100,000-request-per-second peak implies a large decision workload if every request reaches shared storage. Benchmark the chosen operation and key distribution. Do not infer capacity from request count alone: one hot tenant behaves differently from a million quiet keys.
Local token leases can reduce round trips: the authority reserves a small allowance, and a gateway spends it locally. That improves latency but introduces unused capacity, lease-expiry questions, and crash recovery. Count a lease against the authoritative budget at allocation, not after consumption.
Limit key cardinality from untrusted inputs. Group routes by policy instead of creating a bucket from every unique URL. Keep quota enforcement distinct from a concurrency limiter: a low request rate can still overwhelm a service when each request runs for minutes.
05. State the multi-region trade-off
Giving each of two regions the full 10-request-per-second allowance can permit 20 globally. Asynchronous reconciliation does not restore a strict limit after work has already been admitted.
- One authority per key: route decisions to a home region or use a coordinated store. This can preserve a stronger contract at the cost of latency and availability during partitions.
- Partitioned regional budgets: allocate shares whose total respects the global allowance. Spare capacity in one region cannot automatically help another.
- Bounded approximation: permit documented overshoot for availability, then measure it. This is only acceptable when the product contract allows it.
Budget transfers need epochs or fencing so the old owner cannot keep spending a reclaimed allocation. Do not reclaim a lease and reissue it merely because a disconnected gateway appears idle.
06. Decide how failure changes behavior
For low-risk reads, a conservative local fallback might protect availability while limiting damage. For expensive or sensitive actions, rejecting or challenging may be preferable. If the admission authority is unavailable, a 503 can be more accurate than claiming a known quota violation with 429.
A timeout is ambiguous: the state owner may have consumed a token even though the gateway never received the response. Retrying can consume another token. Decide whether conservative overcounting is acceptable or whether decision IDs and deduplication are needed within a bounded retry window.
Monitor decision latency, rejection rate, fallback usage, state-store errors, hot-key load, and per-policy anomalies. Deploy policy changes with versions and rollback. Alert on unexpected changes in allowed traffic, not just on storage availability.
07. Defend the design
“We need an exact billing quota.”
A fast protective rate limiter is not automatically a durable billing ledger. Clarify exactness and audit requirements; use durable usage accounting and idempotent charge events where needed. State-store failover and counter loss are unacceptable assumptions for exact billing.
“Clients retry at the same moment.”
Return meaningful backoff guidance and encourage jitter. Consider whether upstream SDK retries and multiple layers of limiting amplify the burst. Retry-After cannot guarantee admission when many clients share a key.
“One request costs a hundred times more.”
Use weighted costs or a separate policy for expensive routes. Define behavior when a request's cost exceeds bucket capacity; waiting alone can never admit it.
Using non-atomic check-then-update, promising a global limit with independent full regional budgets, ignoring timeouts, or treating a token bucket as a strict rolling-window counter.
Your answer in one minute
“I would clarify identity, quota cost, burst allowance, and regional guarantees. For the chosen policy, I would use an atomic token-bucket decision with bounded state, versioned policies, and explicit failure behavior. I would partition independent keys, treat hot keys separately, and choose coordinated or partitioned global budgets according to the required consistency.”
Sources & further reading
- RFC 6585, section 4 — HTTP 429 semantics.
- Redis: rate-limiting algorithm comparison — common implementation patterns.
- Redis: scripting with Lua — atomic execution and its operational constraints.
Traffic, quotas, and deployment choices are illustrative.
Continue your preparation
Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.