All posts
System Design Mastermind · Part 12
  • System design
  • Distributed systems
  • Interview prep

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.

23 Oct 2026 · 30 min read · interactive

Share

The 1-minute answer

Run the limiter in the API gateway, so every request is checked once, before any work. Identify the caller from its API key (IP only when there's no key), find the matching rules in memory, and check them with one atomic Lua script on the caller's shard of a sharded Redis: a token bucket for per-second bursts, a window counter for daily quotas. Allowed requests go on with RateLimit headers; the rest get 429 and Retry-After and never reach the backend. Keys already over the limit are answered from a local cache, and very hot keys are counted locally and synced. If Redis is slow, each rule fails open to a local bucket, except login and OTP, which fail closed. Rules are config, pushed in seconds, and every new rule starts in shadow mode.

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.

✅ Seen: a company or RFC said so (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

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.

Three rules for this estimate
  1. Every request is a check. Unlike most designs, reads and writes are the same thing here: each request reads and updates a counter.
  2. Count active keys, not all keys. Counters expire with their window, so memory depends on who is calling right now.
  3. Look for the hottest key. Total load spreads across shards; one huge caller doesn't.
They'll push on thisAnswer out loud, then open.

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.

EntityKey fieldsNote
Request
Response

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.

They'll push on thisAnswer out loud, then open.

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.

They'll push on thisAnswer out loud, then open.

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.

On the wire

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.

    DataPickConsideredWhy 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

    1. 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
    2. 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
    3. 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. 🧭
    4. 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

    They'll push on thisAnswer out loud, then open.

    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

    AlgorithmAllowedBusiest minWaits

    The five, in one line each

    1. Fixed window: one counter per minute. Simplest; allows up to 2× at the boundary. ✅ Figma 2017
    2. Sliding log: a timestamp per request; exact; memory grows with the limit. ✅ Figma 2017
    3. Sliding window counter: this minute + last minute × overlap. Two numbers; Cloudflare measured 0.003% wrong decisions. ✅ Cloudflare 2017
    4. Token bucket: steady refill + burst capacity. Two numbers; used by Stripe, AWS API Gateway and Envoy. ✅ Stripe · AWS · Envoy
    5. 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. 🧭

    They'll push on thisAnswer out loud, then open.

    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.

    StrategyLets through/svs limitRedis calls/sAdds

    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

    1. 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
    2. Local only: each node allows limit ÷ nodes. No network; wrong whenever traffic is uneven. 🔶 arithmetic
    3. 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

    They'll push on thisAnswer out loud, then open.

    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.

    NormalSomething went wrongGreyed out: not possible from the current state.

    Edge cases interviewers love

    They'll push on thisAnswer out loud, then open.

    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)

    SignalTargetAlert

    Incident playbook

      The resilience toolkit

      Name the pattern, then say where it goes in this design.

      They'll push on thisAnswer out loud, then open.

      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.

      TeamOwnsPaged 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

      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 home

      All of Classics

      6 published · 4 comingThe problems almost every loop draws from.

      01

      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.

      30 min · interactive Preview
      12

      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.

      You're reading this Preview
      23

      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.

      32 min · interactive Preview
      26

      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.

      32 min · interactive Preview
      29

      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.

      32 min · interactive Preview
      32

      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.

      32 min · interactive Preview
      ··

      Video streaming (YouTube / Netflix)

      Coming next
      ··

      URL shortener

      Coming next

      More posts