Rate limiter system design: fair limits at a million requests a second
How to design a rate limiter for a public API, in real interview order: numbers, API and headers, the gateway design, one request end to end, Redis keys and the atomic script, picking the algorithm, counting across hundreds of nodes, and what happens when the limiter itself fails.
The 1-minute answer
How this page follows the interview
Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.
Requirements and numbers
Agree what is limited and by what, then size it. Change any input: each number comes with the decision it forces, and those decisions come back in the design and data sections.
Functional
- Limit requests per caller (API key, user, or IP) per rule
- Several rules at once: per second (protection) and per day (plan quota)
- Over the limit: reject with 429 and say when to retry
- Change limits and per-customer overrides without a deploy
Non-functional
- Adds about 1 ms (p99 ≤ 2 ms) to every request
- Never takes the API down: the limiter failing is not an outage
- Accurate enough: within ~10% for big limits, exact for small strict ones
- Works across hundreds of gateway nodes and several regions
Out of scope (say it)
DDoS appliances, billing itself, bot detection models.
Capacity calculator
Every input is an assumption 🔶: say it out loud. 100K calls/s per shard is a common planning number (third party), not a Redis guarantee; measure your own.
- Every request is a check. Unlike most designs, reads and writes are the same thing here: each request reads and updates a counter.
- Count active keys, not all keys. Counters expire with their window, so memory depends on who is calling right now.
- Look for the hottest key. Total load spreads across shards; one huge caller doesn't.
Core entities and the API
A limiter has three faces: the internal check, what the client sees, and how admins change rules. What they listen for: 429 with Retry-After, headers on every response, and rules that change without a deploy.
| Entity | Key fields | Note |
|---|
How a token bucket decides
This is the maths inside the check for one request. The bucket holds up to capacity tokens and refills at a steady rate; a request takes cost tokens or is rejected. Change the numbers and watch each line.
Where each number comes from
- Rate and capacity: the rule for the caller's plan, plus any override. AWS API Gateway's default per Region is 10,000 requests/s with a bucket of 5,000. ✅ AWS docs
- Tokens and time: two fields stored in Redis per key. No timer refills anything: the refill is computed when the next request arrives. ✅ Redis docs
- Cost: 1 for most calls; more for expensive ones. GitHub's secondary limit charges 5 points for writes and 1 for reads. ✅ GitHub docs
- Retry-After: tokens missing ÷ refill rate, rounded up to whole seconds. 🧭
The same maths runs inside the Lua script in §05, so two gateways can't both spend the last token.
High-level design
Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.
Walk one request, box by box
From rules loading at start-up, through an allowed request and a rejected one, to a Redis outage. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.
Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.
What happens to a 429, and what a good client does
Rejecting is only half the job. The other half is making sure the rejection slows the caller down instead of starting a retry storm.
Data and database choices
"Where do the counters live?" is guaranteed. Counters and rules have opposite needs: counters are hot, tiny and disposable; rules are cold, tiny and need history.
| Data | Pick | Considered | Why not those |
|---|
The one script to know
-- rl_check: token bucket, atomic on the key's shard.
-- KEYS[1] = rl:{caller}:rule
-- ARGV = rate/s, capacity, now (ms), cost
local rate, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
local now, cost = tonumber(ARGV[3]), tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap -- new key = full bucket
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)
local ok = tokens >= cost
if ok then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000))
local wait = ok and 0 or math.ceil((cost - tokens) / rate * 1000)
return { ok and 1 or 0, math.floor(tokens), wait }Redis runs a script as one step, so no other command on that shard runs in between. ✅ GitHub uses Lua
Why one script, not three commands
- Separate GET then SET races. Two gateways read "1 token", both allow, both write 0. Figma called out this race for a token bucket. ✅ Figma 2017
- INCR then EXPIRE can leave a key with no TTL if the process dies in between. Redis 8.8's INCREX does both in one command. ✅ Redis docs
- All of a caller's rules in one call. Keys share a hash tag,
rl:{ak_77f1}:…, so they sit on one shard and one script checks them all. 🧭 - One clock. Pass the gateway's time in (or use Redis TIME), never mix the two. GitHub's reset header wobbled by a second when they did. ✅ GitHub 2021
More database questions
Deep dive: picking the algorithm
Same caller, same limit (10 a minute here), five algorithms. Each dot is a request: filled means allowed, hollow means rejected, a tail means it waited in a queue. The shaded band is the busiest minute. Pick a traffic pattern and watch the verdict change.
What happened
All five on this pattern
| Algorithm | Allowed | Busiest min | Waits |
|---|
The five, in one line each
- Fixed window: one counter per minute. Simplest; allows up to 2× at the boundary. ✅ Figma 2017
- Sliding log: a timestamp per request; exact; memory grows with the limit. ✅ Figma 2017
- Sliding window counter: this minute + last minute × overlap. Two numbers; Cloudflare measured 0.003% wrong decisions. ✅ Cloudflare 2017
- Token bucket: steady refill + burst capacity. Two numbers; used by Stripe, AWS API Gateway and Envoy. ✅ Stripe · AWS · Envoy
- Leaky bucket: as a meter it's a token bucket (Shopify: 40, leaks 2/s); as a queue it smooths output but makes callers wait. ✅ Shopify docs
How to choose
Per-second protection on a public API: token bucket. You want short bursts to pass and the steady rate enforced. 🧭
Per-day or per-month quota: a window counter (fixed is fine; a day's boundary burst is small next to the quota). 🧭
Small, strict limits (5 logins a minute): sliding log, because it's exact and the log is at most 5 entries. 🧭
Pacing a fragile downstream (an SMS provider at 50/s): a leaky bucket queue. 🧭
Deep dive: one count across many gateways
Two hundred gateway nodes must agree on one count per caller, in under a millisecond. There are three ways to keep the count, and each one wins somewhere. Pick a preset, then change the numbers.
| Strategy | Lets through/s | vs limit | Redis calls/s | Adds |
|---|
Central assumes an over-limit cache, so rejected traffic costs about one call per node per second. Local + sync's worst case lets a whole sync interval through after the limit is crossed. Closed-form teaching numbers. 🧭
The three strategies
- Central: one atomic call per request to the caller's Redis shard. Exact; costs a round trip; a very hot key overloads one shard. ✅ GitHub · Stripe
- Local only: each node allows limit ÷ nodes. No network; wrong whenever traffic is uneven. 🔶 arithmetic
- Local + sync: count in memory, push the total every 50–100 ms. Few calls; overshoot ≈ rate × interval. 🔶
What real systems do
Cloudflare counts inside each data centre, not globally: anycast keeps a client on one location, and a central store would be too slow. ✅ 2017
Envoy recommends a local token bucket in front of the global service to reduce load on it. ✅ docs
GitHub shards counters over Redis clusters chosen by the application, one primary and several replicas each. ✅ 2021
A caller's lifecycle
From the caller's side, a limit is a small state machine. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.
Edge cases interviewers love
Failure, monitoring and recovery
A limiter is in front of everything, so its failures are everyone's failures. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.
Tracing it back: healthy vs Redis timing out
Every span carries the caller key and rule id. In the bad trace the check hits its 5 ms deadline and the gateway falls back to its local bucket: the request still goes through, a little later.
How one failure becomes three
What you'd alert on (SLOs)
| Signal | Target | Alert |
|---|
Incident playbook
The resilience toolkit
Name the pattern, then say where it goes in this design.
Making it fast, and who owns what
The limiter's whole budget is about a millisecond, on every request. The network hop dominates, so the fastest check is the one that doesn't leave the gateway. Bars are sizing estimates, not measured figures.
| Team | Owns | Paged when… |
|---|
Senior follow-ups beyond the happy path
Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.
Practice ladder
Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.
Sources
- Scaling your API with rate limiters, Stripe Engineering (30 Mar 2017)
- An alternative approach to rate limiting, Figma (12 Apr 2017)
- How we built rate limiting capable of scaling to millions of domains, Cloudflare (7 Jun 2017)
- How we scaled the GitHub API with a sharded, replicated rate limiter in Redis, GitHub (5 Apr 2021, updated 2023)
- RFC 6585: Additional HTTP Status Codes (429 Too Many Requests), IETF (Apr 2012)
- RateLimit header fields for HTTP, draft-ietf-httpapi-ratelimit-headers-11, IETF (23 May 2026)
- Rate limits for the REST API, GitHub Docs (checked Oct 2026)
- REST Admin API rate limits, Shopify (checked Oct 2026)
- Amazon API Gateway quotas, AWS Docs (checked Oct 2026)
- Global rate limiting, Envoy docs (checked Oct 2026)
- envoyproxy/ratelimit README, GitHub (checked Oct 2026)
- Rate limiting rules: parameters, Cloudflare Docs (checked Oct 2026)
- INCREX command, Redis Docs (Redis 8.8, checked Oct 2026)
- Handling Overload, Google SRE book (2016)
- Distributed rate limiter, Hello Interview (third party, used to cross-check interview expectations)
Company sources date from 2017 to 2021 (Stripe, Cloudflare, Figma, GitHub); docs and the IETF draft were checked in October 2026. The RateLimit headers are still a draft, and current internals at these companies may differ. In an interview, say so.
System Design Mastermind · Classics
Series homeAll of Classics
6 published · 4 comingThe problems almost every loop draws from.
Uber system design, reverse-engineered: from tap to pickup
In-memory geo index sharded by map cell → rank nearby drivers by road ETA → offer to one driver with a 15 s timeout → accept with compare-and-set → push updates to both apps.
Rate limiter system design: fair limits at a million requests a second
Check every request once in the API gateway → one atomic Lua script per request on the caller's shard of a sharded Redis (token bucket for per-second, window for per-day) → 429 + Retry-After, or forward with RateLimit headers → local cache for keys already over → each rule fails open or closed on purpose.
WhatsApp system design: chat, offline delivery and the three ticks
One long-lived encrypted connection per device → the chat server stores a copy per recipient device in a replicated offline queue, then acks (✓) → session lookup, forward or push → the device saves and acks, the copy is deleted (✓✓) → a read receipt when opened. Client-made ids and dedupe at both ends, backoff with jitter on reconnect, Sender Keys for groups.
Ticketmaster system design: selling seats without double-booking
Cached reads for browsing → a seat inventory with one row per seat, sharded by event → a hold is one conditional UPDATE (only if free or expired) with a 10-minute timer → pay with a client-made idempotency key → confirm only if the hold is still yours, plus an outbox for tickets. A waiting room admits fans at the rate booking can serve.
News feed system design: fan-out, celebrities and ranking
Write each post once → fan-out workers push its id into active followers' capped Redis timelines → accounts above ~1M followers are merged at read time instead → the feed service gathers ~1,500 candidates, a light model trims them, a heavy model predicts actions, a weighted sum orders them → deletes and blocks are checked at read time, pages use a cursor.
Notification system design: push, email and SMS without spam, drops or duplicates
One Notify API with an idempotency key → a router checks dedupe, preferences, caps and quiet hours, picks live devices → per-channel queues with a transactional lane apart from bulk → workers call APNs, FCM, email and SMS with priority, expiry and a collapse id, retry 429s with backoff and delete dead tokens → campaigns paced below the provider quota, OTPs fall back to SMS.