GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Distributed Rate Limiter

A rate limiter caps what one caller may do per second, and it has to hold that count across a whole fleet without becoming the slow part of every request. The full interview walk, from requirements through the deep dives, with the bar named at every level from intern to principal.

A rate limiter looks like the easiest interview on the board: count a caller’s requests, say no past a hundred. It is a trap. The counter is state that every single request wants to write at the same instant, and the moment you run more than one server that count fractures, races, and lies. Each server sees a slice of the traffic and waves through a caller who is already far over the line. The whole difficulty hides in two facts: the check runs on every request so it must be almost free, and the count is shared so more than one server means coordination under contention. This breakdown walks the exact path a great candidate takes: how you make the count-and-check one atomic step, which limiting algorithm you pick and why, how a single counter survives a million writes a second, and what the gate does the moment it cannot reach its own state.

Practise one part of it on a canvas that tests your design: Rate Limit Each Client.

The problem, made real

The interviewer slides one sentence across the table: "Something is hammering our API. Put a bouncer on the door." That is the whole brief, no rules, no scale numbers, no hints, just a threat and a promise.

The short answer, before the walk. A rate limiter answers one question on every request, is this caller allowed right now, and it has to answer in under a millisecond while the whole fleet agrees on the count. That last part is the interview: one server counting alone is easy and wrong, because a caller spread across twenty servers gets twenty times the limit. So the count moves to a shared store, the read and the write become one atomic step, and everything after that is about keeping a shared store off the critical path and alive during the flood it exists to survive.

Concretely: the API behind the door mints resources, serves reads, and is called by real products. Right now a single scraper is firing about three thousand requests a second at the write endpoint. Three thousand a second, across the eighty-six thousand four hundred seconds in a day, is roughly two hundred and sixty million requests from one client. Every one of them costs you a server cycle and a line in the bill, and every one of them is ahead of a creator in the queue. So the scraper is not only expensive. Left alone it can topple the service the creators depend on.

The fix is a gate every request passes through first. It asks one question, "is this caller allowed right now?", and returns one of two answers: yes, go on through, or 429 Too Many Requests, come back later. That is the entire product a caller ever sees.

What makes it a real interview and not a five-minute toy is what lives under that one question. Three facts do all the work, and each one has a consequence you should say in the same breath. The gate meets one hundred percent of traffic, including the attack it exists to stop, so it can never be the slow part. Its answer is added to the latency of every request behind it, so whatever the check costs, the whole API pays it forever. And the count it answers from is written by every request at once, so the interesting problem is not counting, it is many writers racing for one number. Hold those three and the rest of the design answers to them.

What the system must do

The first move is to turn that one sentence into a short list of what the gate must do, and, just as important, to name what it will not. A weaker candidate reaches for everything: a dashboard of rules, machine-learned bot scoring, per-endpoint analytics. A stronger one scopes down on purpose. In a one-hour round the flex is not breadth. It is picking the two or three requirements that actually carry the product, and defending the cut.

State them most-important first. The order is itself a signal, because it tells the interviewer you know which sentence the traffic hangs off.

The three things the rate limiter must do

  1. Identify who is calling, so a limit lands on the right caller. A signed-in creator is their user ID; a partner integration is its API key; an anonymous scraper is still an IP address. This is cheap to state and quietly plants the layered-rules question: one request can match a per-user rule and a per-IP rule at once, so which wins?
  2. Enforce a configurable limit, say one hundred requests per minute per caller, allowing everything inside the limit and rejecting everything past it. This is the heart of the product. The algorithm that actually decides "over or not" is rich enough to be its own deep dive later; here we just commit to the behaviour.
  3. When a caller is over, reject fast with 429 Too Many Requests and headers that say the ceiling, how many requests are left, and when the limit resets. A good "no" is not a slammed door. It tells a well-behaved caller exactly how to back off instead of retrying blindly and making the flood worse.

What must be true of it

Functional requirements say what the gate does. Non-functional requirements say what must be true of it while it does them: how fast, how reliable, how correct under load. This is where the interview is won or lost, because a wish is easy and a requirement carries a number. "It should be fast" is a wish. "The check adds under ten milliseconds at the ninety-ninth percentile" is a requirement, and you can hold a design against it and watch it pass or fail.

Put a number on everything you can. Two promises can be stated right here. The third, the scale, how much traffic the gate must survive, you have no honest basis to name yet, so we make you earn it from arithmetic in the next phase rather than hand it over.

The promises the gate bets the API on

  • Latency: the check is almost free, under about 10 ms at p99. The gate sits in front of every request, so whatever the check costs is added to everything behind it. A limiter you cannot keep cheap is a tax on the entire API, paid on every call, forever.
  • Availability: the gate must never become the outage. Highly available, think 99.99%, and it may be eventually consistent. If two servers each let a caller slip a handful of extra requests during a brief blip, the sky does not fall. A caller wrongly locked out, or the whole API dark because the limiter died, is a far worse failure than a little over-counting.

Size the flood before you draw the gate

Before a single box goes on the whiteboard, size the system. The goal is not precision. It is order of magnitude, the power of ten that decides the architecture. Ten thousand requests a second and ten million are different machines. Keep the arithmetic honest and round hard: false precision ("973,412 ops") reads as nerves, a confident "call it a million a second" reads as fluency.

Start from the number that matters here, the flood. Say peak traffic is around one million requests a second. Now follow it through the gate one step at a time. Every one of those requests hits the gate, because a limiter that only sees some traffic is not a limiter. The gate does exactly one thing to answer each one: it reads the tally, adds one, and decides. That is one read-modify-write per request, with no batching available to soften it, because each request needs its own answer before it can proceed. So one million requests a second is one million atomic counter writes a second. The request rate and the write rate are the same number, and that identity is the whole problem in one line.

Three numbers fall out of it, and the third is the one that decides the architecture.

Back-of-the-envelope for the rate limiter, rounded to the power of ten that matters.
QuestionThe arithmeticThe answer
How many counter writes per second at peak?1,000,000 requests/s × 1 atomic read-modify-write each~1,000,000 atomic writes/s, one for every request, with no batching to hide behind
How much memory to hold the counters?~100,000,000 daily callers × ~50 bytes (id, count, timestamp, headroom)~5 GB, a few gigabytes, so it fits in the RAM of a single modest node
How many writes can one in-memory node take?1,000,000 writes/s ÷ ~100,000 atomic ops/s per node~10 nodes at 100%, so a dozen in practice; one node cannot hold the count at all

Walk the second and third rows out loud, because they point in opposite directions and that contrast is the punchline.

The memory first. A hundred million daily callers, at about fifty bytes each for an identity, a count, a timestamp and a little headroom, is five billion bytes. Five billion bytes is five gigabytes. Five gigabytes fits in the memory of one ordinary machine with room to spare, so you could hold every counter on a single box and still have most of it free.

Now the writes. One in-memory node handles somewhere around a hundred thousand atomic operations a second. The flood is a million. A million divided by a hundred thousand is ten, so ten nodes would be running at exactly one hundred percent of their capacity, which is not a design, it is a dare. Run a dozen and each sits near eighty percent, which leaves room for a bad minute. Either way the conclusion is the same and it is not a small one: the count does not fit on one node, and it never will.

The smallest data model that works

Name the data before the boxes. A rate limiter looks stateless from the outside, but it lives or dies on one tiny, furiously-written record. Three nouns carry the whole product.

The three entities

  • Rule, a limit policy. It carries the ceiling (say 100), the window (say 60 seconds), the scope it applies to (which callers, which endpoints), and how it identifies a caller (by user, IP, or API key). Rules are read on every request and changed rarely, which is exactly the shape that wants a cache in front of it.
  • Caller, the thing being limited: an identity (a user ID, an IP address, or an API key) together with the limit state that tracks it. A caller is not tied to one counter, because the same request can be measured against several rules at once.
  • Counter, the live state for one (caller, rule) pair: the current tally or remaining tokens, plus the timestamp it was last touched (the window start, or the last refill). This is the single most-written object in the entire system. Every design decision from here, atomicity, sharding and hot keys, is really about protecting this one small record under a flood.

Two faces: the check and the controls

A rate limiter has two interfaces, and they could not be more different. One is called a million times a second and must be almost invisible. The other is called by an operator a few times a week and is allowed to be slow, and even a little stale. Keep them separate in your head and the contract writes itself. Hold on to the split, too, because the design you are about to draw grows in exactly those two lanes.

The hot path is the check. It is not a public REST endpoint a caller hits. It is an in-process or edge call the gate makes on every request, before anything else runs.

The check (hot path) and the admin surface (control plane).
InterfaceShapeReturns / status
The check (hot path)isAllowed(callerId, ruleId), a local call at the gate, run before the request proceeds{ allowed, remaining, resetAt }, the decision plus the numbers the response headers need
Allowed → the request continuesthe gate forwards the request downstream, untouched200-and-onward. The caller never knows the gate was there
Rejected → stop it at the doorheaders RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, Retry-After429 Too Many Requests, a machine-readable "no" with a "come back in N seconds"
Change a limit without a deployPUT /admin/rules/{ruleId} with the new ceiling/window in the body200 on update, a control-plane write that seeds the dynamic-config deep dive

Where the gate lives

Now draw it, but do not draw the finished thing. Start where you would actually start, with the smallest arrangement that does the job at all, and let each requirement pull the next piece into the picture. The figure below is the same picture every time it appears; it just grows as the story earns it, and the chips under it are the promises made so far.

Here is the honest starting point. There is one API and the check runs inside it, on a counter in that server’s own memory.

The interactive version of this example is available when JavaScript loads.

That is the fastest check that can exist: no network, no coordination, a few nanoseconds of arithmetic on a number that is already in the CPU’s reach. It is also wrong, and the way it is wrong is the whole reason this problem is an interview.

Run two API servers behind one address and each one keeps its own private counter. A caller with a limit of a hundred a minute can now send a hundred to the first server and a hundred to the second, and both servers are certain they behaved. Run five and the caller gets five hundred through a limit of one hundred. Nothing failed, no alert fired, and the number in your requirements document is now decoration.

So where does the check go instead? There are three homes for it, and each one fixes the flaw in the one before.

Where to put the check. The third rung is the production default.
PlacementWhy it appealsWhere it breaks
Inside each app server (in-process)Fastest possible: the count lives in local memory, zero network hopsEach server sees only its slice of traffic. Five servers behind a balancer each allow 100 → 500 slip through. Only works for a single server, or when approximate limits are acceptable.
A dedicated limiter service every server callsOne global count, and the caller can pass rich context ("premium tier", "this endpoint")An extra network hop on every single request, half a millisecond of the ten you have, spent asking another service to do arithmetic, plus a new service that can fail and must itself be made highly available.
At the API gateway, the front door (chosen)Every request already passes through it; check once, before any app server sees blocked trafficThe gateway can only see what is in the request (headers, IP, key), and it needs somewhere fast to keep the shared count, which is the whole rest of the design.

Put the gate at the API gateway. Two reasons, and the second is the one candidates miss. The obvious one: every request already crosses the gateway, so the check costs no extra hop, and you are adding work to a stop the request was making anyway. The quieter one: a rejected request now dies at the front door, so the app servers never spend a cycle on the flood. That is not a latency detail. It is the difference between a limiter that protects the backend and a limiter that merely reports on it.

The interactive version of this example is available when JavaScript loads.

Look closely at what that picture still gets wrong, because it is the same bug one level up. The count is sitting in the gateway’s memory.

So ask how many gateways there are. One gateway instance does terminate TLS, authenticate, route and run policy on every request, which is real work, and it tops out around twenty thousand requests a second. The flood is a million. A million divided by twenty thousand is fifty. Fifty gateways, each holding its own private count.

That is not a smaller version of the in-process bug, it is a bigger one: fifty independent counters, each admitting a full hundred, is five thousand requests through a limit of one hundred. The fracture did not get fixed by moving to the door. It got fifty times wider, because moving the check to the front door also multiplied the number of places the check runs.

Therefore the gateways must hold nothing. Split the two halves of the check: the decision stays at the edge, because that is the part that has to be cheap and close to the caller, and the count moves out into one shared in-memory store that every gateway reads and writes. Now every gateway is asking the same number the same question, and you can run one gateway or a hundred without changing a single answer.

The interactive version of this example is available when JavaScript loads.

How the gate decides: over the line, or not

With the gate placed and the count externalised, look at the question it answers a million times a second: is this caller over the limit? There are a handful of ways to decide, and the interview reward is knowing the trade-off rather than writing the code. Walk them the way the field actually discovered them, each one invented to fix the flaw in the one before.

Start with the simplest. Fixed window: chop time into clock buckets, so a fresh counter every minute, and count requests in the current bucket. It is one number per caller and trivial to run. Add one, and let the bucket expire on its own.

Its flaw has a name: the boundary burst. Do the arithmetic on a limit of one hundred a minute. A caller fires a hundred requests at 14:31:59 and the counter for the 14:31 bucket goes from one to a hundred, all allowed. One second later, at 14:32:00, the bucket changes, so the counter for 14:32 starts at zero, and the caller fires another hundred. Those are also all allowed. Two hundred requests in about two seconds, through a limit of one hundred a minute, nearly double the ceiling, and nothing malfunctioned. The window simply moved. Fire the toggle below and watch a burst straddling the boundary slip through.

The interactive version of this example is available when JavaScript loads.

The sliding window log fixes the burst by being exact: keep the timestamp of every request and, on each new one, count only those inside the last sixty seconds. There is no boundary to exploit, because the window’s edge moves with the caller rather than with the clock. The 14:31:59 plus 14:32:00 burst above is now simply two hundred requests inside one sixty-second view, and the second hundred are refused.

But look at what it costs, and notice that the cost scales with the wrong thing. You are storing one timestamp per request, so a caller allowed a hundred a minute holds a hundred entries. Raise their limit to ten thousand a minute and that one caller holds ten thousand entries. Multiply by a hundred million callers and the store is no longer holding a counter, it is holding a log of your entire traffic. Perfect accuracy, paid for in memory that grows with your busiest customers.

The sliding window counter is the hybrid most production systems actually reach for, and the concept page works the weighting through on its own timeline if you want to see the boundary burst close. Keep just two numbers, this minute’s count and last minute’s, and weight the previous window by how much of it is still inside your view. Work one through. Say you are eighteen seconds into 14:32, this minute’s count is thirty, and last minute’s was ninety. Eighteen seconds into the minute means forty-two of the previous sixty seconds are still in the window, and forty-two divided by sixty is zero point seven. So the estimate is thirty plus ninety times zero point seven, which is thirty plus sixty-three, which is ninety-three. Ninety-three is under a hundred, so this request is allowed, and the boundary burst that fixed window waved through is refused here, because last minute’s hundred is still weighing on this one.

Two numbers per caller instead of ten thousand, and the boundary is smoothed. The catch is honest to state and you should state it: the weight assumes last minute’s ninety requests were spread evenly across those sixty seconds. If they all landed in the first second, then none of them are really in your window, the true count is thirty, and you just refused someone unfairly. It is an approximation. It is a cheap and very good one.

The interactive version of this example is available when JavaScript loads.

The token bucket is the default worth defending. Picture a bucket that holds up to N tokens and refills at a steady rate; every request spends one, and an empty bucket means 429. Two numbers capture both things an API actually wants. The depth is the burst you tolerate, so a bucket that holds a hundred lets an idle caller spend a hundred at once. The refill is the rate you allow forever, so a hundred tokens per sixty seconds is one point six seven tokens a second, and a caller who never stops is served at exactly that rate and no faster.

That is why so many real APIs describe their limits this way: the two numbers are the promise, in the same words the customer reads. Feel it below. Let the bucket sit idle and it refills to full, which is a saved-up burst; then hammer it and watch it drain to empty and start rejecting at the refill rate.

The interactive version of this example is available when JavaScript loads.

There is one more rung, and reaching it is a principal-level flourish the standard breakdowns skip. The generic cell rate algorithm, GCRA, gives you exactly the token bucket’s behaviour, but it stores a single timestamp instead of a counter.

Here is the idea in one step of arithmetic. If the policy is a hundred requests per sixty seconds, then each request costs sixty seconds divided by a hundred, which is six hundred milliseconds of the caller’s allowance. So instead of counting requests, record one moment: the earliest time the next request may arrive if the caller keeps to that rate. Each check is then a comparison against that moment, and each allowed request pushes it six hundred milliseconds further out.

Why care, when the token bucket already works? Because of what a check has to WRITE. The token bucket reads a count, adds to it, and writes it back, three steps you are about to spend a whole section learning to fuse into one. GCRA writes one timestamp, and "write this only if it has not moved since I read it" is already a single atomic instruction in every store there is. Hold that thought, because it is the bridge to the next section.

The interactive version of this example is available when JavaScript loads.

The race that lets 101 through a limit of 100

Pick the token bucket, put its count in the shared store every gateway reads, and a subtle bug is already waiting, the one this entire archetype exists to teach. The check looks like three innocent steps: read the current count, decide if it is under the limit, write the new count back. Run those as three separate operations against the store, and two requests for the same caller can race straight through each other.

This is the point where a rate limiter stops being a counter and becomes a distributed-systems problem, and it is worth reading distributed rate limiting alongside this section: it takes the same fracture from the other end, starting from what a limiter is and working up to why a count that is perfect on one server is a lie on ten.

Two requests, a limit of 100, a counter at 99, and both slip through.
MomentRequest ARequest BThe count
t0reads the count → 99reads the count → 99 (before A has written)99
t1under 100 → decides allowunder 100 → decides allow99
t2writes 100writes 100100
t3throughthrough101 admitted under a limit of 100

Both requests read the same stale ninety-nine, both judged themselves safe, and the limit leaked. Notice where the decision was made: not in the store, but in the gateway’s own memory, on a copy of a number that another gateway had already invalidated.

At two requests that is one extra caller through the door. Scale it up and the shape gets worse rather than better, because the more traffic arrives at once, the more requests read the same stale value before any of them write. So the leak is widest at precisely the moment the limit was the only thing holding. Drag the overlap up below and watch how much of the count simply vanishes.

The interactive version of this example is available when JavaScript loads.

The fix is not a bigger lock. It is to stop treating read-decide-write as three separable steps at all, and to widen the atomic boundary until the whole decision is inside it. Here is the ladder, and the middle rung is the one that catches people.

Closing the race, rung by rung

  1. A plain read followed by a write. Simple, and exactly the race above: the two operations have a gap, and another request lives in that gap.
  2. Wrap the writes in a transaction (a MULTI/EXEC-style bundle). It feels safer, and it does not fix this at all: the read happened before the transaction opened, so both requests still decided on the same stale ninety-nine, and both transactions then faithfully committed an increment. A transaction makes a group of writes all-or-nothing. It does not make read-then-write atomic. Still races.
  3. Run the whole decision as one atomic script on the store itself, reading, checking and writing in a single server-side step nothing can split. Now only one of the two racing requests can push the count to a hundred; the other reads a hundred and is refused. And look at the cost: one round trip, the same as the broken version. No lock, no waiting, no queue. Widening the boundary was free.

The interactive version of this example is available when JavaScript loads.

Notice what did not change in the picture when you fixed this. No new box, no extra hop, no queue. The same two nodes, and the store simply started doing the comparing. That is worth pausing on, because it is the cheapest fix in the whole design and the one candidates reach for last.

The interactive version of this example is available when JavaScript loads.

One store cannot take a million writes, so do not use one

The estimation already wrote the ending. One in-memory node handles about a hundred thousand atomic writes a second, the flood is a million, and a million divided by a hundred thousand is ten. Ten nodes at full stretch, a dozen if you want to survive a bad minute. Either way the count cannot live on one node.

So the only question left is how you split it, and there is a right answer and a tempting wrong one.

Split the count by the caller key. Every counter belongs to exactly one caller, a user, an IP, an API key, and the reason the split has to follow that boundary is simple: a limit is enforced on a caller’s whole count, so if one caller’s count lives in two places, neither place knows the truth and the limit is unenforceable. Therefore every request from a caller must land on the same node, which you get by hashing the caller key to choose the shard.

And here is the pleasant part, which is worth saying out loud because it sounds too lucky to be true. You are splitting for correctness, but the load comes out even anyway, because there are a hundred million callers and a dozen shards, so each shard owns roughly eight million of them, and eight million independent callers average out. Twelve shards at a hundred thousand writes each absorb one point two million a second, comfortably past the flood. The algorithm from the last two sections does not change by a line; each gateway simply talks to the one shard that owns the caller standing in front of it.

The interactive version of this example is available when JavaScript loads.

In practice the whole split comes down to what you call the key, because the key is what gets hashed. Name it after the caller and the rule it is being measured against, and the routing takes care of itself, including the layered rules from earlier, since a request that must satisfy three limits simply reads three keys and takes the tightest verdict.

The interactive version of this example is available when JavaScript loads.

What the gate does when it can’t see the count

Sharding just bought you throughput and sold you something in exchange. A dozen shards means a dozen single points of failure, each one owning about eight million callers. So two questions follow, and a strong candidate raises both without being asked: what happens the instant a shard is unreachable, and how do you make that almost never happen.

Take the first. When a gateway cannot reach the count it has milliseconds to decide, and there are only two doors. Fail open: let the request through unprotected. Fail closed: reject it. Neither is free, and which one is right is a property of the system, not a default.

The interactive version of this example is available when JavaScript loads.

The failure-mode fork

  • Fail open, allowing requests when the count is unreachable. The API stays up, but it loses the very protection the gate exists for. And the trap is the timing: the store usually becomes unreachable because it is already buckling under a flood, so failing open at that exact moment takes the flood the gate exists to absorb and hands all of it to the backend in one step. You would turn a limiter outage into a full outage, at the worst possible moment.
  • Fail closed, rejecting requests when the count is unreachable. The protection holds, but legitimate callers get turned away, so you have converted the limiter’s outage into an API outage for as long as it lasts. Harsh, but bounded and safe.
  • The choice here: fail closed. The whole reason the gate exists is to survive floods, and a limiter failure most often coincides with one. A brief spell of honest 429s beats letting a viral spike collapse the service everyone depends on. A best-effort read API might choose the opposite; the point is that you choose, out loud, with the cost of a wrong answer in hand.

The interactive version of this example is available when JavaScript loads.

The interactive version of this example is available when JavaScript loads.

The hot key: sharding’s one blind spot

Sharding by caller assumes callers are many and roughly balanced. One case breaks that assumption on purpose: a single caller, a runaway bot, a misconfigured client, or a whole botnet hiding behind one shared office address, sends tens of thousands of requests a second by itself.

Put the numbers side by side, because the imbalance is larger than it sounds. A shard handles about a hundred thousand atomic writes a second and owns roughly eight million callers, so a shard’s whole capacity is meant to be shared by eight million people. One caller sending forty thousand a second is taking forty percent of that shard on their own. Two of them on the same shard and it is gone, melted, while its eleven neighbours coast.

And you cannot spread one caller’s counter across shards, because a split count is an unenforceable count, which is the same rule that chose the shard key in the first place. Therefore the fix is not to spread the traffic. It is to stop it before it ever reaches the counter. Drag the skew below and watch one partition melt while the rest idle, even though every partition owns the same number of keys.

The interactive version of this example is available when JavaScript loads.

Shedding a hot key, earliest first

  1. Local pre-reject at the gateway. A gateway that has already watched this caller blow past the limit can answer 429 locally for a short spell, a couple of seconds, without touching the shard at all. Note why the approximation is safe here: the shared count already refused this caller, so the gateway is not making a new decision, it is repeating a verdict. Being slightly stale about a caller who is provably over costs nothing, and it spares the hot shard entirely.
  2. A short-lived block list. A caller that trips its limit hard and repeatedly gets dropped onto a cheap, fast list that is checked before the expensive counter path, so the flood is shed at the door instead of hammering the count for the next five minutes.
  3. Push the genuinely abusive floods upstream. Volumetric attacks belong to the layer in front of the gate, an edge or DDoS-protection service that absorbs them so the limiter only ever sees plausible traffic. Rate limiting is fair-use enforcement rather than attack mitigation; know where one ends and the other begins.

The interactive version of this example is available when JavaScript loads.

Three questions that separate a staff answer

Three more questions sort a principal answer from a good one, and the standard breakdowns tend to wave at them. Reach them and you are past the interview. The first of them finally brings the second face of the API, the controls, into the picture, and it is the last piece the design needs.

Where the ceiling is

  • Dynamic rule config. Limits have to change without a deploy: raise them for a launch, cut them the instant an attack starts. Either the gateways poll a config store every few seconds (simple, and a few seconds of staleness you name and accept), or the config is pushed to them (instant, more moving parts). Poll is usually enough. The senior move is to say the number: at a five-second poll, a limit you cut during an attack is fully in force five seconds later, and for those five seconds some gateways are still enforcing the old ceiling. Naming the window is the whole difference between a design and a hope.
  • Multi-region. Callers are global, so gateways and counter shards live in many regions, and a globally-strict count would mean a cross-region hop on every request. Price that: a round trip between continents is on the order of a hundred and fifty milliseconds, against a promise of ten. It is not close, so a globally-strict count is not slow, it is impossible. Therefore each region enforces locally and reconciles loosely, either a global cluster with accepted lag or per-region quotas that sync every second or two, tolerating a small window where a caller slips a little extra across regions. It is the same per-requirement CAP call from the NFRs, made once more: availability and latency win over a perfectly-global tally.
  • Observability, the half the references skip. You cannot run a gate you cannot see. Watch the check latency (the tax it charges every request), the store’s error rate (are we quietly failing open?), and the top blocked callers (is this abuse, or a real customer you just throttled?), rather than merely the raw count of 429s. And alert the moment the gate enters fail-open, because that is the exact window the API is running unprotected.

The interactive version of this example is available when JavaScript loads.

What each level is expected to reach

The same problem is graded differently at each level. Here is what a passing walk looks like from intern to principal, and what moves is not the number of boxes, it is how much of the reasoning is made visible.

One problem, four bars. Each level owns everything below it and adds its own row.
LevelWhat a passing answer reaches
SDE1Scopes the three requirements, puts the gate at the front door, names one algorithm (fixed window) and spots its boundary burst, and knows the count has to live somewhere shared. Guided, but the shape is right.
SDE2Reaches the token bucket and defends depth-versus-refill, states the NFRs with numbers, derives the write-scaling capstone from the estimate, and names the race, that read-then-write is not atomic, even if the fix needs a nudge.
SDE3Owns the contention fix (one atomic step, not a lock), shards the count by caller with consistent hashing, reasons the fail-open-versus-closed trade and picks with a why, and raises hot keys and how to shed them, unprompted.
PrincipalReaches GCRA and can say why a timestamp beats a counter under contention, connects the algorithm and the contention fix as one move, prices multi-region against the latency budget rather than asserting it, and treats the store timeout, observability and fail-open alerting as part of the design, not an afterthought.

The traps that sink an answer

Seven ways a rate-limiter answer goes wrong

  • Keeping the count in the gateway’s memory. The moment there is more than one gateway, each sees a slice and the limit leaks. The count is external and shared, always.
  • Wrapping the writes in a transaction and calling the race solved. If the read happened outside the transaction, both requests still decided on the same stale number. Atomicity has to contain the read, the check, and the write together.
  • Sharding for even load instead of by caller. Round-robin or shard-by-rule scatters a caller’s count and makes it unenforceable, and round-robin does it without a single alert firing. Shard by the caller key; balance follows for free.
  • Failing open by reflex. The store usually dies under load, so failing open then hands the whole flood to the backend. Choose the failure mode deliberately, per system.
  • Leaving the store timeout at its default. Seconds-long client defaults mean one dead shard stalls every request bound for it, which is neither failure mode. It is falling over. Tens of milliseconds, and no retry on the hot path.
  • Forgetting the fixed-window boundary burst. It looks correct in a demo and lets through nearly double at the minute edge. If you name fixed window, name its burst.
  • Treating it as a storage problem. The counters are five gigabytes; the difficulty is a million atomic writes a second landing on the hottest keys. Scale the writes, not the bytes.

Interview cheat-sheet, from intern to principal

What are the three functional requirements, really?
Identify the caller (user, IP, or API key), enforce a configurable limit (allow within, reject beyond), and reject over-limit requests with 429 plus headers that say the ceiling, what is left, and when it resets. ML bot-detection, a rules admin UI, and limit analytics are out of scope for the hour.
What is the single most important property of this system?
The count is shared state written by every request at once. Almost every hard decision is really about making that shared read-modify-write correct and fast under a flood: contention first, write-scale second.
Where does the rate limiter live, and where does the count live?
The check runs at the API gateway (the front door every request already crosses), so the gateways stay stateless and decide at the edge; the count lives in a shared in-memory store they all read and write. Split the decision from the state.
Which algorithm, and why?
Token bucket by default, because its depth is the burst allowance and its refill is the steady rate, the two things an API actually wants, in two numbers. Fixed window is simplest but lets nearly 2× through at the boundary; sliding log is exact but stores a timestamp per request; sliding-window counter is the accurate-enough hybrid on two numbers; GCRA stores one timestamp instead of a counter, which is the principal-level flourish.
How do you stop two requests from both slipping past the limit?
Make the read-check-write one atomic step on the store (a single server-side script) rather than three operations with a gap. A plain transaction is not enough, because the read happened outside it, so both requests still see the same stale count. And it costs one round trip, the same as the broken version.
How do you handle a million requests a second?
One store cannot take a million atomic writes. A node does about a hundred thousand, so a million needs ten at full stretch and a dozen in practice. Shard the count by caller key with consistent hashing: one caller to one shard, and because there are a hundred million callers, the load spreads on its own. The counters are only five gigabytes; the write rate, not the storage, is the constraint.
What happens when the count store is unreachable?
Fail open (stay up, lose protection) or fail closed (reject, stay safe) is a deliberate per-system choice. This design fails closed because a limiter failure usually coincides with the flood it exists to stop. Set the store timeout in tens of milliseconds so the decision actually gets made, and replicate each shard so the failure is rare in the first place.
One caller is hammering a single shard. Now what?
A hot key. One caller at forty thousand a second is forty percent of a shard meant to serve eight million callers, and you cannot split their counter without making the count unenforceable. So shed the traffic earlier: reject locally at the gateway for a couple of seconds, drop repeat offenders on a cheap block list, and push volumetric attacks to an upstream DDoS layer. It is the write-side mirror of a viral read hot key.
How does a limit change without a deploy, and what does that cost?
An operator writes the rule through the admin surface and the gateways poll for it: a control plane called a few times a week, next to a check called a million times a second. The cost is a named staleness window. At a five-second poll, a limit you cut mid-attack is fully in force five seconds later, and some gateways enforce the old ceiling until then. Saying the number is the senior move; pretending it is zero is not.

Takeaway

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.