Stage 2 · Building blocks · Medium · 20 min

Rate limiting

Cap how many requests each caller can send, so one client cannot overload the service. Compare token bucket, leaky bucket, fixed window and sliding window.

What each interview level is expected to know

Learn first: Reverse proxies and API gateways

After this lesson you can:

  • Compare token bucket, leaky bucket, fixed window and sliding window counters.
  • Pick the algorithm that allows short bursts but holds a steady average.
  • Decide what the limiter does when its own counter store fails.

Start here

See it in 60 seconds

How a token bucket says no

A request passes only if it takes a token from a bucket that refills at a steady rate, so bursts pass but floods do not.

Scene 1 of 6 · A bucket of tokens

The rate limiter keeps a bucket of 10 tokens for each client, and the bucket starts full.

One clientOne clientRate limiterRate limiterbucket: 10 tokensAPIAPI
  • One client — healthy
  • Rate limiter — healthy — bucket: 10 tokens
  • API — healthy
Tokens in the bucket
10
Passed
0
Answered 429
0
  1. A bucket of tokens. The rate limiter keeps a bucket of 10 tokens for each client, and the bucket starts full.
  2. Each request takes one. Each request takes one token from the bucket, then goes on to the API.
  3. A burst empties it. 9 more requests arrive at once and take the other 9 tokens, so the bucket is now empty.
  4. Empty means 429. Request 11 finds no token, so the limiter answers 429 Too Many Requests straight away.
  5. Tokens drip back. Tokens drip back at 10 a second, one every 100 ms, so 500 ms later there are 5 again.
  6. Bursts yes, floods no. A quiet client can send a short burst, but no client gets more than 10 a second for long.
  7. Now you try. A client sends 10 requests at once, waits, then sends 10 more. How long does it wait? For example: After 400 ms, 4 tokens came back, so 4 of the next 10 pass and 6 get 429. Tokens come back one every 100 ms, whatever the client does, so waiting is the only way to get more.

Scene 1 of 6: A bucket of tokens. The rate limiter keeps a bucket of 10 tokens for each client, and the bucket starts full.

Key points

  1. Each client gets a bucket of 10 tokens; every request that passes takes one.
  2. An empty bucket means the limiter answers 429 Too Many Requests at once, without calling the API.
  3. Tokens come back at a steady rate, here 10 a second, up to the bucket's size.
  4. A full bucket allows a short burst, while the refill rate caps what a client gets over time.

Go deeper in the Rate limiting lab →

In plain words

Say your API allows each customer 100 requests a minute. One customer's script goes wrong and sends 5,000. A rate limiter counts the requests from each caller. It lets the first 100 through and rejects the rest with 429, which means "too many requests". The reply can say when to try again, so a well-behaved client waits.

Where the limiter sits matters. It usually runs in the gateway, before a request reaches your services. With several gateway servers, the counts must live in a shared store such as , or each server allows its own 100. Limits can differ by caller, so a paying customer might get a higher one. The counting method matters too: a fixed clock minute can let a burst of 200 through across the edge between two minutes.

The problem it solves

A service has a fixed capacity, and every caller shares it. If one caller takes too much, the others get slow answers or errors. The limit check also runs on every request, so it must be fast: a millisecond or two, not a slow lookup.

Why it matters

One buggy script or bot can send 100,000 requests a second to an open API. With no limit, that traffic slows the service for every other user and can run up a large cloud bill. A rate limiter rejects the extra requests before they reach your servers.

A worked example

A free-tier limit of 100 requests per minute allows one request roughly every 60 ÷ 100 = 0.6 seconds on average. A client that sends 250 requests in one minute gets 100 of them through. The other 250 − 100 = 150 requests are rejected until the next minute's allowance resets.

Think of it like…

Think of the light at the entrance to a motorway. It lets one car join every few seconds, however long the line behind it. The road does not jam.

Where this analogy stops working

A cap on how fast traffic may enter is the useful part. But the light makes cars wait, and nobody is turned away. Most rate limiters do not hold a request. They reject it with an error, and the caller must try again later. Each caller also has its own count.

Try it

See it working

Live simulationOpen the full lab →

Lab · Traffic

Rate limiting

A rate limiter decides, per client, whether a request may go through or gets a 429 Too Many Requests. All five algorithms here enforce the same policy — compare how they handle bursts and window edges.

Try it

Lab time 3.0 s
Client (one API key), 3 req/sClient (one API key)3 req/sRate limiter, Token bucketRate limiterToken bucket6.9 / 10 tokensAPI service, 10 per 5 s allowedAPI service10 per 5 s allowed8 handled
About each part:
  • Client (one API key) — 3 req/s — healthy
  • Rate limiter — Token bucket — healthy — 6.9 / 10 tokens
  • API service — 10 per 5 s allowed — healthy — 8 handled
  • Request
  • Error / rejected
  • Response
Requests
8
Allowed
8
Rejected (429)
0
0% of all
Most in any 5 s
8/ 10
forwarded to the API

Numbers add up:8 requests = 8 allowed + 0 rejectedThe lab checks this sum as it runs, so a counting mistake would show here.

Controls

Algorithm

A bucket holds up to L tokens and refills at L/W per second. Each request spends one token.

Tokens left6.9 / 10 tokens
Policy
10 requests
5 s

Same policy for every algorithm: on average 2.0 requests per second.

Traffic
3 req/s

Timeline

Requests over the last 15 s
AllowedRejected (429)Last 5 s
0snow (3s)

What just happened

  1. 0.0sInfo: Policy: at most 10 requests per 5 s using Token bucket.
What this model simplifies
  • One client and one limiter. Real limiters keep a counter per user, IP or API key, usually in a shared store such as Redis so every gateway instance sees the same count.
  • Checking and updating the counter is atomic here. In a distributed limiter you need an atomic operation (e.g. a Lua script or INCR with expiry) or two gateways can both let the last request through.
  • Rejected requests are simply dropped with a 429. Good APIs also return a Retry-After header so clients back off.

Mechanics

How it works

Every rate limiter answers one question for each request: has this caller used up its share? The four algorithms below answer it in different ways. Each picture follows one client, the rate limiter and the API behind it.

  1. Token bucket

    Pick a case to follow below

    With this case: 10 of the 15 passed at once, because the bucket was full. After that, the client gets one request through every 100 ms, which is 10 a second.

    Client, one callerClientone callerRate limiter, counts each caller, NOWRate limitercounts each caller10 tokensNOWAPI, does the workAPIdoes the work
    • Client — one caller — healthy
    • Rate limiter — counts each caller — healthy — NOW — 10 tokens
    • API — does the work — healthy
    • Requests
    • Rejected: 429
    Step 1 of 5

    Step 1 of 5 · Rate limiter

    Done: An idle client sends 15 requests at once

    What happens
    The client sent nothing for a while, so the bucket is full: 10 tokens. Now 15 requests arrive together.
    Why
    A bucket fills up while its caller is quiet, but never past its size.
    What changes
    There are tokens for 10 of the 15 requests.
    Next
    10 requests take a token each and pass
    Tokens in the bucket
    10of 10
    one added every 100 ms
    Passed
    0
    Rejected (429)
    0
    passed + rejected = 15 sent

    Step 1 of 5: Rate limiter. An idle client sends 15 requests at once. The client sent nothing for a while, so the bucket is full: 10 tokens. Now 15 requests arrive together.

    Picture a bucket that holds up to 10 tokens and gains a new token every 100 ms, so 10 each second. Each request takes one token. A request that finds the bucket empty is rejected with HTTP 429, which means too many requests.

    Pick the first case. An idle client sends 15 requests at once. The bucket is full, so 10 pass straight away and 5 are rejected. After that, one request can pass each time a token is added.

    So a allows a short burst, up to the bucket's size, but holds the long-run rate to the refill rate. In the second case, the client sends one request every 100 ms, the same speed as the refill, and nothing is rejected.

    It needs only two numbers per caller: the tokens left and the time of the last refill. That makes it cheap, and it is a common choice for public APIs.

    Best for: APIs where a short burst is fine, such as a page that loads 10 things at once, but a steady flood is not.

  2. Leaky bucket

    Client, one callerClientone callerRate limiter, counts each caller, NOWRate limitercounts each callerqueue 5 of 5NOWAPI, does the workAPIdoes the work
    • Client — one caller — healthy
    • Rate limiter — counts each caller — healthy — NOW — queue 5 of 5
    • API — does the work — healthy
    • Requests
    • Rejected: 429
    Step 1 of 4

    Step 1 of 4 · Rate limiter

    Done: 8 requests arrive at once

    What happens
    The limiter puts requests in a queue that holds 5. 5 of the 8 fit.
    Why
    A leaky bucket does not pass a burst on. It makes the burst wait its turn.
    What changes
    The queue is full. 3 requests have no place.
    Next
    3 requests are rejected: the queue is full
    In the queue
    5of 5
    Watch: full
    Longest wait so far
    0ms
    Passed
    0
    Rejected (429)
    0
    passed + rejected = 8 sent

    Step 1 of 4: Rate limiter. 8 requests arrive at once. The limiter puts requests in a queue that holds 5. 5 of the 8 fit.

    Requests join a , and the limiter sends them on at a fixed rate, one every 200 ms here. In the picture, 8 requests arrive at once, and the queue holds 5 requests.

    The 5 that fit wait their turn, and the other 3 are rejected. The API then gets one request every 200 ms, never the burst.

    The cost is waiting. The last request in the queue waits 1,000 ms before it reaches the API. A longer queue rejects fewer requests, but makes each one wait longer.

    Best for: Work that must reach a slow system at an even pace, such as calls to a payment partner that allows 5 a second.

  3. Fixed window counter

    Pick a case to follow below

    With this case: 200 requests passed in 2 seconds, twice the limit. Each burst fell in a different window, so neither one was over its own limit.

    Client, one callerClientone callerRate limiter, counts each callerRate limitercounts each caller12:00: 100 of 100API, does the work, NOWAPIdoes the workNOW
    • Client — one caller — healthy
    • Rate limiter — counts each caller — healthy — 12:00: 100 of 100
    • API — does the work — healthy — NOW
    • Requests
    Step 1 of 3

    Step 1 of 3 · API

    Done: At 12:00:59, 100 requests arrive and all pass

    What happens
    The 12:00 window had 0 requests, so all 100 fit under the limit of 100.
    Why
    The limiter only asks one question: is this window's count over the limit?
    What changes
    The 12:00 window now counts 100.
    Next
    At 12:01:00, a new window starts at 0
    Window
    12:00
    one clock minute
    Count in this window
    100of 100
    Watch: at the limit
    Passed
    100
    Rejected (429)
    0
    passed + rejected = 100 sent

    Step 1 of 3: API. At 12:00:59, 100 requests arrive and all pass. The 12:00 window had 0 requests, so all 100 fit under the limit of 100.

    Count each caller's requests in each clock minute, and reject any above the limit, such as 100. It is the easiest to build: one counter per caller per minute.

    The first case shows its weak spot. 100 requests arrive at 12:00:59 and fit the 12:00 window. At 12:01:00 the count starts again at 0, so 100 more pass. That is 200 in two seconds, twice the limit.

    Inside one window the count works, as the second case shows. Once 100 have passed, the rest of that minute is rejected.

    Best for: Rough limits where a double burst at the window's edge does no harm, such as a daily quota.

  4. Sliding window counter

    Client, one callerClientone callerRate limiter, counts each callerRate limitercounts each callerestimate 100API, does the work, NOWAPIdoes the workNOW
    • Client — one caller — healthy
    • Rate limiter — counts each caller — healthy — estimate 100
    • API — does the work — healthy — NOW
    • Requests
    • Rejected: 429
    Step 1 of 3

    Step 1 of 3 · API

    Done: At 12:00:59, 100 requests arrive and all pass

    What happens
    Nothing came earlier, so all 100 fit under the limit of 100.
    Why
    The limiter keeps two counts: this minute and the minute before.
    What changes
    The 12:00 minute counts 100.
    Next
    At 12:01:00, 100 more arrive and are rejected
    Previous minute
    0
    This minute
    100
    Estimate
    100of 100
    Watch: 100 this minute
    Passed
    100
    Rejected (429)
    0
    passed + rejected = 100 sent

    Step 1 of 3: API. At 12:00:59, 100 requests arrive and all pass. Nothing came earlier, so all 100 fit under the limit of 100.

    What these pictures simplify. Each picture follows one caller, and requests that arrive together are counted in one step. A real limiter counts every caller at once, often in a shared store such as Redis, so all the API servers see the same counts. The Rate limiter lab above runs many callers together.

    This fixes the edge problem by blending two windows. Say the limit is 100 and you are 30 seconds into the current minute. The estimate is the current count plus half of the previous minute's count. If that total is over 100, the request is rejected.

    Step through the same bursts as before. At 12:01:00 the new minute has only begun, so all of the previous minute still counts. The estimate is already 100, and the burst is rejected.

    At 12:01:30, half of the previous minute counts, so the estimate is 50, and 50 more requests pass.

    The estimate assumes the previous minute's requests were spread evenly. Here they all came at 12:00:59, so 150 passed in the real last 60 seconds, not 100. That is close enough for most limits, and it needs only two counters per caller. An exact count would have to store the time of every request.

    Best for: Per-minute API limits where the edge burst of a is not acceptable.

The four algorithms side by side
AlgorithmA burstStored per callerWeak spot
Token bucketAllowed, up to the bucket sizeTokens left and the last refill timeA full bucket lets a burst through at once
Leaky bucketWaits in the queueA queue of waiting requestsRequests wait, and a full queue rejects
Fixed windowAllowed, even twice the limit at the minute markOne counterThe edge of the window
Sliding windowLimited across the minute markTwo countersAn estimate, not an exact count

In code: a token bucket

function makeBucket(capacity, refillPerSec) {  let tokens = capacity  let last = 0 // time of the last refill, in ms  return function allow(nowMs) {    tokens = Math.min(capacity, tokens + ((nowMs - last) / 1000) * refillPerSec)    last = nowMs    if (tokens < 1) return false // over the limit: answer 429    tokens -= 1    return true  }}
  • The bucket starts full. Each request takes one token, and tokens come back at a steady rate.
  • With capacity 10 and 5 tokens a second, a caller can send 10 requests at once, then about 5 a second.
  • This keeps the count in one process. Several servers that share a limit keep it in a shared store such as Redis.

Use it when

  • Public APIs and login pages, to slow down abuse such as password guessing and scraping.
  • Paid plans with different limits, such as 100 requests an hour when free and 10,000 a second for large customers.
  • Protecting a slower service behind you from more traffic than it can take.

Skip it when

  • Calls between functions inside one program: there is no network and no untrusted caller to limit.
  • As the only defence against a very large attack: block that traffic at the network edge, before it reaches your limiter.

Check yourself

A token bucket holds 10 tokens and refills 1 a second. An idle client sends 15 requests at once. How many pass?

Judgement

Trade-offs and how it fails

What you give up

Accuracy
A log stores the time of every request, so it is exact but uses a lot of memory. A sliding window counter stores two numbers per caller and is close enough for most uses.
Latency
A shared counter in Redis adds a network round trip to every request, often 1–2 ms. Keeping part of the count on each server is faster, but less exact.

Failure modes

  • A race on the counter: two requests read the count as 99, both pass, and both add one. Make the check and the add a single step in Redis, for example with a Lua script.
  • The limiter's store goes down. Fail open and all traffic passes with no limit. Fail closed and every request is rejected. Decide which before it happens.

In the real world

  • Stripe's engineering blog (2017) describes the token bucket rate limiters, built on Redis, that protect its API. Source: Stripe blog: rate limiters (2017) (checked 14 October 2026)
  • Twitter's public API answers HTTP 429 when a caller is over its limit, with headers that say when the limit resets.

Trade-offs to be ready to discuss: Sliding window vs token bucket

Check yourself

Why does a rate limiter on many gateway copies often keep its counts in Redis?

Interview

What interviewers look for

  • Pick one and say why: "Token bucket, because it is small to store and allows short bursts while holding the long-run rate."
  • Mention the race on a shared counter, and fix it by making the check and the add one step in Redis.
  • Say what happens when the limiter itself fails: fail open or fail closed, and why.

Say it out loud: What goes wrong at the edge of a fixed window, with a limit of 100 requests a minute?

Which algorithm lets a short burst through, but still holds callers to a steady average rate?

Expected depth by interview level

Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.

JuniorExpected
Why and where to limit requests.
MidCore
Token bucket vs fixed and sliding windows; 429 responses.
SeniorCore
Shared counters in Redis, accuracy vs cost, per-tenant limits.
StaffExpected
Limits as fairness and cost control across a platform.

Practice

Apply it

Three harder questions

The first two use the idea on a new case. The last asks you to judge a design.

Apply it

A fixed window allows 100 requests per clock minute. A client sends 100 requests at 12:00:59 and 100 more at 12:01:00. How many pass?

Apply it

A sliding window counter allows 100 a minute. The previous minute had 80 requests. You are 45 seconds into this minute, with 75 so far. Does the next request pass?

Judge a design

Two gateway copies share a count in Redis. Each one reads the count, and if it is under the limit, adds one in a second step. What breaks, and what fixes it?

Next: caching, which answers repeated reads from memory so the database does less work.

Go deeper

Sources and further reading

First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.