Design: distributed rate limiter

In one sentence

Enforce limits at the gateway with rules cached in memory and counters in a regional Redis updated by one atomic script; answer excess with 429 and Retry-After, and fail open if the limiter breaks.

Rules are matched from memory; the only network hop is one atomic Redis call, and each rule decides what happens when that call fails.

How it works

  • Enforce at the gateway: one place, and excess traffic is rejected before the backend does any work.
  • Check-then-set from two nodes races; one atomic Redis script that counts and decides closes it.
  • Rules come from a config store and are matched from memory, never fetched per request.
  • An exact global counter costs a cross-region round trip; regional counters trade a small overshoot for speed.
  • If Redis fails, fail open to a local limit; fail closed only for security limits like login.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your limit is 100 requests/min per API key. During bursts, logs show keys getting 130+ requests through in one minute. Each of the 20 gateway pods runs GET counter, compares it with 100, then INCR. What is the best fix?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: cap requests per client (API key, user or IP) and per endpoint, from rules that change without a deploy; tell rejected clients when to retry. Non-functional: add ~1 ms at most to each request (assumed budget), count correctly across every gateway node, and never become the outage.

Scale (assumed): 100k requests/s at peak and 10M active keys.

Questions I'd ask:

  1. Is the limit a hard contract (billing, abuse) or a fairness guard where a small overshoot is fine?
  2. One global limit, or one per region?
  3. If the limiter is down, do we let traffic through?

Where it lives

  • Client: throttling and backoff in the SDK. Polite, but a client can skip it; never trust it.
  • Gateway (my default): one place, and it rejects before the backend does any work.
  • Service: a library or sidecar, for limits only the service understands (cost per query, caps per resource).

Architecture

Rules (key, limit, window, on_error) live in a config store and reach each node by push or polling; nodes match them from memory, never on the request path. Counters live in a regional Redis Cluster, sharded by client key. Per request: identify the client → match the rule → one Redis call that counts and decides → forward, or reply 429. The algorithm is a parameter of the rule; they are compared in Rate limiting.

The hard parts

  1. The race. GET, compare, SET from two nodes at once: both read 99 and both allow. The fix is one atomic step: a Lua script, or an INCR whose returned value decides.
  2. Accuracy vs latency. One global counter is exact but puts a cross-region round trip on every request. Regional or local counters are fast and slightly wrong. Choose per rule.
  3. Failure. A limiter that blocks traffic when Redis is down has become the outage: fail open, except on security limits.
Code Gateway middleware: atomic count, fail-open, 429 headers
pythonGateway middleware: atomic count, fail-open, 429 headers
import redis.asyncio as redis
from redis.exceptions import RedisError
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()
r = redis.Redis(socket_timeout=0.005)   # 5 ms budget: the limiter is never the slow hop

# Count, set the TTL and read it back in ONE atomic step. Fixed window to keep it
# short; a real rule would pick the token bucket from the rate-limiting concept.
HIT = r.register_script("""
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
return {n, redis.call('TTL', KEYS[1])}
""")

@app.middleware("http")
async def rate_limit(request: Request, call_next):
    rule = RULES.match(request)             # in-memory copy, refreshed in the background
    client = request.headers.get("x-api-key") or request.client.host
    try:
        n, ttl = await HIT(keys=[f"rl:{rule.id}:{client}"], args=[rule.window_s])
    except RedisError:                      # timeout or Redis down
        if rule.fail_closed:                # login, OTP: safety over availability
            return JSONResponse({"error": "limiter unavailable"}, status_code=503)
        n, ttl = LOCAL.hit(rule, client), rule.window_s   # fail open to a per-node limit
    # IETF draft-12 syntax (Nov 2026): a = available quota, w = window in seconds
    headers = {"RateLimit": f'"{rule.id}";a={max(0, rule.limit - n)};w={ttl}'}
    if n > rule.limit:
        return JSONResponse({"error": "rate limit exceeded"}, status_code=429,
                            headers={**headers, "Retry-After": str(ttl)})
    response = await call_next(request)
    response.headers.update(headers)
    return response
Real example

An API allows 100 requests/min per key behind 20 gateway pods.

  • v1, in-memory counters: each pod allows 100, so a client spread over the fleet gets up to 2,000/min.
  • v2, Redis GET → compare → SET: a burst of 300 concurrent requests reads the same count on several pods, and more than 100 pass.
  • v3, one Lua script: exactly 100 pass; the other 200 get 429 with Retry-After: 23.

Then a Redis node fails over: for those seconds each pod applies a local limit and logs it, instead of rejecting every customer.

Trade-offs +3 · −3

+ You gain

  • One atomic Redis call per request: correct counts across any number of gateway nodes.
  • Rules change through config: no deploy, and no lookup on the request path.
  • Rejecting at the edge is cheap: excess traffic never reaches the application servers.

− You pay

  • Redis is now on the path of every request: one more round trip and one more dependency to keep available.
  • Exact global limits and low latency conflict: multi-region setups accept overshoot or skewed quotas.
  • Failing open means a limiter outage is also a window with weaker protection.

Use it when

Any public or multi-tenant API served by more than one node: per-key quotas, login and signup throttles, protecting a shared dependency.

Avoid it when

A single-node service, where an in-process bucket is enough. Or as your overload protection: limits cap clients, not total load, so add load shedding (Backpressure & load shedding).

Numbers to know 5
  • Memory (assumed): 10M active keys × ~100 B per counter ≈ ~1 GB. Counter memory is rarely the constraint.
  • Throughput: 100k checks/s (assumed) is about one Redis instance's ~100k simple ops/s (rule of thumb): shard by client key.
  • Cloudflare (2017): its sliding-window counters wrongly allowed or limited only 0.003% of 400M requests.
  • Envoy's rate-limit filter: 20 ms default timeout; on errors it lets traffic through unless failure_mode_deny is set (then 500).
  • N regions with independent counters: worst case N × the limit; with a static split, a one-region client gets 1/N.
Common pitfalls 4
  • GET, compare, then SET: two gateways read the same count and both let the request through.
  • INCR and EXPIRE as two separate calls: a crash between them leaves a counter that never resets.
  • Loading rules from a database on every request: the limiter becomes the slowest hop.
  • Failing closed everywhere: a Redis blip turns into a full API outage.
Interview questions 3

Answer out loud first, then reveal.

Redis goes down. What does your limiter do?Show answer

It depends on the rule, and I decide it before the incident. For general API limits I fail open: the Redis call has a timeout of a few ms, and on error each gateway applies a conservative in-memory limit, so abuse is still capped per node. For login, OTP or paid operations I fail closed with a 503. I alert on the fail-open rate, because a limiter that silently allows everything looks healthy.

How do you enforce one limit across three regions?Show answer

First I ask how exact it must be. For a fairness limit I count per region and accept that a client spreading traffic can exceed it; or nodes count locally and sync asynchronously, which bounds the overshoot to one sync interval. For a billing quota I want one source of truth: a global counter, with each region leasing chunks of quota so the cross-region call is not on every request. Exact, fast, multi-region: pick two.

How do you keep the limiter from slowing every request?Show answer

Three things. Rules are matched in memory, so the only I/O is one Redis script call on a pooled connection in the same region. Clients already over the limit are remembered locally until their window resets, so repeat offenders cost no Redis call at all; Cloudflare does this. And for very hot keys, each node leases a batch of tokens and spends them locally. I track the limiter's own p99 as an SLO.

Deep dive 3

The race and the atomic fix

Read-then-write is two round trips, and any other node can run between them. Three fixes, simplest first. Decide on the result of INCR: the increment is atomic and returns the new count, so no two requests see the same value. Set the TTL in the same step: Redis's own docs warn that INCR followed by a separate EXPIRE leaks a counter with no expiry if the client dies in between, and that counter eventually blocks the client for good. A Lua script for anything richer (token bucket, sliding window): Redis runs a script atomically, blocking everything else meanwhile, so keep it O(1). Read the time with Redis TIME inside the script, not from the gateway's clock. In Redis Cluster a script may only touch keys passed in KEYS, all in one slot: use one key per client and rule.

Multi-region: local vs global accuracy

A global limit of 1,000/min across three regions has three designs. One global counter: exact, but every request pays a cross-region round trip, and that region's outage breaks limiting everywhere. Per-region counters: fast and independent; a client spreading traffic can reach 3× the limit, and a static split (333 each) starves the one region the client really uses. Local counting with async sync: nodes count in memory and flush to the shared store on a short interval, so overshoot is bounded by what arrives in one interval. Cloudflare counts per point of presence, because anycast sends an IP's traffic to the same one, and increments asynchronously. Envoy applies two stages: a local token bucket absorbs bursts before the global service is called. I'd keep exact global counters for billing quotas only.

Failure modes and what the client sees

The limiter sits on every request, so its failure mode is a product decision. Give the Redis call a tight timeout (Envoy's rate-limit filter defaults to 20 ms) and choose per rule: fail open for general API protection, as Stripe's limiters do, ideally to a conservative in-memory limit; fail closed for login, OTP and anything that costs money per call. Alert on the fail-open rate, or a dead limiter goes unnoticed. Rejected requests get 429 (RFC 6585) with Retry-After; without it clients retry at once and deepen the overload (Retries, backoff & circuit breakers). Send the remaining quota on successful responses too: GitHub uses x-ratelimit-remaining and x-ratelimit-reset, while the IETF RateLimit header is still an Internet-Draft (draft-12, Nov 2026). Launch new rules in shadow mode: log what they would block, then enforce.