← Back to System Design, page 2

system-design-0036 · Medium mid

Design a distributed rate limiter for an API gateway that serves about 1 million requests per second.

Run the limiter inside the gateway, look up the rule for each request's key, and keep token-bucket state in a sharded Redis cluster updated atomically with a Lua script, so every gateway instance sees the same counts. Return 429 with Retry-After when limited. At 1M requests per second you need about 10 or more Redis shards under a stated per-shard assumption, plus a local fallback and a decision on failing open or closed.

Full answer

Requirements

Functional:

  • Limit requests per key (API key, user ID or IP) per rule, for example "free plan: 100 requests per minute", "login: 5 per minute per account".
  • Different rules per endpoint and plan, changeable without redeploying.
  • Tell clients when they are limited and when to retry.

Non-functional:

  • Adds under about 1 to 2 ms to request latency.
  • Accurate enough across many gateway servers (small overshoot is acceptable).
  • The limiter failing must not take down the API.

Capacity estimates

Assumptions: 1M requests per second at peak across 100 gateway instances; 50M distinct keys active per day; about 100 bytes of state per key (key name, token count, last refill timestamp, overhead); one Redis node handles about 100,000 simple script calls per second (an assumption to verify with load tests).

  • State memory: 50M x 100 B = 5 GB. Small; it fits in memory across a few nodes.
  • Operations: one atomic check per request = 1M operations per second. At 100k per node that is 10 primary shards; plan 15 to 20 for headroom, each with a replica.
  • Network: each call is a few hundred bytes, so about 1M x 300 B = 300 MB/s across the cluster, fine for a data centre network.

API and responses

Internal check, called by the gateway:

allow(key="apikey:abc123", rule="free_api", cost=1) -> {allowed: bool, remaining: int, reset_ms: int}

Client-facing behaviour:

HTTP/1.1 429 Too Many Requests Retry-After: 12 RateLimit-Limit: 100 RateLimit-Remaining: 0

(The RateLimit-* header names follow an IETF draft; many APIs use X-RateLimit-*.)

Data model

Rules (in a config store, cached in each gateway): rule_id, match (path, method, plan), key_type (api_key, user, ip), capacity, refill_per_second. State (Redis): hash rl:{rule}:{key} with fields tokens and ts, with an expiry so idle keys disappear.

High-level design

mermaid
flowchart LR
  C[Clients] --> LB[Load balancer]
  LB --> G1[Gateway + limiter]
  LB --> G2[Gateway + limiter]
  G1 --> RC[(Redis cluster: bucket state)]
  G2 --> RC
  CFG[(Rule config store)] -. push / poll .-> G1
  CFG -. push / poll .-> G2
  G1 --> S[Backend services]
  G2 --> S

Atomic token bucket

Read-modify-write from the gateway would race between instances, so the check runs as one Lua script inside Redis (shown for illustration, not run here):

lua
-- KEYS[1] = bucket key; ARGV[1] = capacity, ARGV[2] = tokens per ms, ARGV[3] = now in ms
local cap  = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now  = tonumber(ARGV[3])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= 1 then
  tokens = tokens - 1
  allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate) + 1000)
return allowed

Keys hash to shards, so each bucket lives on exactly one shard and the script stays atomic.

Bottlenecks and how to handle them

  • Hot keys: one huge customer hitting one shard. Give such keys a local pre-allocation: each gateway takes a batch of tokens (say 50) from Redis and spends them locally, cutting Redis calls by the batch size at the cost of small overshoot.
  • Latency: keep Redis in the same zone as gateways; pipeline calls; skip the check for unlimited internal traffic.
  • Redis failure: decide per rule. Fail open (allow) for normal API traffic so an outage of the limiter does not become an outage of the API, with a coarse local in-memory limit as a safety net. Fail closed for security limits like login attempts.
  • Clock differences: pass Redis TIME or a single gateway clock; the math.max(0, ...) guard prevents negative refill if clocks disagree.
  • Multi-region: limits are usually enforced per region with the global quota divided between regions; exact global limits need cross-region coordination and add latency.

Trade-offs

Central Redis state gives accurate shared limits but adds a network hop. Purely local limits (each gateway allows limit / number_of_gateways) are zero-latency but inaccurate when traffic is uneven across gateways. Token batching sits between the two. Token bucket allows bursts, which suits most APIs; use sliding window counters if bursts are a problem.

By level

Fresher: Explain where the limiter sits, describe the token bucket, show the 429 response, and explain why counts must be shared across servers. A fresher should also describe the 429 response and Retry-After header.

Mid: Size Redis for the request rate, make the update atomic, design rule configuration, and choose per-rule failure behaviour. Expect a stated per-shard assumption behind the Redis sizing.

Senior: Handle hot keys with local batching, multi-region quotas, clock skew, limiter observability, and the accuracy versus latency versus availability trade-off across thousands of gateways. The senior answer justifies fail-open or fail-closed per rule.

Key points

  • Enforce in the gateway with shared state in a sharded Redis cluster
  • Make the check atomic with a Lua script per bucket
  • About 1M checks per second needs about 10+ shards under a stated per-node assumption
  • Return 429 with Retry-After and remaining-quota headers
  • Decide fail-open versus fail-closed per rule and handle hot keys with local token batches

Common mistakes

  • Doing read-then-write from the gateway and racing between instances
  • Failing closed for all traffic when Redis is down
  • Ignoring hot keys on a single shard
  • Promising exact global limits across regions without discussing latency

Follow-ups

  • How would you limit by cost (an expensive endpoint counts as 10)?
  • How do you change a customer's limit instantly?
  • How would you test that the limiter overshoots by less than 5%?

Tips

  • Ask which key and which algorithm the product needs
  • Size Redis from requests per second, not from memory
  • State your fail-open policy explicitly

Evaluation rubric

  • Requirements include latency and failure behaviour
  • Capacity math for operations and memory with stated assumptions
  • Atomic distributed algorithm
  • Covers hot keys, failures, multi-region and trade-offs