Course contents

17. Real-World System Design Lesson 3 of 20

Rate Limiter

Design a distributed rate limiter end to end: token buckets at the gateway, shared atomic counters, window algorithms, and failing open when the store dies.

20 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Pin down rule shape, fleet size and the per-check latency budget first; they decide where counters live.
  • Local buckets multiply the limit by the instance count; dividing the limit only works with perfectly even traffic.
  • A shared in-memory store with one atomic script per check makes limits exact at the cost of one round trip.
  • Fixed windows allow 2× at the boundary; sliding window counters and token buckets smooth it.
  • Fail open with a coarse local cap: the limiter must never be the reason the API is down.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A distributed rate limiter decides, for every request entering an API, whether the caller (an API key, user, IP or route) is still within its allowance, and refuses the request with 429 Too Many Requests if not. In this case study it is a library inside every API gateway instance, backed by a regional in-memory counter store, with rules delivered by a separate control plane.

The Rate Limiting lesson covers the basics (why limits exist, per-client buckets, burst size, Retry-After). This lesson designs the system that enforces them across a fleet. The full interview walk-through, with API, data model and estimates, is at /system-design/interviews/rate-limiter.

Why it exists

A public API is shared capacity. Without per-key limits, one tenant's runaway batch job or scraper decides latency for everyone. Limits also protect expensive endpoints (login, search) from abuse. The hard part is not the algorithm; it is enforcing one limit consistently when requests for the same key land on hundreds of gateways, within a millisecond or two, and without making the limiter a new way for the API to fail.

How it works

Requirements and estimates. The interview version assumes about 1M requests/s at peak over roughly 300 gateways, so ~3,300 checks/s per gateway. With up to three matching rules per request, grouped by subject so most requests need about 1.2 store calls, that is ~1.2M counter operations/s. Planning ~50,000 script executions/s per store primary (well under what a single primary can do, to leave headroom) gives about 24 primaries per region. Memory is small: ~20M active buckets × ~150 B ≈ 3 GB. The latency budget, p99 under ~3 ms per check, fits only a same-region round trip (0.2–0.5 ms), which is why limits are enforced per region.

One instance: a local token bucket. Each key's bucket holds up to burst tokens and refills at rate tokens per second. A request takes one token or is refused. Refill is computed lazily from the time since the last check, so there is no background job. On one gateway this is exact.

A fleet breaks local counters. With N gateways and an independent bucket on each, a key gets up to N × the limit. Giving each instance limit ÷ N only works if every key's traffic is spread evenly; per-connection balancing and long-lived connections make the split lumpy, so a gateway that receives more than its slice refuses requests while the key is under its plan. Small limits (5 per minute) cannot be divided at all.

Shared counters. Keep each bucket in one place: a hash such as rl:{k_7f3a}:plan with fields tokens and ts, in an in-memory store (Redis Cluster in the interview design). Every key gets a TTL equal to its full refill time, so idle buckets disappear. The {...} hash tag puts all rules for one subject on the same shard, so one call can check them all.

Atomicity. GET, compute in the gateway, SET races: two gateways read "1 token", both allow. The fix is a short server-side script that refills, checks and decrements in one step and uses the store's own clock (TIME) so 300 gateway clocks do not need to agree. Denied requests do not consume tokens. For several rules on one subject, compute all buckets first and decrement only if all allow.

Window algorithms. A fixed window counter is a single atomic INCR with an expiry, but allows up to 2× the limit around a boundary. A sliding window counter keeps the previous and current window counts and estimates previous × (1 − elapsed/W) + current; it is approximate (it assumes the previous window's requests were evenly spread) but smooth and cheap. A sliding log is exact but stores one entry per request. Token bucket maps directly onto "rate plus burst" plans; sliding windows suit quotas such as "5 login attempts per minute".

Failure handling. Each store call has a strict timeout (around 5 ms in the interview design) and a breaker per shard. When the breaker is open, the gateway uses a local fallback bucket per subject of about limit × safety factor ÷ gateway count, and marks those decisions as fallback in its metrics.

When to use it

  • Public or partner APIs with plans or quotas per key.
  • Protecting expensive or abuse-prone endpoints (authentication, search, writes).
  • Multi-tenant platforms where fairness between tenants matters.
  • Any fleet where a per-key limit must hold regardless of which instance receives the request.

When not to

  • Volumetric DDoS: absorb network floods upstream (CDN, WAF, network-level filtering); an application limiter behind them is too late and too expensive per packet.
  • Billing quotas that must be exact over a month: use durable counters and reconciliation, not a cache that may lose a few hundred milliseconds of updates on failover.
  • Very high per-key limits spread evenly across a fleet: plain local limits are accurate enough and avoid the store call.
  • Protecting a backend from overload in general: that is load shedding and backpressure based on the backend's own health, not per-client limits.

Trade-offs

Choice You gain You pay
Shared counters instead of local buckets Exact limits regardless of traffic spread; small limits work One round trip per check (~0.5 ms); a store to run and size
Atomic script instead of GET/SET No over-admission under concurrency Logic lives in the store; script deployment and versioning
Token bucket instead of sliding window Natural "rate + burst" semantics, constant memory Harder to explain as "N per window" quotas
Fail open with local fallback API stays up when the store fails Approximate limits (up to the safety factor) during the outage
Regional limits Fits the latency budget; no cross-region dependency A tenant's limit must be split between regions
Asynchronous store replication Sub-millisecond writes A failover forgets recent counts: brief over-admission

Alternatives

  • Purely local limits (limit ÷ instances): no dependency and no extra hop; accurate only for large limits with even balancing.
  • A dedicated limiter service in the request path: central logic and language-agnostic, but another hop and another fleet, without better accuracy than the shared store it would also need.
  • Token leasing: gateways take batches of tokens from the store and spend them locally; far fewer store calls for hot keys, slightly less precise.
  • Managed gateway limits: cloud API gateways and service meshes offer per-key limits; check whether they are global or per instance and how they behave when their backing store fails.

Failure modes

  • Fail-closed outage: treating "store unreachable" as "denied" refuses every request. The simulation shows the backend idle while the API is down.
  • Over-admission after failover: asynchronous replication loses the latest decrements, so some buckets reset towards full. Usually acceptable for fairness limits.
  • Hot keys: one tenant at very high rate saturates the shard that owns its key. Lease tokens or limit locally for such subjects.
  • Bad rule rollout: a limit published as 1 instead of 1,000 causes mass false 429s. Validate changes, start new or tightened rules in shadow mode, keep the last good snapshot, make rollback one click.
  • Cardinality attacks: creating counters for any string a client sends lets an attacker fill the store. Create per-key counters only after the key is validated.
  • Synchronised retries: a constant Retry-After brings every refused client back at the same moment. Compute it from the bucket and ask clients to add jitter.

In production

Rules live in a durable, versioned store; gateways poll a validated snapshot and keep running on the last good one if the control plane is down. Export the rules version each gateway runs. Measure decisions per rule (allowed, denied, shadow-denied, fallback), store script latency and CPU per shard, and evictions. Page on fallback mode or a sustained limiter p99 above budget. Sample 429 logs instead of logging each one, since denial volume is driven by the very clients you are refusing. Return RateLimit-* headers and Retry-After so well-behaved clients can pace themselves.

Common misconceptions

  • "Each instance can just enforce the limit." That multiplies the limit by the instance count.
  • "Divide the limit by the number of instances." Only with perfectly even, per-request balancing; otherwise keys are refused while under their plan.
  • "Redis is single-threaded, so GET then SET is safe." Each command is atomic; the sequence across the network is not. Use a script.
  • "A rate limiter should fail closed to be safe." For fairness limits, failing closed causes the outage the limiter exists to prevent.
  • "Fixed windows enforce N per window." Across a boundary a client can get 2N in a moment.

Interview angle

Start from requirements: what is limited (key, user, IP, route), rule shape (rate + burst, per-window quotas), accuracy tolerance and the latency budget. Estimate checks per second and store operations to size the counter store, then justify a regional in-memory store with atomic scripts. Interviewers probe the race condition, window algorithm trade-offs, what happens when the store dies (fail open with a local cap), hot keys, multi-region limits and how clients learn to back off. Work the full problem at /system-design/interviews/rate-limiter.

Model assumptions

The simulation follows a single API key, so a node's token bucket stands for that key's bucket; numbers are illustrative, not benchmarks. Arrivals are Poisson. Gateways have 32 workers and ~1 ms of work; the backend has 8 workers at a 50 ms mean (lognormal, cv 0.35), about 160 req/s. The shared counter store is modelled as a tiny server with a token bucket (50/s, burst 50) that every gateway calls before the backend; a request it refuses is counted as failed at the client (in reality a 429). The engine has no per-key script, so the store's internal atomicity is assumed, not simulated. Uneven connection-level balancing is modelled with weights (half the key's traffic on Gateway 1). Fail-open is shown as the state after the gateways' breakers have opened: they no longer call the store and enforce local buckets of 25/s (limit × 1.5 ÷ 3); timeouts and breaker transitions themselves are not simulated. The GET/SET race and the fixed versus sliding window comparison (5 requests per 1-second window) are scripted illustrations, not simulation output. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together.

The lesson as textEvery step of the simulation, written out.
  1. 1. What the limiter must do

    A public API runs behind a fleet of gateways. Each API key has a plan; Acme’s allows 50 requests per second with bursts up to 50. We follow only Acme’s key, so every request you see carries it.

    The interview version sizes the real thing: about 1 million requests per second at peak over ~300 gateways (≈ 3,300 checks per second each), up to ~1.2 million counter operations per second, and a budget of under 3 ms at p99 for one check. That budget only fits a counter store in the same region.

    Right now there is no limiter: Acme sends 70 requests per second and all 70 reach the backend.

    Scene: Acme’s API key sends 70 requests per second through the edge load balancer and one gateway to the backend. There is no limit yet: every request reaches the backend and succeeds.

    Key idea: Pin down the rule shape (rate + burst, per key), the fleet size and the latency budget first; they decide where the counters live.

  2. 2. A token bucket inside the gateway

    The gateway gets a token bucket for Acme’s key: 50 tokens, refilled at 50 per second. Each request takes a token; with none left the gateway answers 429 immediately and the backend never sees the request.

    About 50 of the 70 requests per second get through; the other ~20 are refused. Refill is computed lazily from elapsed time, so nothing runs in the background. With one gateway this is exact.

    Scene: Gateway 1 enforces a local token bucket of 50 per second. About 50 requests per second reach the backend; about 20 per second are refused with 429 at the gateway.

    Key idea: Token bucket: rate is the sustained average, bucket size the allowed burst. Refuse at the edge so refusals cost almost nothing.

  3. 3. Three gateways, three buckets

    Traffic grows, so we run three gateways behind the edge balancer. Each keeps its own local bucket of 50 per second, because nothing is shared.

    One second in, Acme pushes to 140 requests per second. Each gateway sees only about 47 per second, under its own limit, so almost nothing is refused: the effective limit is now 3 × 50 = 150. The backend, sized for plans like Acme’s, climbs towards 90% busy and latency rises.

    Scene: Three gateways each enforce their own 50 per second bucket. When Acme sends 140 requests per second, almost all of them pass because each gateway sees only a third; the backend becomes much busier.

    Key idea: Independent local counters multiply the limit by the number of instances.

  4. 4. Divide the limit by the fleet size?

    Next idea: give each gateway a third of the limit (about 16.7 per second, burst 17). That works only if the balancer splits every key’s traffic evenly, and it rarely does: clients keep long-lived connections and balancing happens per connection. Here two of Acme’s three connections landed on Gateway 1, so it receives half of Acme’s traffic.

    Acme sends 45 requests per second, below its plan. Gateway 1 sees about 22 per second against a slice of 16.7 and refuses some of them, while Gateways 2 and 3 have unused slices. Small limits (5 per minute) cannot be split at all.

    Scene: Each gateway enforces a third of the limit. Acme sends 45 requests per second, under its plan, but Gateway 1 receives half of it and refuses some requests while Gateways 2 and 3 refuse nothing.

    Key idea: Per-instance slices are approximate in both directions: they over-admit when traffic is skewed one way and under-admit the other.

  5. 5. One bucket in a shared counter store

    The fix is to keep the bucket in one place: an in-memory store (Redis in the interview design). Each gateway runs one small script per check that refills, checks and decrements the key’s bucket and returns allowed or denied. Local buckets are gone.

    Acme sends 140 requests per second again. It no longer matters which gateway a request lands on: about 50 per second pass in total and the rest are refused. The price is one extra round trip per request, well under a millisecond inside a region.

    Scene: Every gateway asks the shared Redis counter store before forwarding. Acme sends 140 requests per second; about 50 per second pass in total, whichever gateway they reach, and the rest are refused.

    Key idea: Shared counters make the limit exact regardless of how traffic is spread, at the cost of a network hop and a new dependency.

  6. 6. Why the check must be one atomic step

    *Scripted illustration; the simulation is paused for this step.*

    First the naive version: two gateways GET the bucket at the same moment, both read “1 token left”, both allow, and both forward a request: two requests on one token. With hundreds of gateways and a hot key, over-admission has no bound.

    Then the fix: one script that runs inside the store (refill, check, decrement in one step). The store serialises the two calls, the first gets the token and the second is denied (red). Use the store’s clock for refill, not the gateways’ clocks.

    Scene: Scripted: Gateways 1 and 2 both read the bucket, both see one token and both forward a request to the backend. Then, with an atomic script, the store answers Gateway 1 with allowed and Gateway 2 with denied, and only one request reaches the backend.

    Key idea: Read-compute-write across the network races. Do the whole token-bucket update atomically inside the store.

  7. 7. Fixed window vs sliding window counter

    *Scripted illustration with a rule of 5 requests per 1-second window.*

    A fixed window counter is a single INCR, trivially atomic. But five requests at the end of one window and five at the start of the next all pass: 10 in about 0.65 s, twice the limit.

    A sliding window counter weighs the previous window by how much of it still overlaps: estimate = previous × (1 − elapsed/W) + current. Replayed with the same arrivals, only one request of the second batch passes. Token bucket remains the best fit for “rate plus burst” plans; sliding windows suit quotas like “5 logins per minute”.

    Scene: Scripted: ten requests arrive around a window boundary. With a fixed window all ten are allowed. Replayed with a sliding window counter, the first five pass and only one of the next five passes; the others are refused.

    Key idea: Fixed windows allow up to 2× at the boundary; a sliding window counter smooths that with two integers per key.

  8. 8. The counter store goes down: fail closed

    Back to live traffic: Acme sends 70 requests per second. One second in, the counter store crashes.

    This gateway treats “cannot reach the store” like “denied”: it fails closed. Every request is now refused, not just Acme’s excess. The backend is idle and healthy, yet the API is down. A component meant to protect availability has become the cause of the outage.

    Scene: Acme sends 70 requests per second. When the counter store goes offline, every gateway check fails and every request is refused; the backend receives nothing.

    Key idea: A limiter that fails closed turns a counter-store outage into a full API outage.

  9. 9. Fail open, with a local fallback limit

    The interview design fails open in a controlled way. Each call to the store has a short timeout (5 ms) and a breaker per shard; once the breaker opens, the gateway stops calling the store and switches to a local fallback bucket: limit × 1.5 ÷ 3 gateways = 25 per second each.

    Acme’s 70 requests per second all get through again. At 1.5 s Acme spikes to 150: the local buckets still cap it at about 75 per second. Approximate, and up to 1.5× the plan, but the API stays up and abuse stays bounded.

    Scene: The counter store is still offline. Gateways no longer call it and enforce local 25 per second buckets. Acme’s 70 requests per second all succeed; after it spikes to 150, about 75 per second pass and the rest are refused.

    Key idea: Fail open so the limiter never takes the API down, but keep a coarse local cap so the backend stays protected.

  10. 10. Trade-offs of the design

    The store is back and the gateways use it again. What we chose and what it costs:

    Shared counters give exact limits but add ~0.5 ms and a dependency; async replication of the store means a failover forgets a few hundred ms of counts (brief over-admission). Limits are regional: a cross-region check would blow the 3 ms budget. Hot keys (one tenant at 200,000 req/s) overload one shard: lease batches of tokens to gateways or limit very large plans locally. Send 429 with Retry-After computed from the bucket.

    Work through the full interview at /system-design/interviews/rate-limiter.

    Scene: The counter store is back online and every gateway checks it before forwarding. Acme sends 70 requests per second; about 50 per second pass and the rest are refused.

    Key idea: Accuracy, latency and availability pull against each other: shared counters for accuracy, regional stores for latency, fail-open with a local cap for availability.