system designs

Rate Limiter

3 deep dives · 2 follow-ups · updated Oct 27, 2026

1. Functional requirements

  1. Enforce a configurable limit per client per endpoint.
  2. Reject over-limit requests with 429 and Retry-After.
  3. Tell clients where they stand: X-RateLimit-Limit, -Remaining, -Reset on every response.

Below the line: per-IP fallback for unauthenticated routes, rules admin UI.

Scale: 100K requests/s through the limiter, the only number that matters; one Redis node does ~100K ops/s, so that number alone decides a Redis cluster sharded by client key. Storage drives nothing: 10M clients × a few rules × ~50 bytes < 2 GB. The design is driven by latency on every request and what happens when the counter store dies.

2. Non-functional requirements

  1. Latency under 10 ms: it sits in the path of every request
  2. Availability: if the limiter dies the API must not die with it, fail open or fail closed
  3. Accuracy across servers: twenty gateways share one count per client; approximate is fine, 20x is not

3. Core entities

  • Clients
  • API keys
  • Rules: scope = endpoint + tier, limit, window; change rarely
  • Counters: one per client per rule, live state, gone at window end

The Rule vs Counter split is the design: rules are config, counters are the hot path.

4. API routes

Identity from the Authorization header, never the body; the IP when there is no key. Simple enough to start; check is a call inside the gateway, not a route clients see.

Check                                  hot path, inside the gateway
check(apiKey, endpoint)
returns: allowed, remaining, resetAt

Put rule                               admin, per endpoint or tier, never per key
PUT /rules
body: scope { endpoint, tier }, limit, window
returns: ok

5. High-level design

The simplest system that satisfies the two routes. One client, one load balancer, one gateway with the limiter as middleware, the services behind it, one rules database. The deep dives change this picture.

Boxes, drawing order: client · load balancer · gateway with the four limiter steps inside · services · rules DB under the gateway, admin beside it.

High-level design

Four steps per request, inside the gateway:

  1. Identify the client from the API key in the Authorization header; no key, use the IP.
  2. Identify the endpoint.
  3. Match the rule for (endpoint, tier), increment this client’s counter, compare it to the limit. Increment-and-compare is one atomic step.
  4. Under the limit: route, with X-RateLimit-Limit, -Remaining, -Reset. Over: 429, Retry-After = seconds to the window end.

Data model:

Rule     scope (endpoint, tier), limit, window
Counter  (apiKey, endpoint, window) → count

Rules are loaded into gateway memory at startup and refreshed every minute or on a change event; the database is where rules are edited, never read on the hot path. In v1 the counter lives in the gateway’s own memory.

Parked flaws, fixed in the deep dives: the counter lives in one gateway’s memory, so add a second gateway or restart this one and the count is wrong (6.1); the counter store goes down and every request waits on something dead (6.2); 100K/s all hit the counter store (6.3).

6. Deep dives

Order in the room: 6.1 must · 6.2 if time · 6.3 one line. Each deep dive opens with three spoken sentences: Problem, Pick, Cost. Everything under them is what you say when the interviewer digs.

6.1 Shared counters across gateways: Redis, fixed window

Problem. Three gateways each see a third of a client’s traffic, so the client gets 3x the limit, and a restart resets everyone to zero. Pick. One Redis shared by every gateway; the counter is a fixed-window key, rl:{apiKey}:{endpoint}:{minute}, bumped with INCR and expired with the window. Cost. One network hop, ~1 ms of the 10 ms budget. Rejected: vertical scaling of one gateway, hardware and a cap; sticky routing, the LB hashes the API key so a client always lands on one gateway and the counter stays local, but hot clients skew the gateways, a dying gateway loses its clients’ counts, and rebalancing moves clients to a gateway with no memory of them.

Draw: Redis beside the gateways; the counter moves out of gateway memory.

6.1 Shared counters

Flow

  1. The key is the client, the endpoint and the current minute: rl:{apiKey}:{endpoint}:{minute}, minute = unix_time / 60 read from the clock.
  2. Every request runs INCR on that key and compares the number it gets back to the limit held in gateway memory.
  3. Safe across gateways because Redis runs one command at a time: INCR reads and writes in one step, so no two requests ever get the same number back.
  4. Reset is free because the minute is in the key: a new minute is a new key, and the old one got EXPIRE 60 the moment INCR returned 1.

Limit 3/min on /search:

10:00:05  rl:k:/search:600   INCR → 1, EXPIRE 60   allow
10:00:20  …:600              INCR → 2              allow
10:00:41  …:600              INCR → 3              allow
10:00:50  …:600              INCR → 4              429, Retry-After: 10
10:00:58  …:600              INCR → 5              429
10:01:02  …:601              INCR → 1, EXPIRE 60   allow
10:01:05  …:600 expired

Follow up: three calls at the end of one minute and three at the start of the next is six in about 20 seconds. Isn’t the limit 3 a minute?

Answer: That is the fixed window’s boundary burst, up to 2x the limit across a boundary. The upgrade is a token bucket: Redis stores two numbers per client, tokens left and last refill. Each request adds the tokens that dripped in since then, capped at the bucket size, takes one, and writes both back. That is read-compute-write, three steps instead of one, so the three steps go in a Lua script, which Redis runs start to finish with nothing interleaved, as safe as INCR. Refill rate = the average allowed, bucket size = the burst allowed. Cost: a script instead of a single command.

6.2 The counter store goes down: fail open, with guards

Problem. Redis is down or slow and every request waits on it; a safety rail takes the whole API with it. Pick. Fail open: on a Redis error the gateway lets the request through under a coarse local limit. Fail closed only where the limiter is the protection: login attempts, password resets, payment retries. Cost. While Redis is down the services are exposed to overuse, loosely limited rather than unlimited. Rejected: fail closed for a public API, because then no one can use it; the limiter is a safety rail, not the product.

Draw: a local fallback counter inside the gateway; a timeout and circuit breaker on the Redis call; an alert on time in fail-open.

6.2 Fail open

Flow

  1. A coarse local limit in each gateway’s memory, ~10x the rule, so open means loosely limited, not unlimited.
  2. A short timeout plus a circuit breaker around the Redis call, so a slow Redis does not become a pool-exhaustion cascade: after a run of errors the gateway stops calling Redis for a while and counts locally.
  3. An alert on time spent in fail-open: it is a degraded mode, never a steady state.

6.3 100K/s: a Redis cluster sharded by client

Problem. 100K requests/s all hit one Redis node, which does about 100K ops/s; there is no headroom. Pick. A Redis cluster, keys sharded by hashing the API key, so a client’s counter always lands on one node; add nodes as traffic grows. Cost. A cluster to run, and one huge client is one node’s problem.

6.3 Sharded counters

Final design

Final design

Trade-offs, the two to say:

  • Shared Redis over sticky routing: one count per client whichever gateway it hits, at the cost of a ~1 ms hop on every request.
  • Fail open over fail closed: the limiter is a safety rail, not the product; an outage costs some overuse, not the API.

Monitor: the limiter’s own p99 against the 10 ms budget; the 429 rate overall and per client, a spike is abuse or a broken rule; Redis errors; time spent in fail-open.


Study only, not for the room: the 6.3 follow-up, the other algorithms, the headers, the rules engine.

6.3 follow-up

Follow up: traffic grows 10x and the biggest client becomes a hot key on one node. What then?

Answer: Count locally per gateway and sync to Redis every ~100 ms: a little accuracy for much less traffic. Or split a huge client’s key into sub-buckets, rl:{apiKey}:{endpoint}:{minute}:{0..n}, each with limit / n, spread across nodes.

Algorithms

  • Fixed window (6.1): one INCR per request, O(1); boundary burst up to 2x.
  • Token bucket (6.1 upgrade): two numbers in a Lua script, O(1); bursts up to the bucket size, the average held to the refill rate.
  • Sliding window log: every request timestamp in a sorted set, count those in the last window. Exact, memory per request.
  • Sliding window counter: weighted previous + current fixed window; 30% into the current minute counts 0.7 × previous + current. O(1), fixes the boundary flaw, approximate.

Headers

Every response carries X-RateLimit-Limit, X-RateLimit-Remaining (limit − the number INCR returned, floored at 0) and X-RateLimit-Reset (unix seconds of the window end); a 429 adds Retry-After in seconds.

Rules engine

Rules live in the database keyed by scope, endpoint + tier: “100/min on /search for the free tier”. Each gateway loads them all at startup, a few hundred rows, and refreshes every minute or on a change event; matching is a lookup on (endpoint, tier), most specific wins. The database is never on the hot path.