Day 5 B-Building blocks 2026-09-29 ← All lessons

Design a rate limiter: token bucket, sliding window, Redis

“100 requests per minute” sounds like one rule. It is at least five different rules, and they disagree about what happens at 00:59. This lesson draws each algorithm, shows the exact moment the cheap one breaks, and then makes it work across a fleet of servers.

2× the limitWhat a fixed-window counter actually lets through at a boundary (§2)
HTTP 429Too Many Requests — plus the headers that make it usable (§4)
0.003%Cloudflare's error rate with a sliding-window counter (§3)
1 round tripWhat a Lua script costs, and why it beats a lock (§5)

Key points

Outcomes

01Draw each of the five algorithms and name what each one trades away.
02Show the exact failure of a fixed-window counter and compute how much it over-admits.
03Place the limiter in an architecture and say what it returns to the client.
04Explain the distributed race condition and fix it atomically.
01

Why, and where


A rate limiter caps how many requests a client may make in a period. It exists for three reasons, and they are worth separating because they imply different limits:

How to read: The limiter is in front of everything expensive. A rejected request costs one counter lookup, never a database query. That placement is the entire point.

client rate limiter middleware, at the edge or in the gateway Redisthe counters ~1 ms allow API servers database 429 Too Many Requests — costs one counter read, nothing more everything to the right of the limiter is expensive
It can live in client code (trivially bypassed), in a server-side middleware, or in an API gateway. For anything public-facing, put it at the edge — the closer to the client, the less of your infrastructure a flood touches.
02

Token bucket, and why bursts are a feature


A bucket holds up to N tokens and is refilled at a steady rate. Each request removes one token. No token, no service. That is the whole algorithm, and it is the default choice at Amazon and Stripe.

Run it: capacity 5, refill 1 token per second, bucket starts full. One burst, replayed on a loop — watch the spotlight.

token bucket · cap 5 · refill 1/s

t = 0.0s3 requests land at once. Tokens 5 → 2. All 3 allowed. This instant burst is the bucket's whole job.
t = 0.1s4 more arrive. Only 2 tokens left: 2 allowed (2 → 0), 2 rejected with 429.
t = 0–2sQuiet. Refill ticks 1/s, so by t = 2.1s the bucket is back to 2 tokens.
t = 2.1s1 request arrives. Allowed, tokens 2 → 1.
takeawayThe burst of 3 passed untouched; the hammering after was capped at refill rate. Capacity = the burst you forgive. Refill = the average you enforce. Two knobs, two jobs.

Try it: the bucket refills in real time. Press Send 20 at once to spend a full bucket in one burst, then watch it recover — and notice that the long-run rate settles at the refill rate no matter how hard you press.

how big a burst you tolerate
the long-run average you enforce
tokens
10 / 10
next token in
full
allowed
0
rejected (429)
0
Two knobs, two separate concerns: capacity governs burst tolerance, refill rate governs the long-run average. Set capacity to 1 and you have a strict rate limiter that punishes every normal page load; that is why the bucket exists.
Why allowing bursts is correct Real traffic is not smooth. A page load fires twelve API calls in 200 ms, then nothing for a minute. A limiter that enforces a strict 2 requests/second would reject ten of those twelve — a legitimate user, broken, while their long-run average sits far under the limit. The bucket smooths over exactly that.

How many buckets? One per thing you want to isolate: per user ID for authenticated APIs, per IP for anonymous ones, per endpoint when some operations are far more expensive, or a global bucket to protect a single downstream dependency. Real systems run several at once, and the request must pass all of them.

03

Windows: the cheap one, the correct one, and the compromise


The other family counts requests inside a time window. The entire design space comes down to how you define the window.

Fixed window counter — and the boundary it leaks through

Keep one counter per clock-aligned minute. INCR it, reject above the limit, let it expire. Two integers of memory and one operation per request — it is the cheapest thing that works. Here is how it fails:

Run it: limit 5 per minute, 10 requests across one clock boundary. Same failure, counted out loud.

fixed window · limit 5/min

00:59:545 requests arrive in the last seconds of the minute. Counter 0 → 5. All allowed — the window is respected.
01:00:00The clock ticks. Counter resets to 0. Nothing about the clients changed.
01:00:045 more arrive. Counter 0 → 5. All allowed.
takeawayAny real 60-second span across the boundary — say 00:59:30 to 01:00:30 — now holds 10 requests against a limit of 5. The counter resets on the clock, not on the client.

How to read: The limit is 5 requests per minute, and both windows respect it — each counter reads exactly 5, neither is ever exceeded. Now look at the red box.

window 1   00:00–00:59 counter = 5 / 5  ✓ legal window 2   01:00–01:59 counter = 5 / 5  ✓ legal 01:00 — counter resets 00:00 02:00 10 requests in 20 seconds twice the limit, and no rule was broken The counter resets on the clock, not on the client. Any real 60-second span that straddles a boundary can carry up to 2× the limit. At scale, that is a load spike you did not budget for.
This is not a corner case. Clients that retry on a schedule naturally synchronise on minute boundaries, which is exactly where the leak is.

Sliding window log — correct, and expensive

Store a timestamp for every request in a sorted set. On each new request, drop everything older than 60 seconds and count what remains. The window now genuinely means “the last 60 seconds,” so the boundary leak is impossible and the limit is never exceeded in any rolling span.

The cost is memory, and it is worse than it sounds: you store timestamps for rejected requests too, so the client hammering you hardest consumes the most memory. At 1 million users and a 1,000/hour limit that is potentially a billion timestamps.

Run it: limit 5 per rolling 60 seconds. Six requests, then the slow recovery — watch old timestamps die.

sliding window log · limit 5 / 60s

t = 0–50Requests at 0, 10, 20, 30, 40, 50. Stored: [0, 10, 20, 30, 40, 50]. All allowed.
t = 55New request. Evict older than 55 − 60: nothing. Count is 6 ≥ 5 → rejected. And 55 is stored anyway → [0, …, 50, 55].
t = 65Evict older than 5: drop 0. Six remain → rejected, store 65.
t = 75Evict older than 15: drop 0, 10. Six remain → rejected, store 75.
t = 125Evict older than 65: everything through 65 dies. Only [75] remains: 1 < 5 → allowed, store 125.
takeawayExact in every rolling span — at the price of storing every timestamp, rejects included. The client hammering hardest eats the most memory.

Sliding window counter — the compromise everyone ships

Keep two fixed-window counters and weight the previous one by how much of it still falls inside the rolling window. One number instead of a list of timestamps, and the boundary leak mostly disappears.

Run it: limit 100 per minute, previous minute saw 84. Two decisions, arithmetic shown.

sliding window counter · limit 100/min

setupPrevious minute: 84 requests. Now 18s into the current minute, 36 so far.
request 1Estimate = 84 × (60 − 18)/60 + 36 = 84 × 0.7 + 36 = 58.8 + 36 = 94.8 < 100 → allowed.
request 250s in, 40 so far: 84 × 10/60 + 40 = 14 + 40 = 54 → allowed.
meaningThe 0.7 is “how much of the previous minute is still inside my rolling 60 seconds.” No timestamp list — just two counters and one weight.
takeawayThe error hides in the assumption that the 84 were evenly spread. If they all came in that minute's last 10 seconds, the estimate is wrong — that residue is the measured 0.003%.

Try it: drag seconds into the minute toward zero with a busy previous minute, and watch the two algorithms disagree. The fixed window keeps saying “allowed” while the real last-60-seconds figure is over the limit.

previous minute current minute minute boundary the real rolling 60 s now

fixed window counter says
36 / 100
sliding window counter says
94.8 / 100
weight on the previous minute
70%
how much of it is still inside the rolling window

Cloudflare runs the sliding window counter across its edge network and measures a 0.003% error rate — three requests in a hundred thousand wrongly allowed or blocked, for one extra integer per client. The approximation assumes the previous minute's traffic was evenly spread; when it was not, this is where the residual error lives.

Leaking bucket — when the downstream rate is fixed

Requests go into a FIFO queue and are processed at a constant rate. Overflow is dropped. Unlike token bucket it never bursts — outflow is perfectly smooth. Use it when the thing you are protecting has a hard fixed throughput (a legacy service, a payment processor with a contractual rate). Shopify uses it for exactly that. The cost is that a burst fills the queue, so later legitimate requests get rejected while older queued ones are still being drained.

Run it: queue holds 4, worker takes 1 every 2 seconds. Same burst as the token-bucket trace above — opposite outcome.

leaking bucket · queue 4 · outflow 1 / 2s

t = 0s4 requests arrive → queued [r1, r2, r3, r4]. Nothing is served yet. No burst, ever.
t = 1s2 arrive. Queue is full (4/4) → both dropped on the floor.
t = 2sWorker takes r1. Queue 3/4. The first byte leaves a full 2 seconds after it arrived.
t = 3s1 arrives → queued, back to 4/4.
takeawayOutflow is exactly 1 per 2s whatever arrives — the token bucket served all 4 at t = 0. Smoothness is the product; the price is queue wait, and a full queue drops fresh requests while stale ones still drain.
AlgorithmMemory per clientAllows bursts?The flawReach for it when
Token bucket2 numbersYes, up to capacityTwo knobs to tune and they interactDefault. Amazon, Stripe
Leaking bucketqueueNo — perfectly smoothQueued old requests starve fresh onesDownstream has a hard fixed rate. Shopify
Fixed window1 numberAccidentally, at boundariesAdmits up to 2× across a boundaryCheapest option; limits are soft
Sliding window log1 timestamp per requestNoMemory, including for rejected requestsThe limit must be exact
Sliding window counter2 numbersSlightlyApproximates; assumes even distributionBest general trade. Cloudflare
04

What the client gets back


A bare 429 is a bad citizen: the client has no idea how long to wait, so it retries immediately and makes things worse. Return the state of the limit with every response, not just the rejections.

Response headershttp
# On a successful request — the client can self-pace before it is ever blocked.
HTTP/1.1 200 OK
X-Ratelimit-Limit: 100        requests allowed per window
X-Ratelimit-Remaining: 36     left in the current window
X-Ratelimit-Reset: 24         seconds until the window resets

# On rejection — Retry-After is the one that actually changes client behaviour.
HTTP/1.1 429 Too Many Requests
X-Ratelimit-Limit: 100
X-Ratelimit-Remaining: 0
Retry-After: 24
Content-Type: application/json

{"error": "rate_limit_exceeded", "retry_after_seconds": 24}

Rules themselves belong in configuration, not in code — a YAML file or a config service that workers reload, so changing a limit does not require a deploy:

Rule configurationyaml
- domain: auth
  descriptors:
    - key: login_attempt
      value: by_ip
      rate_limit: { unit: minute, requests_per_unit: 5 }    strict: credential stuffing

- domain: messaging
  descriptors:
    - key: send_message
      value: by_user
      rate_limit: { unit: day, requests_per_unit: 1000 }

- domain: search
  descriptors:
    - key: query
      value: by_user
      rate_limit: { unit: second, requests_per_unit: 20 }   loose: cheap and read-only
Interview tip — drop or queue? When a request is limited you can reject it (429) or hold it and serve it later. Reject anything user-facing — a fast failure the client can retry beats a request that silently waits 30 seconds. Queue only non-urgent work where ordering and completion matter more than latency, such as a batch import.
05

Making it work across a fleet


One limiter on one box is easy. Ten limiter instances sharing one limit introduces two genuine distributed-systems problems.

Problem 1: the race condition

The obvious implementation is read, add one, write back. With concurrent requests that is wrong:

How to read: Two requests, two servers, one counter. Step through it. Both read before either writes, so one increment is lost and the limit is quietly exceeded.

limiter A Redis counter limiter B GET counter GET counter 99 99 99 < 100, allow 99 < 100, allow SET 100 SET 100 two requests admitted, counter says 100. One increment vanished.
With ten limiter instances under load this is not rare — it is constant, and it scales with your traffic.
Option A

Take a lock

  • Correct, and obvious.
  • Every request now serialises on one lock, and the limiter becomes the bottleneck it was supposed to prevent.
  • Lock acquisition adds a round trip to the hot path of every request.
Option B

Make it one atomic operation

  • Redis INCR is atomic by itself — it returns the new value, so read and write are a single step.
  • For multi-step logic, a Lua script runs atomically inside Redis: one round trip, no lock.
  • For a sliding window log, ZREMRANGEBYSCORE + ZCARD + ZADD inside one script does the whole thing.
Fixed window, atomicallylua
-- KEYS[1] = "ratelimit:user:42:1699891260"   (counter key, window-aligned)
-- ARGV[1] = limit, ARGV[2] = window seconds
local current = redis.call('INCR', KEYS[1])   -- atomic: read and write in one step
if current == 1 then
  redis.call('EXPIRE', KEYS[1], ARGV[2])   -- first hit in this window: set the TTL
end                                        -- the TTL is what garbage-collects old windows
if current > tonumber(ARGV[1]) then
  return 0                                 -- reject
end
return ARGV[1] - current                   -- allow, and report what's left
Sliding window log, atomicallylua
-- KEYS[1] = "ratelimit:user:42"  (a sorted set of request timestamps)
-- ARGV[1] = now_ms, ARGV[2] = window_ms, ARGV[3] = limit
local cutoff = ARGV[1] - ARGV[2]
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, cutoff)  -- drop anything older than the window
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
  redis.call('ZADD', KEYS[1], ARGV[1], ARGV[1])     -- record only requests we allow,
  redis.call('EXPIRE', KEYS[1], math.ceil(ARGV[2]/1000))  -- which bounds the memory problem
  return 1
end
return 0

Problem 2: synchronisation, and the latency of being correct

Ten limiter instances must agree on the count. Two approaches, and only one survives contact with autoscaling:

At global scale there is one more wrinkle. If your limiters run on edge servers in 100 cities, a synchronous call back to one central Redis adds the cross-ocean round trip from Day 3 — up to 150 ms on every request, to enforce a limit. Nobody accepts that. The answer is regional counters with eventual consistency: each region enforces locally against its own share and reconciles asynchronously. You over-admit slightly during the reconciliation lag. That is the price of not putting an ocean on the hot path, and it is the right trade.

What happens when the limiter itself fails?

You have put a dependency in front of every request. If Redis is unreachable, the middleware has to decide something, and there are only two options:

Usually right

Fail open — allow the request

  • A cache outage does not become a total outage.
  • You lose protection exactly when you may need it, so pair it with a local in-process fallback limiter — approximate, per-instance, but far better than nothing.
  • Alert loudly. A silently disabled rate limiter is how you discover the outage during the next incident instead of this one.
Sometimes right

Fail closed — reject the request

  • Correct where exceeding the limit is worse than being down: login attempts, payment endpoints, anything metering a paid third-party API.
  • Turns a Redis blip into a full outage for that endpoint.
  • Decide per rule, not globally. Most teams fail open on read APIs and closed on auth.

Also give the Redis call a tight timeout — a few milliseconds. A limiter that blocks for 2 seconds waiting on a sick Redis has become the outage it was supposed to prevent, and it does so on every request simultaneously.

Interview tip — what to monitor Two numbers tell you whether the limiter is doing its job: the rejection rate per rule, and who is being rejected. A sudden spike in 429s for one rule means either an attack or a limit set too tight after a legitimate traffic change — and the distinction is usually “is it one client or all of them?”. If you are rejecting a broad population, your limit is wrong, not their behaviour.
Q&A

Check yourself


Rate limiter questions in real loops are mostly operational: something is being limited that should not be, or the limiter itself has become the problem.

Q1A large enterprise customer reports being rate limited constantly. Their traffic is well under your per-user limit. Your limiter keys on client IP. What is happening?
  • Their requests are malformed
  • Hundreds of their employees share one NAT egress IP, so they are all counted as one client
  • Your limit is set too low globally
✓ They are all behind one NAT gateway. IP is a proxy for identity, and it is a bad one in both directions: a corporate NAT, a university, or a mobile carrier's CGNAT can put thousands of distinct users behind one address, while one abuser with a residential proxy pool looks like thousands of users. The fix is to key on the strongest identity available and fall back: API key or authenticated user ID when you have one, IP only for unauthenticated traffic. Typically you run both — a generous per-IP limit to blunt crude floods and a tighter per-user limit for fairness. Two follow-ups to be ready for: if you sit behind a load balancer or CDN, the IP you see is theirs, so you must read X-Forwarded-For — and you must only trust the hop your own proxy appended, because clients can forge the rest of that header. And IPv6 should be bucketed by prefix (commonly /64), since a single customer may be handed trillions of addresses.
Q2Redis — which holds every counter — becomes unreachable. What should the middleware do, and does the answer vary by endpoint?
  • Reject everything until Redis returns, to stay safe
  • Fail open by default with a tight timeout and a local fallback limiter, but fail closed on auth and payment endpoints
  • Retry the Redis call until it succeeds
✓ Fail open by default, fail closed per rule, and time out aggressively. Failing closed everywhere converts a cache outage into a total outage — the limiter exists to protect availability, so it should not be the thing destroying it. But the logic inverts where exceeding the limit is worse than being unavailable: login (credential stuffing), payments, and anything metering a paid third-party API. The detail that matters most is the timeout. If the Redis call has no deadline, a sick-but-reachable Redis blocks every request thread for seconds, and you fall over from thread exhaustion without a single error being logged. Set it to a few milliseconds and treat a timeout exactly like a failure. Retrying is the worst option: you add load to a struggling dependency and multiply the latency on the hot path.
Q3You run limiters on edge servers in 100 cities and need one global limit of 1,000/hour per user. Exact enforcement is required by a contract. What do you tell the business?
  • Use one central Redis — it is the only correct option
  • Exact global enforcement means a cross-region round trip on every request; propose budget-splitting with reconciliation, and negotiate the word “exact”
  • Run 100 independent limiters of 10/hour each
✓ Price the exactness, then propose the approximation. A single authoritative counter means every edge in the world calls one region synchronously — Day 3's 150 ms, added to every request, to enforce a quota. Nobody accepts that once you say it out loud. The standard answer is budget distribution: each region leases a slice of the global quota, enforces locally at memory speed, and reports consumption back asynchronously; regions that run low request more from the coordinator. You over-admit slightly during the reconciliation lag, bounded by the lease size — so you can tune the error by making leases smaller at the cost of more coordination traffic. Static per-region splits (option 3) fail badly because traffic is not uniform: the user in Tokyo exhausts the Tokyo slice while 99 other slices sit unused. The real-world move is to go back to the contract: “1,000/hour, enforced within 1%” is achievable and cheap; “never 1,001” is neither.
Q4Your API returns bare 429s. Clients are retrying immediately and your error rate is climbing during every brief spike. What do you change on both sides?
  • Raise the limits until clients stop hitting them
  • Return Retry-After plus the limit/remaining/reset headers, and have clients back off exponentially with jitter
  • Return 503 instead so clients treat it as a server error
✓ Tell the client when to come back, and make it obey. A bare 429 gives the client no information, so a naive retry loop hammers you at full speed — your limiter is now generating more load than the traffic it rejected. Server side: Retry-After is the one header that changes behaviour, and X-RateLimit-Limit / Remaining / Reset on successful responses lets well-behaved clients self-pace before they are ever blocked. Client side: exponential backoff with jitter (Day 11), because without jitter every rejected client retries at the same instant and you get a synchronised thundering herd. Returning 503 is actively harmful: it tells the client your server is broken, which triggers retry logic and may trip their circuit breaker and take you out of their rotation entirely. 429 means “you, slow down”, which is the truth.
Q5Product wants paid tiers: free users get 100 requests/hour, pro users 10,000. An engineer proposes one Redis key per user with the tier's limit baked in. What will go wrong at the first tier change?
  • Nothing — the key is per user, so the limit is per user
  • The limit lives in the counter rather than in config, so upgrades take effect inconsistently and limits cannot be changed without touching data
  • Redis cannot store different limits per key
✓ The policy has been baked into the data. Counters should hold usage; limits belong in configuration looked up at check time. Bake the limit into the key or its value and a tier upgrade means rewriting live counters, a limit change for all free users means a data migration, and a user who upgrades mid-window is left in an ambiguous state. The clean shape is: key on (user, window) holding only the count; look the limit up from a cached config keyed on the user's current tier; compare. Now an upgrade is a config read that takes effect on the next request, and changing the free tier is a config push with no deploy and no data touched. Worth adding out loud: decide what an upgrade means mid-window — does the user get the new allowance immediately, or at the next window? Both are defensible; the bug is not having decided.
In practiceWhat production adds, and the questions that come next optional

This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.

Rate limiting

  • Distributed enforcement: central store vs. local buckets with periodic sync, and the accuracy trade-off

Hot keys and stampedes

  • Retry storms and why naive client retries amplify an incident; jitter, backoff, retry budgets

Terms used

429
HTTP status “Too Many Requests”. Pair it with Retry-After or clients will hammer you.
Token bucket
Tokens accrue at a fixed rate up to a cap; each request spends one. Bursts allowed up to the cap.
Leaking bucket
A FIFO queue drained at a constant rate. Never bursts; overflow is dropped.
Fixed window
One counter per clock-aligned period. Cheapest, leaks up to 2× at boundaries.
Sliding window log
A timestamp per request; count what falls inside the last N seconds. Exact, memory-hungry.
Sliding window counter
Two fixed counters, the older one weighted by overlap. The usual production choice.
Atomic operation
One indivisible step. No other operation can observe a half-finished state.
Lua script
Multi-step logic executed atomically inside Redis in one round trip.
Race condition
Two operations interleaving so a result depends on timing. Here: two reads before either write.
Eventual consistency
Replicas converge, but may disagree briefly. Here, the price of not calling across an ocean.

What breaks next. This design leans on one shared Redis. Scale it and you need several — which means deciding which counter lives on which node. The obvious answer, hash(key) % N, works perfectly until you add the fourth node, at which point almost every counter moves and every limit resets at once. Day 6 is about why, and the fix that every distributed store uses.

Source: System Design Interview, Ch. 4 — Design a rate limiter (pp. 1–20). Algorithm diagrams, the Lua scripts, the response-header contract and the regional-counter discussion are standard practice added here to make the trade-offs concrete.