InterviewDryRun
Lesson 2 · 23 min video · free

Design a Rate Limiter

A rate limiter decides, in under a millisecond, whether one request from one client may go through. The interview tests whether you know the algorithms and their trade-offs, and whether you can keep a count correct when hundreds of API servers are counting the same client at the same time. This lesson walks through the whole 45-minute answer.

What you will learn

  • Pin down who is limited, by what key, and what happens to a rejected request before choosing an algorithm.
  • Token bucket allows bursts and is the usual default; sliding window counter is the accurate, cheap alternative.
  • Keep the counters in a shared in-memory store and update them with one atomic operation per request.
  • Fail open when the limiter's store is down, except for limits that protect money or security.
  • Return 429 with Retry-After and rate limit headers so well-behaved clients slow down by themselves.
  • Local counters with periodic sync trade a little accuracy for much less latency at very high traffic.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The interface
  5. Step 4: The four algorithms
  6. Step 5: Where the limiter lives
  7. Step 6: Sharing counts without races
  8. Step 7: Scaling to very high traffic
  9. Step 8: When the limiter fails
  10. Step 9: The parts people forget
  11. Step 10: The follow-up questions
  12. Recap

Short on time? Read the answer outline for design a Rate Limiter.

Practice this question with Max

The question

Welcome to lesson two of the InterviewDryRun system design course. Today we are designing a rate limiter: the part of a system that decides whether a request is allowed through, or whether the caller has sent too many and has to wait.

Every public API has one. It protects servers from being flooded, whether by a bug in somebody's retry loop, a scraper, or a deliberate attack. It keeps one heavy customer from slowing everyone else down. And it is how paid plans are enforced: a free plan gets a hundred calls a minute, a paid plan gets ten thousand.

Max asks

“Design a rate limiting service that sits in front of a public API and enforces per-client limits across many API servers.”

That is how Max, our AI interviewer, asks it. Notice the last part of the sentence: across many API servers. Counting requests on one machine is easy, and any candidate can do it. The interesting question is how hundreds of machines agree on one count, in under a millisecond, without becoming the bottleneck themselves. That is where we will spend most of our time.

Here is the plan. We will clarify requirements, size the problem, define the interface, then compare the four classic algorithms in detail, because interviewers almost always want to hear that comparison. Then we will decide where the limiter lives, how the counters are shared, how to avoid races, what happens when things fail, and finish with the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Limit by clientAPI key, user id, or IP address for anonymous calls
  2. 02
    Configurable rulesDifferent limits per plan and per endpoint
  3. 03
    Reject clearly429 Too Many Requests, with when to retry
  4. 04
    Several windowsPer second for bursts, per day for quotas
  5. 05
    Change rules liveNo redeploy to raise a customer's limit

As always, start with questions, not boxes. The first question is the most important one: who exactly are we limiting? The answer becomes the key we count by, and the whole design hangs off it.

For a public API, the natural key is the API key, or the user behind it. For calls with no key, like a sign-in page, we fall back to the IP address. Say out loud that IP addresses are a weak key: many people can share one address behind an office or a mobile network, and one attacker can use thousands of addresses.

Next, are the limits the same for everyone? Almost never. Free and paid plans have different limits, and expensive endpoints, like a search or a report export, get tighter limits than cheap ones. So we need rules, keyed by plan and by endpoint, and stored as data rather than code.

Ask what happens to a request over the limit. In most designs it is rejected immediately with the status code four-twenty-nine, too many requests. The alternative is to queue it and process it later, which is shaping rather than limiting, and it belongs in a different design. Confirm that rejection is what they want.

And finally, do we need more than one window? Usually yes: a short window, like per second, stops bursts that hurt the servers, and a long one, like per day, enforces the quota the customer paid for. Rules should also change without a deploy, because support will need to raise a customer's limit in the middle of an incident.

Non-functional requirements
  1. 01
    Tiny latencyWell under a millisecond added to each request
  2. 02
    Accurate enoughA few percent over the limit is fine; ten times over is not
  3. 03
    Highly availableThe limiter must never take the API down with it
  4. 04
    Shared viewAll API servers see the same count for a client
  5. 05
    VisibleClients can see their limit and what is left

Now the qualities. The limiter runs on every single request, so it must add almost nothing, ideally well under a millisecond. And ask how accurate it must be. For protecting servers, letting through a few percent extra is fine. For billing quotas, it may need to be exact. That one answer changes the design, so ask it.

Availability is subtle here. The limiter exists to protect the API, so it would be absurd if the limiter going down took the API down too. We will come back to this when we talk about failure, but note it now as a requirement: the API must keep working if the limiter does not.

Then the hard requirement from the question: every API server must see the same count for a client. If a client's requests are spread across fifty servers, and each server counts on its own, the client effectively gets fifty times their limit. And finally, clients should be able to see their limit and how much is left, through response headers, so good clients can slow down before they hit the wall.

Step 2: Back-of-the-envelope estimates

Sizing the limiter
API traffic1 M requests / sat peak, across all servers
API serversabout 5002,000 requests a second each
Active clients10 millionkeys seen in the last hour
State per clientabout 100 byteskey, counters, timestamps
Total stateabout 1 GBper rule; a few GB in all
Counter operations1 M / sone or two per request

Now a quick sizing, because it tells us what kind of store we need for the counters. Let us assume a big public API.

Say one million requests a second at peak, spread over about five hundred API servers, so roughly two thousand requests a second each. Every one of those requests needs a rate limit decision, so the limiter must make a million decisions a second.

How much state is that? Say ten million clients are active in any hour. For each we keep a key, a counter or two and a timestamp, about a hundred bytes. Ten million times a hundred bytes is about a gigabyte. Even with several rules per client, it is a few gigabytes, which fits comfortably in memory. So storage is not the problem.

The problem is operations. A million counter updates a second, each needing an answer in well under a millisecond. That rules out a disk-based database on the request path. It points straight at an in-memory key-value store, sharded across a handful of nodes, each doing a couple of hundred thousand operations a second. Write that conclusion down: small state, huge operation rate, so in-memory and sharded.

One more number worth saying: the limiter's own latency budget. If the API's typical response time is fifty milliseconds, and we add one network round trip to a counter store in the same data centre, that is around half a millisecond, or one percent. Acceptable. Two round trips would be noticeable, and anything that crosses regions would be unacceptable. So the design rule is: at most one round trip per request, and always to a nearby store.

Step 3: The interface

What the API server calls, and what the client sees
// inside the API, before the handler runs
decision = limiter.check(key = "api-key:k_81f2",
                         rule = "search:per-minute")
→ { allowed: false, limit: 100, remaining: 0,
    resetInSeconds: 23 }

// what the client gets back
HTTP/1.1 429 Too Many Requests
Retry-After: 23
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 23

This system has two interfaces, and it is worth showing both. The first is internal: what the API server asks. Given a client key and a rule, the limiter answers allowed or not, plus the numbers needed to tell the client what is going on.

The second interface is what the client sees. A rejected request gets four-twenty-nine, too many requests, with a Retry-After header saying how many seconds to wait. Successful responses also carry headers with the limit, how many calls remain, and when the window resets. Mention that there is a standard draft for these header names, and that consistent headers let client libraries back off automatically.

And a third, small interface for operators: an admin API to create and change rules, for example, plan pro, endpoint search, one thousand per minute. Rules are read far more often than they change, so every API server keeps them in memory and refreshes them every few seconds, or when it is told they changed.

Step 4: The four algorithms

Rate limiting algorithms
AlgorithmHow it worksWeakness
Fixed window countercount per calendar minutedouble burst at the boundary
Sliding window logkeep every timestampmemory grows with the limit
Sliding window counterblend this and last windowan estimate, slightly off
Token buckettokens refill at a steady ratetwo numbers to tune

This is the heart of the question. Interviewers expect you to know the main algorithms and, more importantly, to compare them. There are four you should be able to explain from memory.

The simplest is the fixed window counter. Take the current minute, say ten oh five, and keep a counter for this client and that minute. Each request increments it. If it goes over the limit, reject. When the minute changes, a new counter starts at zero. It is one integer per client, one increment per request. Very cheap.

Its weakness is the boundary. Suppose the limit is a hundred a minute. A client sends a hundred requests in the last second of ten oh five, and another hundred in the first second of ten oh six. Both windows are within the limit, but the server just took two hundred requests in two seconds, twice the intended rate. For protecting a server, that burst can matter. Draw it if you have a whiteboard: it is the classic picture.

The sliding window log fixes the boundary exactly. Keep a log of the timestamps of the client's recent requests. On each request, drop timestamps older than one minute, count what remains, and allow the request if the count is under the limit. It is perfectly accurate. But it stores one entry per request, so a limit of ten thousand a minute means up to ten thousand timestamps per client. At our scale that memory is too expensive.

The sliding window counter is the clever compromise. Keep only two fixed window counters: this minute and the last minute. If we are twenty percent of the way into this minute, estimate the requests in the past sixty seconds as all of this minute's count, plus eighty percent of last minute's count. Two integers per client, and the boundary burst mostly disappears. It is an estimate, because it assumes last minute's requests were spread evenly, but in practice it is very close.

And the token bucket, which is probably the most widely used. Picture a bucket that holds up to, say, a hundred tokens, and refills at a steady rate, say ten tokens a second. Each request takes one token. If the bucket is empty, the request is rejected. The bucket size controls how big a burst is allowed, and the refill rate controls the long-term average.

Token bucket, stored as two numbers
state: tokens, lastRefill

on request at time now:
  tokens = min(capacity,
             tokens + (now - lastRefill) * ratePerSecond)
  lastRefill = now
  if tokens >= 1:
      tokens = tokens - 1
      allow
  else:
      reject, retry after (1 - tokens) / ratePerSecond

The nice trick is that you never need a timer to add tokens. You store just two numbers: how many tokens there were, and when you last updated. On each request, work out how many tokens would have dripped in since then, cap at the bucket size, and take one. Two numbers per client, constant work per request.

So which do you pick? Say it clearly. For an API, I would choose the token bucket as the default, because real clients are bursty. A mobile app opening a screen fires ten calls at once and then goes quiet, and the token bucket allows exactly that while holding the average. If the interviewer wants smooth limits without bursts, the sliding window counter is the accurate, cheap alternative. And I would mention that daily quotas can simply use a fixed window per calendar day, because the boundary burst does not matter at that scale.

One more algorithm name that sometimes comes up is the leaky bucket. It is a queue that drains at a fixed rate, so requests come out perfectly smooth. It shapes traffic rather than rejecting it, which is useful in front of something fragile, like a legacy system, but it adds waiting time. Mention it, and say why it does not fit a public API that should answer fast.

Step 5: Where the limiter lives

High-level design
allowedcheckcached rulesCLIENTClientsEDGEAPI gatewaylimiter middlewareSERVICEAPI serversbusiness logicCACHECounter storein memory, shardedSTORERules serviceplans and limits

Where should the limiter run? There are three choices, and you should name all three. It can live in the client, which we cannot trust, so that is out for protection. It can be a library inside each API server. Or it can be a separate layer in front of the API, usually the API gateway that already handles authentication and routing.

For a public API with many services behind it, the gateway is the natural place. Every request passes through it anyway, it already knows the client's identity from the API key, and rejected requests never reach the business servers at all, which is the whole point. The limiter becomes a piece of middleware in the gateway.

The gateway instances are stateless and there are many of them, so the counts must live somewhere shared. That is the counter store: an in-memory key-value store, sharded by client key, sitting in the same data centre. Each request does one round trip to it.

The rules live in a small, ordinary database, behind a rules service. Gateways load all the rules into memory and refresh them every few seconds, so looking up a client's limit costs nothing on the request path. Only the counter check needs the network.

Mention the alternative, too. Some teams put a limiter library inside each service, sharing the same counter store. That gives each service fine control over its own limits, for example per database query, but it means every service team must use it correctly. A common answer is both: coarse per-client limits at the gateway, and a few fine-grained limits inside the services that need them.

Step 6: Sharing counts without races

The race, and the atomic fix
// broken: two gateways, same client, same moment
A: count = GET k      → 99
B: count = GET k      → 99
A: SET k 100, allow
B: SET k 100, allow   // 101 requests allowed

// fixed window: one atomic increment
n = INCR k:10-05      // returns the new value
if n == 1: EXPIRE k:10-05 120
allow if n <= limit

Now the hard part: many gateways updating the same counter. Start by showing the bug, because naming it is half of the answer. Two gateways get requests from the same client at the same moment. Both read the count, both see ninety-nine, both decide there is room, both write a hundred. The client has made a hundred and one requests, and one slipped through.

At small scale one extra request does not matter, but under a real burst many requests can slip through this way. The fix is to never read, decide and write as separate steps. For a fixed window, use the store's atomic increment: one command that adds one and returns the new value. The store runs it as a single step, so no two gateways can see the same value. If the returned value is over the limit, reject.

For the token bucket, the update is a little calculation: read two numbers, compute the refill, take a token, write two numbers back. That cannot be a single increment. The usual answer is to run the whole calculation inside the store as a small server-side script, which in-memory stores generally support, so it executes atomically on the shard that owns the key. Still one round trip, and no race.

Another option is optimistic concurrency: read with a version, write only if the version has not changed, and retry if it has. That works, but under exactly the bursty traffic we are protecting against, retries pile up. So the server-side script is the cleaner answer, and it is the one I would give.

Sharding the counter store
  1. 01
    Shard by client keyAll of one client's counters on one node
  2. 02
    Consistent hashingAdding a node moves only a slice of keys
  3. 03
    Expire everythingEvery counter gets a time to live
  4. 04
    Replicas for failoverLose a few counts, not the service

How do we shard? By client key, so that every counter for one client, across all its rules, lives on the same node. Then one script can check several rules at once, say per second and per day, in one round trip.

Use consistent hashing to place keys on nodes, so adding a node to handle more traffic moves only a slice of the keys. And give every counter a time to live slightly longer than its window, so idle clients disappear on their own. We never have to clean up the store.

Each shard has a replica for failover. Replication is usually asynchronous, so if a primary dies, its replica may be a few counts behind. That is a perfect example of a trade-off to say out loud: for rate limiting, losing a few counts during a failover is harmless, so we do not pay for synchronous replication.

Step 7: Scaling to very high traffic

Local counting with periodic sync
every 100 msSERVICEGateway 1local countsSERVICEGateway 2local countsSERVICEGateway 3local countsCACHECounter storeglobal totalsSTOREHot client listlimited everywhere

Suppose the interviewer pushes further: the counter store is now the bottleneck, or the extra round trip is too slow. There is a well-known answer, and it trades accuracy for speed.

Each gateway counts locally, in its own memory, with no network call on the request path. Every hundred milliseconds or so, it sends its local counts to the shared store in one batch, and gets back the global totals. Each gateway then makes decisions using the last known global total plus its own local count since then.

The cost is accuracy. Between syncs, every gateway is a little behind the others, so a client hitting all gateways at once can overshoot by roughly one sync interval of traffic. If the limit is a hundred a second and we sync every hundred milliseconds, the overshoot is around ten percent. For protecting servers, that is a great trade. For billing quotas, use the exact path instead.

A related trick: when a client goes over the limit, the store can publish its key to a hot list that every gateway caches. Then every gateway rejects that client locally for the rest of the window, without any round trip at all. Attackers and runaway scripts are exactly the clients that send the most traffic, so this removes most of the load from the counter store precisely when it matters.

And one more scaling point that interviewers like: a single huge client. If one customer sends half a million requests a second, all their counters live on one shard, and that shard becomes hot. Local counting with periodic sync solves this naturally, because the shard then sees one batched update per gateway every hundred milliseconds instead of every request.

Step 8: When the limiter fails

Fail open or fail closed?
Limit protectsIf the counter store is downWhy
Server capacityfail open: allowan outage is worse than a burst
Paid quotafail open, reconcile latercustomers forgive a free extra
Sign-in attemptsfail closed: rejectguessing passwords is the threat
Money movingfail closed: rejectan extra payment cannot be undone

Now the question that separates good answers from great ones: what happens when the counter store is unavailable? The gateway cannot get a decision. It has to choose: let the request through, or reject it.

For most limits, fail open. The limiter exists to protect the API, and if a limiter outage rejected every request, we would have caused the very outage we were trying to prevent. So with a short timeout, a few milliseconds, the gateway gives up waiting and allows the request, and logs that it did. Quotas can be reconciled later from request logs.

But not every limit. A limit on sign-in attempts exists to stop password guessing, and a limit on payments or money transfers exists to stop fraud. For those, fail closed: reject when in doubt. The cost is a short outage for those endpoints, and that is the right cost. The great answer is not fail open or fail closed. It is: it depends on what the limit protects, and here is the rule per category.

Two more protections are worth a sentence each. First, a circuit breaker around the counter store, so that when it is struggling, gateways stop calling it for a few seconds instead of piling on. And second, a crude local fallback: while the store is down, each gateway can enforce its share of the limit locally, for example the limit divided by the number of gateways. It is rough, but it is far better than no limit at all.

And remember multiple regions. A client's requests can arrive in two regions at once. Synchronising counters across regions on every request would add tens of milliseconds, which breaks our latency budget. So the common answer is to enforce limits per region, giving each region a share of the global limit, and to sync usage between regions in the background for quotas. Say that the global limit is therefore approximate, and that this is a deliberate choice.

Step 9: The parts people forget

Details that show experience
  1. 01
    Clock skewLet the store's clock define the window, not each gateway's
  2. 02
    Retry stormsTell clients to back off with jitter
  3. 03
    Cost-based limitsAn export costs 50 units, a read costs 1
  4. 04
    Allow listsHealth checks and internal callers skip the limiter
  5. 05
    ObservabilityCount rejections per rule and per client

A few details make an answer sound like someone who has run one of these. Clock skew: if each gateway uses its own clock to decide which window a request belongs to, gateways a second apart will disagree. Let the counter store's script read the time, so there is one clock per key.

Retry storms: when a big client is limited, a naive client retries immediately, which makes things worse. The Retry-After header helps, and your client libraries should back off exponentially with random jitter, so thousands of clients do not all retry at the same second.

Not every request costs the same. A request that exports a year of data is far more expensive than reading one record. So let rules charge a cost per endpoint: the token bucket simply takes fifty tokens instead of one. This is an elegant extension, and it costs nothing in the design.

Internal callers and health checks should be on an allow list, or the limiter will one day reject your own monitoring during an incident. And measure everything: rejections per rule, per client and per endpoint. A sudden jump in rejections for one big customer is often the first sign of a bug in their integration, and your support team will want to call them before they call you.

Step 10: The follow-up questions

Max asks

“Your token bucket allows a burst of a hundred. A client sends a hundred requests at the same instant to fifty different gateways. How many get through?”

With the atomic script on a shared store, exactly a hundred, because every request goes through the same key on the same shard, one at a time. With local counting and periodic sync, it could be more, up to a hundred per gateway in the worst case, until the next sync. That is why the local mode should be reserved for protective limits, and why the hot list matters: after the first sync, every gateway knows the client is over.

Max asks

“How would you rate limit users who are not signed in?”

By IP address, with care. Use a more generous limit, because many real people can share one address behind a company network or a mobile carrier. For IPv6, limit by a prefix rather than the full address, because one person can easily control a huge block of addresses. And add a second signal for sensitive endpoints, such as a limit per account name on the sign-in page, so an attacker cannot guess one account's password from many addresses.

Max asks

“A customer upgrades from the free plan to pro. How quickly does their new limit apply?”

Within seconds. The rules are cached in each gateway and refreshed every few seconds, and the upgrade can also publish a change event so gateways refresh at once. Since the counters are keyed by client and rule, the new rule starts counting fresh. It is worth saying that we do not need a cache invalidation protocol for this: a few seconds of the old limit after an upgrade is perfectly acceptable.

Max asks

“Would you put the limiter in the load balancer instead of the gateway?”

For simple, coarse limits by IP address, yes, and that is a good first line of defence against floods, because it rejects traffic before it costs us anything. But the load balancer does not know the API key, the plan or the endpoint's cost, so the real per-client limits belong in the gateway, which has that context. Layering both is common: a cheap, coarse limit at the edge, and the precise one at the gateway.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsWho, by what key, which rules, what a rejection looks like
  2. 02
    5 to 10: estimates1 M checks a second, a few GB of state: in memory, sharded
  3. 03
    10 to 20: algorithmsFixed, log, sliding counter, token bucket; pick and justify
  4. 04
    20 to 35: shared countersGateway middleware, atomic script, sharding, local sync
  5. 05
    35 to 45: failure and edgesFail open or closed by limit, regions, headers, retries

Let us map it onto forty-five minutes. Five minutes of requirements, ending with who we limit, by what key, under which rules, and what a rejected client sees. Five minutes of estimates, ending with: a million checks a second, a few gigabytes of state, so in memory and sharded.

Then around ten minutes on the algorithms. Explain all four, draw the fixed window boundary problem, and pick the token bucket for bursty API clients, with the sliding window counter as the alternative.

Fifteen minutes on the distributed part: the limiter as gateway middleware, counters in a sharded in-memory store, one atomic script per request to avoid races, and local counting with sync for extreme traffic. And the last ten minutes on failure: fail open or closed depending on what the limit protects, regions, clear headers and well-behaved retries. Say the trade-offs out loud at each step, and you have a strong answer.

Knowing the four algorithms is the easy part. Explaining them clearly, while someone asks you what happens when fifty gateways race for the same counter, is the part that takes practice. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson three.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.