Skip to content

Design a Rate Limiter

A system design interview walkthrough for a distributed rate limiter, covering atomic counters, token buckets, hot keys, failure modes and rules.

Intermediate23 minUpdated 2 December 2026

Before this: Rate Limiting, Caching

"Design a rate limiter" sounds like an algorithms question, and candidates who treat it that way spend twenty minutes comparing token buckets with sliding windows. The algorithm is a five-minute topic.

The real question is distributed. A hundred limiter nodes serve one customer, and all of them must agree on how many requests that customer has made, in under two milliseconds, without becoming the thing that takes the API down. So the interviewer is testing three things: whether you can make a check-and-update atomic across machines, what happens to one hot customer on one key, and what the limiter does when its own storage fails.

This page assumes you know where limiters sit and why (rate limiting) and what the algorithms are (the low-level rate limiting lesson). We spend our words on the system design.

Clarify the requirements

Functional requirements:

  1. Limit requests per client, where a client is an API key, a user id or an IP address, depending on the rule.
  2. Rules are configurable: "100 per minute per API key on /v1/search", with different limits per plan and per endpoint.
  3. A rejected request gets 429 Too Many Requests with a Retry-After header. Allowed requests carry headers showing the remaining budget.
  4. Limits apply across the whole fleet, not per server.
  5. Rules can change without a deploy.

Out of scope, said aloud: billing quotas that reset monthly (a different, durable system), bot detection, DDoS mitigation at the network layer.

Non-functional requirements:

  • Very low overhead: the check adds under 2 ms at p99, because it sits on every request.
  • Accurate enough: brief over-admission of a few percent is fine, letting double the limit through is not.
  • Highly available: the limiter must never be the reason the API is down.
  • Fair under contention: one noisy client must not slow the check for everyone else.

Estimate the scale

Assume the API behind the limiter receives 1 billion requests a day, from 10 million active clients, with 10 million rules-and-client combinations live at any moment.

Check rate: 1,000,000,000 ÷ 86,400 s ≈ 11,600 checks per second, and about 35,000 per second at 3× peak. Every request is one check, so reads and writes are the same operation.

State size: a token bucket is two numbers (tokens left and last refill time). With the key name and overhead, call it about 100 bytes. 10 million × 100 B = 1 GB.

Compare the sliding window log: to allow 1,000 requests per minute it stores up to 1,000 timestamps of 8 bytes, which is 8 KB per key. 10 million × 8 KB = 80 GB, eighty times more memory for the same job.

Redis capacity: one Redis node does on the order of 100,000 simple commands per second. A script that reads and writes a small hash is heavier, so assume 25,000 per second. 35,000 peak ÷ 25,000 means two shards at minimum, and four gives comfortable headroom.

Network: 35,000 checks × about 200 bytes = 7 MB/s, which is nothing.

"Eleven thousand checks per second is easy. What matters is that every one is a read-modify-write on shared state, that the state is small enough for memory and that the choice of algorithm changes memory by 80×. The design problem is atomicity and failure, not throughput."

Try it in the capacity estimator (ignore its storage line: limiter state is per client, not per request).

API and data model

check(clientId, ruleId) -> { allowed, remaining, retryAfterMs }     (internal call)

GET  /v1/limits/rules                  list rules
PUT  /v1/limits/rules/{ruleId}         { match, limit, windowSec, burst }
rule      (ruleId, match: {endpoint, plan}, rate, burst)      in a config store
bucket    key = "rl:{ruleId}:{clientId}"  ->  { tokens, ts }  in Redis, with a TTL

Rules are tiny and change rarely, so each limiter node caches them in memory and refreshes every 30 seconds. Bucket state is the hot data. It carries a TTL equal to the time the bucket needs to refill, so idle clients cost nothing.

High-level design

The slice to simulate is the check path: limiter nodes share one counter store, then forward allowed requests to the protected API.

Requests hit a fleet of limiter nodes that read and update counters in Redis before forwarding allowed calls to the protected API.callerslimiter nodescounter storeprotected api
Requests hit a fleet of limiter nodes that read and update counters in Redis before forwarding allowed calls to the protected API.
  • Callers reach any of several stateless limiter nodes.
  • Each node reads and updates the client's bucket in the shared Redis store.
  • Allowed requests continue to the protected API.
Describe this diagram

Components

  • callers (Client)
  • limiter nodes (Service)
  • counter store (Redis)
  • protected api (Service)

Connections

  • callers sends to limiter nodes
  • limiter nodes sends to counter store
  • limiter nodes sends to protected api

Run it, then try cutting the limiter fleet to one node or turning up the load, and watch what the counter store's latency does to the whole path. Every request pays that store's latency.

The check path: the limiter node derives the key from the request, runs one atomic script against the bucket in Redis and gets back allow or deny plus the remaining budget. If allowed, it forwards the request. If not, it answers 429 itself and the protected API never sees the request.

The rules path: an operator edits a rule in the config store, nodes poll it and the new limit applies within one refresh interval. No request waits on the config store.

The interesting problem: atomic checks across many nodes

The failure interviewers want you to find is the race. With a hundred limiter nodes, two of them can check the same client at the same instant.

Approach A: each node counts locally

Give each of N nodes limit ÷ N of the budget and count in memory.

Good: no network hop, near-zero latency, nothing to fail.

Bad: load balancers do not spread one client evenly. A client whose requests land mostly on one node gets rejected while the fleet has budget to spare, and a client spread over all nodes gets the full limit. Accuracy is poor, especially at low limits such as 10 per minute.

Approach B: read the count, decide, write it back

The node runs GET, checks the number, then SET.

Good: simple, and one shared view of the state.

Bad: it is a race. Two nodes both read 99 of 100, both decide to allow and both write 100, so 101 requests pass. Under load the leak is large, not rare.

Approach C: one atomic script in Redis

Send the whole check-and-update as a single Lua script, which Redis runs without interleaving other commands.

-- KEYS[1] = bucket key, ARGV = rate, burst, cost
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or tonumber(ARGV[2])
local ts = tonumber(s[2]) or now
tokens = math.min(ARGV[2], tokens + (now - ts) * ARGV[1] / 1000)
local allowed = tokens >= tonumber(ARGV[3])
if allowed then tokens = tokens - ARGV[3] end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(ARGV[2] / ARGV[1] * 1000) + 1000)
return { allowed and 1 or 0, math.floor(tokens) }

Good: exact, because the script is the unit of atomicity. One round trip. The refill uses the Redis server's clock via TIME, so skewed clocks on limiter nodes cannot hand one client extra tokens.

Bad: every check lands on one Redis shard, so the shard is the contention point, and a script that gets slow blocks everyone behind it.

The recommended answer is C, with token buckets because they are two fields (the 1 GB case) and allow the short bursts real clients make. Shard Redis by a hash of the client id so each client's bucket lives on exactly one shard, which keeps the script atomic without cross-shard work.

When the limiter itself fails

The second decision is what the limiter does when it cannot do its job. Redis can be down, slow or partitioned, and the answer must be chosen in advance.

  • Fail open: allow the request. The API is protected less for a while, but no customer sees errors caused by the limiter.
  • Fail closed: reject the request. The API is fully protected, but a limiter outage becomes an API outage.

Neither is right alone. A sound answer is fail open with a local fallback: when a check times out (set the timeout to a few milliseconds, never seconds), the node applies a coarse in-memory limit and counts the incident. A brief storm of over-admission is cheaper than an outage. The exception is endpoints where the limit is the security control, such as login attempts or one-time password sends, where you fail closed, because letting an attacker through uncounted is the harm the limiter exists to prevent.

Bottlenecks and failures

One hot client. A single customer sending 20,000 requests per second lands every check on one shard. Reduce the load without losing accuracy: each node leases a block of tokens (for example 100) from Redis and spends it locally, as described in rate limiting. Redis traffic for that client drops by about 100×, and over-admission is bounded by the leased blocks.

Redis failover. A promoted replica may lack the last milliseconds of writes, so some clients briefly get fresh buckets. That is acceptable over-admission. Do not pay for synchronous replication on the hot path.

Slow checks. If Redis p99 rises from 1 ms to 50 ms, every request gets 50 ms slower, and thread pools fill. Set a hard timeout and fall back as above. A limiter that adds latency under stress makes the stress worse.

Client identity. Limiting by IP punishes everyone behind a corporate NAT and is easy to evade with many addresses. Limit by authenticated identity where you have one, and by IP only before authentication.

Retry storms. If rejected clients retry immediately, load returns instantly. Always send Retry-After, and document exponential backoff with jitter.

What if the rule store is down? Nodes keep running with the last rules they loaded. A stale rule is far better than no rule.

Trade-offs to name aloud

  • Token bucket over sliding log: bursts are allowed and memory is 80× lower, but the limit is an average with a burst, not a strict count in every window.
  • Atomic script over local counters: one network hop per request in exchange for accuracy.
  • Fail open with a fallback: possible over-admission during an outage, in exchange for availability.
  • Token leasing: slight over-admission per node, in exchange for much less Redis traffic.
  • Server-side clock in Redis: a dependency on one clock source, in exchange for no skew between limiter nodes.

What interviewers listen for

  • A working answer: a counter per client in a shared store, a check against the limit and a 429 with Retry-After.
  • A strong answer: names the read-modify-write race and fixes it with an atomic script, picks token buckets with a memory argument and shards by client id.
  • A standout answer: also designs the failure mode (fail open with a fallback, closed for login), handles hot clients with token leasing, uses one clock source and shows how rules change without a deploy.

Check your understanding

Common mistakes

Spending the interview on algorithms. Listing four algorithms and picking one takes five minutes. The distributed behavior is the rest of the hour.

A non-atomic check. GET then SET looks fine on a laptop and leaks badly under real concurrency. Say the word "atomic" and show how you get it.

Using each node's own clock. Clock skew between limiter nodes makes refill uneven and lets clients exploit the faster node. Use one authoritative clock.

No plan for the limiter's own failure. If your design is silent about Redis being down, you have designed an outage.

Limiting only by IP. Shared addresses block innocent users and botnets walk around the limit. Prefer an authenticated identity.

Rejecting without telling the client when to return. A bare 429 invites an instant retry. Include Retry-After and remaining-budget headers.

Practice

One enterprise customer legitimately sends 40,000 requests per second, 1,000 times the typical client. Their bucket is on one Redis shard. What do you do?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Look for a way to cut the number of Redis calls for that one key without giving up the limit.

Show a strong answer

Confirm it is the shard, not the script. At 40,000 checks per second, one key can use more than a whole shard's script capacity of roughly 25,000 per second. Moving the key to a different shard does not help, because the key is the problem.

Lease tokens instead of checking every request. Each limiter node asks Redis for a block of tokens (say 500) and spends them locally. With 100 nodes the client's Redis traffic falls from 40,000 per second to roughly 80 calls per second (40,000 ÷ 500).

Accept bounded error. Unspent leases at the moment of a rule change or node crash mean the client may briefly exceed or fall short of its limit by up to nodes × block size. For an enterprise limit in the tens of thousands, that is a small, documented tolerance.

Smaller blocks as the budget drains. When the bucket is nearly empty, lease fewer tokens at a time so the last requests are counted accurately.

The pattern worth keeping: for a hot key, trade a little accuracy for far fewer coordinated operations by batching the shared decision.

You run in three regions and a customer's limit is 3,000 requests per minute globally. Cross-region latency is 80 ms. How do you enforce it?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

A synchronous check against a remote region would add 80 ms to every request. What can be approximate?

Show a strong answer

Do not check a remote store on the request path. An 80 ms hop on every request is far above the 2 ms budget, so each region enforces locally.

Split the budget. Give each region a share, for example 1,000 each, based on recent traffic. A region can reject without asking anyone.

Rebalance asynchronously. Every few seconds each region reports its usage to the others (or to a coordinator), and shares shift toward the busier regions. A customer who sends all traffic from one region converges to nearly the full 3,000 within a few intervals.

Name the error. Between rebalances, the total can exceed 3,000 slightly. If the limit is a hard contractual cap, enforce it in the billing system after the fact, and keep the gateway limit as protection.

The pattern worth keeping: when exact global agreement costs more than the problem is worth, enforce locally, share the budget and reconcile in the background.

Key takeaways

  • Limiting is a distributed read-modify-write. Make the check atomic or it leaks under concurrency.
  • Token buckets use two fields per client, allow bursts and keep memory small.
  • Shard by client id so each bucket has exactly one home.
  • Decide the failure mode first: fail open with a local fallback for most traffic, closed for security controls.
  • Lease tokens for hot keys to cut shared traffic at a bounded cost in accuracy.
  • Always answer 429 with Retry-After, and keep the check under a couple of milliseconds.

Further reading

  • M. Nottingham and R. Fielding, RFC 6585 "Additional HTTP Status Codes" (2012): the definition of 429 Too Many Requests.
  • Redis documentation, "Scripting with Lua" and the EVAL command: why a script runs atomically.
  • Stripe engineering blog, "Scaling your API with rate limiters" (2017): the production use of token bucket limiters and load shedders.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track