Design a Rate Limiter

How to design a distributed API rate limiter: algorithms, shared atomic counters, behaviour when the store fails, and what interviewers ask about it.

Case study26 minLesson 2 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A rate limiter sits in front of an API and rejects requests from clients that send more than they are allowed to. It protects the backend from overload and abuse, and it stops one client from using the capacity that other clients need.

The question is popular because the service is small but touches several hard topics: counters shared by many servers, atomic updates, race conditions, clocks, and deciding what to do when the limiter's own dependency fails. Rate Limiting explains the algorithms on their own; this case study builds the whole service, following A Framework for Any Design.

Clarify the problem

"Design a rate limiter" can mean a class in one process or a company-wide service, so first find out which.

The first five minutes
Interviewer

Design a rate limiter for our public API.

You

Does the limiter run inside one service, or is it shared by many gateway servers? And do we limit by API key, account or IP address, with different limits for different plans?

Interviewer

It is shared, because every request passes through one of our API gateways. We limit per API key for logged-in traffic and per IP address for anonymous traffic. Plans have different limits, and the login endpoint has its own strict limit.

You

How many requests a day do we handle, and how many distinct clients are there?

Interviewer

About a billion requests a day, from around 10 million API keys and a similar number of IP addresses.

You

Then I will assume the check adds under 2 ms at p99, a limiter outage must not take the API down, and limits may be a few percent loose but never ten times loose. Billing and dashboards are out of scope.

  • Functional: limit requests per API key, per IP address and per account, with rules that vary by endpoint and plan. Reject excess requests with status 429 and a retry time. Allow operators to change rules without a deploy.
  • Non-functional: the check adds under 2 ms at p99. The API stays up if the limiter's store is down. Counts are shared across gateways and accurate to within a few percent. Rule changes take effect within about 10 seconds.
  • Out of scope: billing, usage dashboards and bot detection.

Estimate the scale

A day has 86,400 seconds. The estimate assumes that peak traffic is three times the average and that each request is checked against two rules, one for its API key and one for its IP address.

Estimate: Counter store load at peak

How many counter operations per second must the shared store handle at peak?

You know
  • 1 billion API requests a day
  • Peak is 3x the average
  • Each request is checked against 2 rules, one store operation each

Show the working
  1. Average: 109 ÷ 86,400 s ≈ 11,600, rounded up to 12,000 a second
  2. Peak: 12,000 × 3 = 36,000 requests a second
  3. Store operations: 36,000 × 2 = 72,000 a second

Estimate 72 thousand/s (anything from 30 thousand/s to 200 thousand/s is a good answer)

An in-memory node handles about 100,000 simple operations a second, but each check runs a small script, so plan for about 50,000 a node. That needs 2 nodes at minimum, and 4 shards leave room for failures.

Your turn: Define the API

Sketch three interfaces before reading on: what clients see, what the gateway asks the counter store, and how operators change rules.

Compare with a model answer

Clients see a 429 response with a Retry-After header, and headers on every response that show how much of the limit is left. The gateway makes one atomic "take a token" call to the counter store for each rule. Operators write rules to a config store, and the gateways reload them.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

What clients see, and the internal calls
Every response from the API:
  X-RateLimit-Limit: 100        bucket size for the tightest rule
  X-RateLimit-Remaining: 36     tokens left after this request
 
Rejected request:
  429 Too Many Requests
  Retry-After: 1                seconds until a token is available
  body: { "error": "rate_limited", "rule": "key-free-plan", "retry_after_s": 1 }
 
Gateway to counter store, one atomic call per rule:
  take(key, capacity, refill_per_sec, cost = 1)
    -> { allowed, remaining, retry_after_ms }
 
Operators:
  PUT /admin/rules/{rule_id}    body: the rule (see the data model)
  400 if the rule is invalid; gateways pick up changes within 10 s

The API decision worth arguing is the status code. A 429 means that this client sent too much, while a 503 means that the service is overloaded. The limiter should return 429, so that a well-behaved client reads Retry-After and slows down. Keep 503 for load shedding, because a client that reads a limit as a server fault retries at the wrong times.

Your turn: Model the data

List the records the system keeps, how big each one is, and how often it is read and written. Pick a kind of store for each.

Compare with a model answer

Rules are a few hundred records that are read constantly and changed rarely, so every gateway keeps them in memory. Counters are 20 million small records that are written on almost every request, so they belong in an in-memory key-value store.

Model the data

Rules (config store) and counters (in-memory store)
rule
  rule_id          "key-free-plan"
  match            endpoint pattern and plan, e.g. "/v1/*", plan = free
  key_by           api_key | ip | account
  capacity         100            burst size
  refill_per_sec   10             long-run rate
  on_store_down    open | local | closed
 
counter            key = "rl:{rule_id}:{subject}"   e.g. "rl:key-free-plan:k_8f3a"
  tokens           float, 8 bytes
  last_refill_ms   integer, 8 bytes
  TTL              capacity / refill_per_sec = 100 / 10 = 10 s

The rules are a few hundred records in any durable config store, and each gateway polls them into memory every 10 seconds.

The counters are updated on almost every request and must answer in about half a millisecond. That calls for an in-memory key-value store, such as Redis, that runs small scripts atomically and expires keys. Losing a counter only gives one client a fresh, full bucket, so durability matters little.

Twenty million buckets of about 100 bytes each come to 2 GB, so memory does not limit the design. The TTL frees idle buckets without changing any answer, because a bucket idle for 10 seconds is full again and a missing key is treated as full.

Your turn: High-level design

Sketch where the check happens, where the counters and rules live, and what a rejected request touches.

Compare with a model answer

The limiter is a library inside each gateway, so the only extra hop is the call to the counter store. A rejected request never reaches the backend services.

High-level design

The limiter runs as a library inside each API gateway. Making it a separate service would add a network hop to every request and a second fleet of servers to operate. The counter store has 4 shards by key, each with a replica.

Each gateway checks the counters in a shared store before forwarding a request, and rules reach the gateways in the background, off the request path.API clients to API gateway + limiter (HTTPS); API gateway + limiter to Counter store (4 shards) (take(key)); Rules store to API gateway + limiter (reload every 10 s), asynchronous; API gateway + limiter to Backend services (if allowed).API clientsAPI gateway +limiterCounter store (4shards)Rules storeBackend servicesHTTPStake(key)reload every 10 sif allowed

request and replyasynchronous message

Each gateway checks the counters in a shared store before forwarding a request, and rules reach the gateways in the background, off the request path.
Allowed, rejected, and the store goes downUse the arrows or ← → keys
  1. Allowed, rejected, and the store goes down, step 1API client to API gateway + limiter; API gateway + limiter to Counter store; Rules store to API gateway + limiter, asynchronous; API gateway + limiter to Backend services.API clientAPI gateway +limiterCounter storeRules storeBackend services
    tokens
    37
    allowed
    0
    rejected
    0

    1A free-plan client with key k_8f3a calls GET /v1/orders. Its bucket holds 37 of 100 tokens and refills 10 a second.

  2. Allowed, rejected, and the store goes down, step 2API client to API gateway + limiter; API gateway + limiter to Counter store; Rules store to API gateway + limiter, asynchronous; API gateway + limiter to Backend services.API clientAPI gateway +limiterCounter store37 → 36Rules storeBackend services
    tokens
    36
    allowed
    1
    rejected
    0

    2The gateway makes one atomic call to the shard that owns rl:key-free-plan:k_8f3a. The shard refills the bucket and takes one token in about 0.5 ms.

  3. Allowed, rejected, and the store goes down, step 3API client to API gateway + limiter; API gateway + limiter to Counter store; Rules store to API gateway + limiter, asynchronous; API gateway + limiter to Backend services.API clientAPI gateway +limiterCounter storetokens: 0Rules storeBackend services
    tokens
    0
    allowed
    38
    rejected
    0

    3A buggy client loop then sends 80 requests in 0.1 seconds. The bucket holds 36 tokens and refills 1 more in that time, so 37 of the 80 requests pass and the bucket reaches zero. Allowed requests are forwarded to the backend.

  4. Allowed, rejected, and the store goes down, step 4API client to API gateway + limiter; API gateway + limiter to Counter store; Rules store to API gateway + limiter, asynchronous; API gateway + limiter to Backend services.API clientAPI gateway +limiter429Counter storeRules storeBackend services
    tokens
    0
    allowed
    38
    rejected
    43

    4The other 80 − 37 = 43 requests receive 429 with Retry-After: 1, and the backend never sees them.

  5. Allowed, rejected, and the store goes down, step 5API client to API gateway + limiter; API gateway + limiter to Counter store; Rules store to API gateway + limiter, asynchronous; API gateway + limiter to Backend services.API clientAPI gateway +limiterlocal limitCounter storedownRules storeBackend services

    5The shard that holds this key dies and the call times out after 5 ms. The rule says on_store_down: local, so the gateway checks an in-memory bucket that holds its share of the limit.

  6. Allowed, rejected, and the store goes down, step 6API client to API gateway + limiter; API gateway + limiter to Counter store; Rules store to API gateway + limiter, asynchronous; API gateway + limiter to Backend services.API clientAPI gateway +limiterCounter storedownRules storeBackend services

    6Requests that fit within the local limit pass, so the API stays available and is still roughly limited while the shard's replica is promoted.

1 / 6

Deep dives

Interviewers usually push on the algorithm, the shared counter, store failure and the identity a limit applies to.

Choosing the algorithm for each rule

The problem is to count requests so that the limit is enforced cheaply and without surprising clients. Different rules protect different things, so the choice is made per rule.

A token bucket gives each client a bucket that holds a fixed number of tokens and refills at a steady rate. Each request removes one token, and a request that finds the bucket empty is rejected. The state is two numbers per key, and it allows a burst as large as the bucket while holding the long-run rate at the refill rate. Its weakness is that a full bucket lets a whole burst through at once, which a fragile backend may not tolerate.

A sliding window log stores the timestamp of every accepted request and counts those inside the last window. The count is exact, but a limit of 5,000 requests an hour needs up to 5,000 timestamps per client.

A fixed window counter keeps one integer per client per window and resets it when the window ends. It is the cheapest option, but a client can send the full limit at the end of one window and again at the start of the next, which is up to twice the limit in a short time.

A sliding window counter removes most of that error by keeping the counts of the current and previous window. With a 60-second window and a request 15 seconds in, the estimate is the current count plus 75 percent of the previous count. It stores two integers and is accurate to within a few percent.

Which algorithm for which rule
OptionGood atBad atPick it when
Token bucket Usual defaultIt allows short bursts and holds the long-run rate.A full bucket lets a whole burst through at once.General per-key and per-IP limits. This is my default here.
Sliding window logThe count over the window is exact.It stores one timestamp per request.Small limits that must be exact, such as login attempts.
Sliding window counterIt stores two integers and avoids most of the edge error.The count is an estimate.Large limits where bursts should not be allowed.

I would use a token bucket for the general per-key and per-IP rules, because bursts from real clients are normal and the backend has headroom for them. Login uses a sliding window log, because its limit is tiny and has to be exact. A fixed window counter is enough for coarse daily quotas.

Sharing counters across gateways with atomic updates

If each of 20 gateways counted on its own, a client whose requests were spread across all of them could send up to twenty times its limit. So the count for each key lives in one place, on the shard chosen by consistent hashing of the key, which means that adding a shard moves only a small share of the keys. The danger is to split the check from the update, as the next tracer shows.

The read-then-write race, and the fixUse the arrows or ← → keys
  1. The read-then-write race, and the fix, step 1Gateway A to Counter shard; Gateway B to Counter shard.Gateway AGateway BCounter shardtokens = 1
    tokens
    1
    allowed
    0

    1The bucket for k_8f3a holds 1 token. Two requests from this key reach gateways A and B in the same millisecond.

  2. The read-then-write race, and the fix, step 2Gateway A to Counter shard; Gateway B to Counter shard.Gateway Aread 1Gateway Bread 1Counter shardtokens = 1
    tokens
    1
    allowed
    0

    2In the naive version, both gateways read the bucket before either has written back, so each sees 1 token and decides to allow its request.

  3. The read-then-write race, and the fix, step 3Gateway A to Counter shard; Gateway B to Counter shard.Gateway AGateway BCounter shardtokens = 0
    tokens
    0
    allowed
    2

    3Both gateways write tokens = 0 and both requests pass, so two requests used one token.

  4. The read-then-write race, and the fix, step 4Gateway A to Counter shard; Gateway B to Counter shard.Gateway AallowedGateway B429Counter shard1 → 0
    tokens
    0
    allowed
    1

    4The fix is to run refill, check and take as one script that the shard finishes before starting the next. A's script takes the token and B's finds 0 tokens, so one token allows one request without locks.

1 / 4
The atomic take, run inside the counter store
take(key, capacity, rate, cost):
  now = store's own clock, in ms
  tokens, last = read key            (missing key: tokens = capacity, last = now)
  tokens = min(capacity, tokens + (now - last) / 1000 * rate)
  if tokens >= cost:
      tokens = tokens - cost
      allowed = true
  else:
      allowed = false
  write key = (tokens, now), expire after capacity / rate seconds
  return allowed, floor(tokens), time until tokens >= cost

Two details show that you have built this before.

  • Use the store's clock, not the gateway's. Gateway clocks drift apart, and if gateway A's clock is behind gateway B's, then now - last can become negative and the refill calculation breaks.
  • Never retry a take that timed out. The store may have taken the token before the reply was lost, so a retry would charge the client twice. Treat a timeout as "store unavailable" and apply the failure behaviour below.

Failing open, failing closed, or limiting locally

The problem is that the limiter now depends on the counter store, and the gateway must decide what to do when the store does not answer within its 5 ms timeout. There are three choices, and the right one depends on the endpoint.

Failing open means allowing every request while the store is down. A limiter outage then never becomes an API outage, but there is no protection until the store returns, and one abusive client can hurt everyone in the meantime.

Falling back to local limits means that each gateway keeps an in-memory bucket per key and enforces its own share of the limit. With 20 gateways and a rule that refills 10 tokens a second, each gateway allows 10 ÷ 20 = 0.5 a second for that key, so a client spread evenly across all gateways still gets 20 × 0.5 = 10 a second. The weakness is that a client routed to only one gateway gets just 0.5 a second.

Failing closed means rejecting requests while the store is down. No request ever skips the limit, but a store outage rejects every request on that endpoint.

I would use local limits for the general API and fail closed for login, which is why each rule carries its own on_store_down setting.

Combining per-IP, per-key and per-account rules

A single request can match several rules at once, for example one for its IP address, one for its API key and one for the endpoint. The gateway allows the request only if every rule allows it, and returns the longest Retry-After among the rules that rejected it. It checks the IP rule first, so a flood is rejected before it costs a second store call.

An IP address is a poor identity on its own, because an office or a mobile carrier can put thousands of users behind one address. Use the IP address for anonymous traffic and floods, and switch to the key or account as soon as it is known. The login endpoint needs two limits: one per IP address, which stops one attacker trying many accounts, and one per target account, which stops many addresses trying one account.

Bottlenecks and failures

At 10 times the traffic, the peak is 360,000 requests a second and the store sees 720,000 operations a second. At about 50,000 operations per shard that needs 16 shards, and a key that moves to a new shard simply starts as a full bucket.

The first thing that breaks is usually a hot key. One abusive client sending 50,000 requests a second puts every check on a single shard. A deny cache handles this: once a key has been rejected, the gateway remembers it for the 0.1 s until its next token arrives and rejects that key's requests from memory without calling the store.

A large customer allowed 20,000 requests a second is a harder hot key, because the deny cache does not help when requests pass. Each gateway can instead take tokens from the store in batches of 50 and spend them locally, which cuts the store calls by a factor of 50.

When this failsWhat happensWhat you do
A gateway nodeThe requests it was handling fail.The load balancer removes it from rotation. Counters are shared, so no counts are lost.
A counter shard's primaryIts keys time out for a few seconds until the replica is promoted.Each rule's on_store_down setting applies. Replication is asynchronous, so a few extra requests may pass once.
The whole counter storeThere are no shared counts.Most rules use local limits and login fails closed. An alert pages the on-call engineer.
The rules storeRules cannot be changed.Gateways keep enforcing the last rules they loaded.
The network to the store is slowChecks exceed the 2 ms budget.A 5 ms timeout sends the request to the fallback, and repeated timeouts make the gateway skip that shard for a few seconds.

What a strong answer sounds like

LevelWhat the answer does
JuniorDescribes one algorithm in one process, and needs a hint that separate gateway counts multiply the limit.
MidUses a shared counter store with an atomic check, returns 429 with Retry-After, and estimates the load on the store.
SeniorChooses the algorithm and the failure behaviour for each rule, uses the store's clock, avoids retrying a timed-out take, handles hot keys, and says what each endpoint does when the store is down.
Defending the failure modeStrong answer
Interviewer

Your counter store is down. What happens to the login endpoint?

You

Login fails closed. Without a limit an attacker can try passwords as fast as we answer, and a few minutes of failed logins is the smaller harm. The rest of the API falls back to local limits, so it stays up.

Interviewer

Isn't rejecting every login a bad experience for real users?

You

It is, so I would soften it. During the outage each gateway applies a strict local limit, for example 1 attempt per IP address per minute. Real users can still log in slowly, and an attacker gets almost nothing.

Follow-up questions

How do you limit across several regions?

A store shared between regions would add tens of milliseconds to every request, which breaks the 2 ms budget. Instead, give each region its own counters and divide each client's limit between regions in proportion to its traffic.

Why not put the limit in the load balancer?

Many load balancers can limit requests per IP address, and that is a good first layer against floods. They do not know the API key, the plan or the endpoint rules, though, so they cannot enforce the per-customer limits. Use both.

How do you charge more for expensive requests?

Give each endpoint a cost, for example 1 token for a read and 10 for an export, and pass it as the cost argument to the atomic take. A request whose cost exceeds the tokens left is rejected, and Retry-After says how long until enough tokens have refilled.

How do you roll out a new or stricter rule safely?

Run the rule in shadow mode first, where the gateway evaluates it and records what it would have rejected but allows the request anyway. Once the logged rejections look right, for example that they hit only abusive clients, switch the rule to enforcing.

Self-review: rate limiter0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure