{}DSA Atlas

Design a Distributed Rate Limiter

A rate-limiting service for an API platform handling millions of requests per second — rules and configuration, placement (gateway, sidecar, library), the algorithm choice, atomic Redis implementation, latency budgets, fail-open vs fail-closed, local batching and approximate limits, multi-region limits, and observability.

Intermediate → Advanced5 interview questions

1. Requirements

Functional

  • Limit requests by configurable keys: API key, user, IP, tenant, endpoint — e.g., free tier: 100 req/min; pro: 2,000 req/min with bursts of 200.
  • Return 429 Too Many Requests with Retry-After and rate-limit headers.
  • Rules change without deploys; shadow mode for new rules.

Non-functional

  • Adds < 2 ms p99 latency.
  • Handles 1M+ checks/s.
  • Highly available; a limiter failure must not take down the API.
  • Accuracy: small overshoot acceptable for most rules; exact for security rules.

2. Estimation

QuantityValue
Checks1M/s peak
Active keys10M
State per key (token bucket)~50 B (key + tokens + timestamp) → ~500 MB + overhead
Redis throughput~100k–200k ops/s per shard → ~10 shards with headroom

3. High-level design

clients API gatewayrate-limit filterrules cached in memory rules config store(push / watch) Redis Clustersharded by key metrics / logs429s per rule backendservices allowed 429
One atomic Redis round trip per request; rules pushed to the gateway, never read per request.

Flow: request arrives → gateway authenticates and extracts keys (API key, IP, route) → finds matching rules (in-memory) → for each rule runs an atomic script in Redis (all rules for one request can be batched in a single script/pipeline) → allowed: forward and add RateLimit-* headers; denied: return 429 with Retry-After.

4. The atomic check

lua
-- KEYS[1] = bucket key; ARGV = capacity, refill_per_ms, now_ms, cost
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local cap, rate, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
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 = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate) * 2)
local retry_ms = allowed and 0 or math.ceil((cost - tokens) / rate)
return { allowed and 1 or 0, math.floor(tokens), retry_ms }

The algorithms themselves (token bucket, sliding window variants, in-process implementations) are covered in depth in Backend: rate limiting, and the object-oriented design in LLD case studies II.

5. Deep dives

Scaling beyond one Redis round trip per request

central counter (Redis) gateway Alocal bucket: 40 tokens gateway Blocal bucket: 12 tokens gateway Clocal bucket: 0 → reserve reserve tokens in batches of 50
Batching reservations cuts store traffic ~50× at the cost of slight inaccuracy.
  • Batch reservations: each node takes N tokens at a time from the central bucket and spends them locally.
  • Periodic sync: nodes count locally and push deltas every 100 ms; the central store returns the global count.
  • Sticky routing (consistent hashing of API key → gateway node) makes local limiting exact without a shared store, until nodes change.

Hot keys

One giant tenant hammering one Redis key: shard that key into sub-buckets (key#0..7, each with 1/8 of the limit, chosen randomly) or use local reservation for that tenant.

Failure handling

FailureBehaviour
Redis timeout (> 5 ms)fail open for normal API limits; log + metric
Redis shard downreplica promotion; fall back to local in-memory limits meanwhile
Security limits (login, OTP)fail closed or strict local limit
Config store downkeep using last-known rules in memory

Multi-region

Each region enforces its share locally; counters replicated asynchronously for monitoring; per-tenant home region for strict quotas. Accept that a client spraying all regions can briefly exceed the global limit.

6. Client contract

HTTP
HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 12
Content-Type: application/problem+json

{"type": "https://api.example.com/errors/rate-limited", "title": "Too many requests", "status": 429}

7. Trade-offs summary

DecisionChoiceWhy
Algorithmtoken bucket (+ sliding window for some)bursts + O(1) state
StoreRedis Cluster + Luaatomic, ~0.5 ms
Placementgateway (+ service-level for business limits)reject early
Failure policyfail open (most), closed (security)availability vs safety
Global limitsper-region split + async reconciliationlatency over precision

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.