All posts
  • #apis
  • #reliability
  • #algorithms

Rate Limiting: The Bouncer, the Turnstile and the Leaky Bucket

Why every serious API limits requests, how fixed windows, sliding windows, token buckets and leaky buckets actually differ (with a live simulator), and how to do it across many servers with Redis. Case files from Stripe, GitHub, Cloudflare, Shopify and Zerodha.

Akshit Bansal22 min readPart 4

go on, spam the button
on this page

In one minute

  • A rate limiter checks every request against a limit, like "100 per minute per API key". Under the limit: let it in. Over: make it wait, or turn it away with 429 and a Retry-After.
  • It protects your servers, keeps things fair between customers, slows down abuse and caps what expensive requests cost you.
  • Five classic ways to count: fixed window (simple, leaks at the edges), sliding log (exact, memory-hungry), sliding counter (a cheap, near-exact estimate), token bucket (a steady average plus short bursts) and leaky bucket (a smooth, constant output).
  • On many servers the counters live in Redis and are updated atomically. Good clients back off with jitter. When requests differ hugely in size, limit by cost, not by count.

Words you need

  • API

    The doorway other code uses to talk to your servers. A program sends a request and gets a response back.

    Like the order counter at a restaurant

  • Client

    Whatever is calling your API: an app, a script, another company's server.

    Like a customer at the counter

  • Request and status code

    One call to the API. The response starts with a number saying how it went: 200 means OK, 202 means accepted for later.

    Like an order slip, and the 'done' or 'later' stamp it comes back with

  • Header

    A labelled extra line sent along with a request or response, such as Retry-After: 2.

    Like a sticky note on the parcel

  • Endpoint

    One address in an API that does one job, such as 'get a quote' or 'place an order'.

    Like one window at the post office: stamps, parcels, passports

  • Rate limit (quota)

    How many requests a client may make in a period, such as 100 per minute.

    Like a daily cash limit on your bank card

  • Window

    The period the limit counts over, such as one minute.

    Like the 'per day' in 'two coffees per day'

  • Burst

    Many requests close together. A page loading 10 things at once is a small, normal burst.

    Like a whole train's worth of people reaching the gates at once

  • Key

    Who is being counted: a user ID, an API key, an IP address, or a mix.

    Like the name on the guest list

  • 429 Too Many Requests

    The standard status code for 'you are over the limit'.

    Like a 'full, come back later' sign on the door

  • Retry-After

    A header on the 429 saying how many seconds to wait before trying again.

    Like the 'next train in 2 min' display

  • Token

    A permission slip. A token bucket hands them out at a steady rate; each request spends one.

    Like a metro token for the turnstile

  • Queue

    Requests waiting their turn, served in order.

    Like the line at a ticket window

  • Noisy neighbour

    One customer using so much capacity that everyone else slows down.

    Like a flatmate who uses all the hot water

  • Concurrent requests

    Requests that have started and not finished yet, all at the same moment.

    Like people inside the shop right now, not people per hour

  • Backoff and jitter

    After each failure, wait longer before retrying (1 s, 2 s, 4 s), plus a small random extra so clients don't all retry at the same instant.

    Like calling a busy shop back later each time, at a slightly random minute

  • API gateway / edge

    A front-door server, or a CDN (a network of servers close to users), that every request passes through before your service.

    Like the security desk in the lobby

  • Redis

    A very fast in-memory data store that all your servers can share.

    Like one whiteboard the whole office reads and writes

  • Atomic (Lua script)

    Done as one step that nothing can interrupt halfway. A small Lua script runs inside Redis this way.

    Like a bank transfer: both sides happen, or neither does

  • Fail open / fail closed

    What to do when the limiter itself is down: let everything through (open) or block everything (closed).

    Like a broken turnstile left open, or locked shut

  • Load shedding

    When your servers are overloaded, dropping the least important traffic first, no matter who sent it.

    Like triage in an emergency room

  • Autoscaling

    Adding servers automatically when load rises.

    Like opening more checkout lanes when the queue grows

  • CAPTCHA / proof of work

    A test that is easy for a person but tedious for a bot, or a puzzle a computer must spend time solving before it is let in.

    Like a quiz at the door

  • GraphQL and query cost

    GraphQL is an API style where one query names exactly the fields it wants, so one query can ask for one field or ten thousand. Query cost is a score for how much work a query takes.

    Like paying by parcel weight, not per parcel

Why every API needs a limiter

Now the API version:

  • One customer ships a script with a bug in a while loop. It calls your API a few thousand times a second.
  • Your servers slow down, then fall over, and every other customer goes down with them.
  • That runaway script is the 9 a.m. crowd, and you have no turnstiles.
A rate limiter at the door: a steady share of requests get in (green), the extras are turned away with a 429 (red), and the server stays healthy. Hover to pause the stream.

Four reasons to limit, and most APIs care about all of them:

  • Protection

    Your servers have a maximum safe load. A limit stops any single client, buggy or malicious, from pushing you past it.

  • Fairness

    Without limits, the noisiest customer gets the most capacity. With limits, everyone gets a fair share, and the noisy neighbour can't crowd anyone out.

  • Abuse prevention

    Limits slow down password guessing on login pages, scraping, spam and fake sign-ups.

  • Cost

    Some requests cost real money: sending an SMS with a one-time password, calling a paid AI model, running a heavy report. A limit caps the bill.

How a limiter decides

Every rate limiter answers one question, many thousands of times a second: a request from this key just arrived; let it in or not?

  1. 01

    Request arrives

    GET /quotes

  2. 02

    Find the key

    API key, user ID or IP

  3. 03

    Check its count

    window, log, or bucket

  4. 04

    Decide

    200 · queue · 429 + Retry-After

The five classic algorithms differ only in step 3: what they remember, and how they count.

1. Fixed window counter

  • Count requests per key in fixed blocks of time: 10:00–10:01, 10:01–10:02, and so on.
  • Under the limit: allow the request and add one. When a new block starts, reset to zero.
  • Tiny, fast and easy to understand.
ts
const windowStart = Math.floor(now / 60_000);        // which minute is it?const count = (counters.get(key + windowStart) ?? 0) + 1;counters.set(key + windowStart, count);return count <= LIMIT;                                // allow or reject

The famous flaw is the boundary. Fire the burst below, then switch to the sliding log to see the fix.

Count with

10 allowed in a few seconds Each minute only ever counted 5, so twice the limit got through.

Limit: 5 per minute. Five requests at the end of minute 1 and five at the start of minute 2. Each fixed window only ever counts 5, so all 10 get in within a few seconds: twice the limit. A sliding frame can't be fooled.

2. Sliding window log

Instead of counting per block, remember the timestamp of every accepted request.

  1. 01

    Request at 10:00:40

    look up this key's log

  2. 02

    Drop old stamps

    anything before 09:59:40

  3. 03

    Count what's left

    stamps in the last 60 s

  4. 04

    Under the limit?

    yes: allow and log the stamp

  • Exact. The window slides with time, so there is no boundary trick.
  • Memory-hungry. With a limit of 10,000 requests per hour, you might store 10,000 timestamps for each key. Across millions of users, that adds up.

3. Sliding window counter

A clever compromise: keep just two counters per key, this window and the previous one. Then estimate the last full window by weighting the previous window by how much of it the frame still covers.

ts
// 15 s into the current minute, the previous minute still overlaps by 45 s (75%).const estimate = previousCount * 0.75 + currentCount;return estimate < LIMIT;

Estimate (two counters)9 × 0.75 + 4 = 10.8 ≥ 10: next request gets 429

Exact (sliding log)11 requests in the last 60 s

Limit: 10 per minute. The amber frame is the last 60 seconds. The estimate assumes the previous minute's requests were spread evenly, so it multiplies their count by the overlap. Drag the slider and compare it with the exact count.
  • It assumes the previous window's requests were spread evenly. That is rarely exactly true, but close enough at scale.
  • Cloudflare uses this approach, and found the estimate wrong for only a tiny fraction of requests (case file #3).

Quick check: Your API allows 100 requests per minute, counted in fixed windows. What's the most one client can get through in the two seconds around 10:01:00?

4. Token bucket

A tap refills a bucket with tokens at a steady rate, say 2 per second, up to a maximum of 5. Every request must take one token. No token, no entry, until the tap drips in another.

InteractiveToken bucket
try Burst ×8
  • No requests yet. Press a button.

Refills 2 tokens a second, holds 5. A full bucket lets a burst of 5 straight through; after that, requests only get in as fast as tokens drip in. When the bucket is full, new drips spill away.

Two knobs, and that's its superpower:

  • The refill rate sets the long-run average (2 per second).
  • The capacity sets how big a burst you tolerate (5 at once).
  • A page that fires 5 requests on load sails through. A script trying 50 per second is cut down to 2.

5. Leaky bucket

The leaky bucket flips the picture. Requests pour into a bucket (a queue) and leak out of the bottom at a fixed rate.

InteractiveLeaky bucket
try Burst ×8
  • No requests yet. Press a button.

Holds 5, leaks 2 a second. A burst waits in the bucket (202, with its wait time) and drains at a steady pace. Only when the bucket is full do extras get 429.
  • A burst isn't served instantly. It is smoothed out into a steady stream.
  • That is exactly what you want when the thing behind the limiter (a database, a payment network, an SMS provider) can only handle a constant pace.
  • The bucket has a maximum size. Without one, the queue would grow without end.
  • Shopify's REST Admin API is a real leaky bucket (case file #4).

Quick check: A token bucket refills 2 tokens a second and holds 5. A client has been quiet for a minute, then fires 8 requests at once. What happens?

The five side by side

Fixed windowSliding logSliding counterToken bucketLeaky bucket
Remembers per keyOne counterA timestamp per accepted requestTwo countersTokens left + last refill timeQueue level + last leak time
AccuracyLeaks up to 2× at a boundaryExactNear-exact estimateExact for its ruleExact for its rule
BurstsAllowed, even double ones at the edgeNever above the limitNever much above the limitUp to the capacity, at onceQueued and smoothed out
Over the limit429429429429Wait in the queue; 429 when it's full
Pick it whenYou want the simplest thing, and edge bursts don't hurtLimits are small and must be exactYou need it cheap at huge scaleYou want a steady average but allow short burstsThe thing behind you needs a constant pace
Seen in this postThe two-command Redis version—CloudflareStripe's per-user limiterShopify's REST Admin API

Try them all

Both limiters below allow 2 requests per second on average, with bursts of up to 5. Every request goes to both at the same moment.

InteractiveRate limiter simulator
spam the button!
loading the demo…
Token bucket on the left, the algorithm you pick on the right. Each timeline shows the last 8 seconds, with now on the right.

Things to try:

  1. Burst ×10 on a fresh start. The token bucket lets 5 through and turns 5 away.
  2. Fixed window: press Burst ×10, then press it again as soon as a new dashed line reaches "now". Ten get through in quick succession, double the burst.
  3. Leaky bucket: Burst ×10. One goes straight through, four wait in the queue, five get 429.
  4. Steady traffic at 4 a second. Every limiter settles at about 2 a second; watch how the sliding counter tracks the sliding log.

Where should the limit live?

You can limit in three places, and real systems usually use all three.

Client

Polite retriesrespects Retry-After, backs off with jitter

Gateway / edge

Cheap, early stoprejects floods before they reach your servers

Your service

Business-aware limits'send OTP' is expensive; this user is on the free plan
Each layer stops a different kind of excess. The client slows itself down, the edge drops floods cheaply, and the service applies limits that need business knowledge.
  • Client-side. Doesn't protect you from bad clients, but makes good ones much easier to live with.
  • At the gateway or edge. The cheapest place to stop a flood (more in the traffic patterns post).
  • In the service. Only the service knows what a request means, so fine-grained limits live here.

A polite client, in code:

ts
// Polite client: respect Retry-After, otherwise back off exponentially with jitter.async function callWithRetry(request: () => Promise<Response>, attempt = 0): Promise<Response> {  const response = await request();  if (response.status !== 429 || attempt >= 5) return response;  const retryAfter = Number(response.headers.get("Retry-After"));  const backoff = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 500;  await new Promise((resolve) => setTimeout(resolve, backoff + Math.random() * 250));  return callWithRetry(request, attempt + 1);}

Why the random extra matters:

Retry with

8 retries in the same 20 ms Every client waits exactly as long as the others, so they all hit the server together, four times over.

Eight clients get a 429 at the same moment and retry with the backoff above. Without jitter they come back in lockstep, as one wave each time. With up to 250 ms of random extra per retry, the waves break up. Hover to pause the playhead.

Many servers, one limit (Redis)

Your API runs on 20 servers behind a load balancer. If each server counts in its own memory, a client can get 20 times the limit by spreading its requests around.

Each server counts alone

Server 1this key: 100 / 100
Server 2this key: 100 / 100
… Server 20this key: 100 / 100
The client got2,000 a minute

One shared counter

Servers 1 to 20all ask the same place
Redisthis key: 100 / 100, then 429
Counters in each server's memory multiply the limit. One shared counter in Redis enforces it once.
  • Fixed window in Redis is two commands: INCR the key's counter, and set it to expire at the end of the window.
  • A token bucket needs read, refill, take a token, write back. Two servers doing that at the same moment can race:

Without atomic updates

Server A reads1 token left
Server B reads1 token left
2 requests in on 1 tokenthe limit quietly leaks

One Lua script in Redis

Read, refill, take, writeone step nobody can interrupt
A gets the token, B gets 429exactly as the rule says
Read-then-write from two servers lets two requests spend one token. Running the whole update as one Lua script inside Redis makes it atomic.
lua
-- KEYS[1] = bucket key; ARGV = capacity, refill per second, now (seconds)local bucket = redis.call("HMGET", KEYS[1], "tokens", "ts")local capacity, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])local tokens = tonumber(bucket[1]) or capacitylocal last = tonumber(bucket[2]) or nowtokens = math.min(capacity, tokens + (now - last) * rate)local allowed = tokens >= 1if allowed then tokens = tokens - 1 endredis.call("HSET", KEYS[1], "tokens", tokens, "ts", now)redis.call("EXPIRE", KEYS[1], math.ceil(capacity / rate) * 2)return allowed and 1 or 0

A shared limiter brings one more decision: what if Redis is down?

Fail openFail closed
When the limiter is downAllow everythingReject everything
You keepYour API upYour protection
You loseProtection, until it's backAvailability, until it's back
Most teams use it forGeneral trafficExpensive or security-sensitive actions, like login

Quick check: Your API runs on 20 servers. Each keeps its own in-memory counter: 100 requests per minute per key. A client spreads its requests across all of them. Roughly how many can it make per minute?

Saying "slow down" politely

A good rejection is specific and useful:

http
HTTP/1.1 429 Too Many RequestsRetry-After: 2Content-Type: application/json{ "error": "rate_limited", "message": "Too many requests. Try again in 2 seconds." }
  • Say when. Retry-After tells well-behaved clients exactly how long to wait.
  • Say how much is left. Many APIs also send headers on every response, such as requests remaining and when the quota resets, so clients slow down before they hit the wall. GitHub does this (case file #2).

Other ways to handle too much traffic

ApproachWhat it doesLikeWhere it falls short
Just scale upAutoscaling adds servers when load rises. Wonderful for genuine growth.Building more turnstilesIt doesn't stop abuse, it bills you for it. A runaway script grows with your capacity, and autoscaling takes minutes while a flood takes seconds.
Queue everythingNobody is turned away; requests wait their turn.A line outside the clubIf requests arrive faster than you serve them, the queue grows without end, waits grow, and requests time out anyway after using up memory.
Load sheddingWatches your own servers' health, not each client. When overloaded, drops the least important traffic first.Triage in an emergency roomIt can't tell a fair client from a greedy one. Use it with rate limits, not instead of them.
CAPTCHA / proof of workMakes abuse expensive instead of counting requests.A quiz at the doorMachine-to-machine traffic can't solve puzzles, and people hate them. A tool for sign-up and login pages, not a general limiter.
Charge by costGives each request a cost based on how much work it does, and limits the total.Paying by weight at the post officeMore work to build and to explain. Worth it when request sizes vary wildly.

Limit clients AND shed load

Stripe runs both, as four layers (case file #1):

Incoming API requestfor example, creating a charge

Per client

Request-rate limitera token bucket per user
Concurrent-requests limitercaps requests in flight, protects expensive endpoints

Whole fleet

Fleet-usage load shedderreserves capacity for critical requests
Worker-utilisation load shedderdrops low-priority traffic, the last line of defence
Your API serverscritical traffic has room reserved; all four limiters are backed by Redis
Stripe's four limiters, as described in its engineering post. The first two look at each client; the last two look at the health of the fleet.

When requests differ in size, count cost

Counting requests treats a tiny lookup and a giant query the same. For GraphQL, where one query can ask for one field or ten thousand, that's a poor fit.

  1. 01

    Query arrives

    fields it asks for

  2. 02

    Add up its cost

    every field has a cost

  3. 03

    Check the points bucket

    before the query runs

  4. 04

    Bucket refills

    points come back over time

  • Shopify limits its GraphQL Admin API by calculated query cost (case file #4).
  • GitHub's GraphQL API also uses a points-based limit instead of a plain request count.
  • Fairer and better at protecting the servers when request sizes vary wildly; harder to build and to explain.

In the wild: case files

Case file #01

Stripe

Startup turned big tech · 2017

four layers of no

The problem
Stripe's API handles payments, so availability is everything. Traffic spikes, misbehaving scripts, and floods of low-priority requests could crowd out critical ones like creating charges.
The fix
Stripe's engineering post describes four limiters working together: a request-rate limiter (token bucket per user), a concurrent-requests limiter that caps in-flight requests to protect expensive endpoints, a fleet-usage load shedder that reserves capacity for critical requests, and a worker-utilisation load shedder that drops low-priority traffic as a last line of defence. They're backed by Redis.
The lesson
Limits are layered. Per-user rate limits handle unfair clients; load shedders protect the fleet when everyone at once is too much. And critical traffic should have capacity reserved for it.
Source: Stripe: Scaling your API with rate limiters(opens in a new tab)
Case file #02

GitHub

Big tech · ongoing

tell people their quota

The problem
GitHub's API is used by millions of scripts, CI systems and apps. Unauthenticated scrapers and buggy integrations could easily overwhelm it.
The fix
GitHub's REST API documents a primary limit of 60 requests per hour for unauthenticated requests and 5,000 per hour for authenticated users, with higher limits for some apps. On top of that, it enforces secondary limits to prevent abuse, such as a cap on concurrent requests, and reports usage in response headers.
The lesson
Make the anonymous path tight and the identified path generous: it nudges people to authenticate, which makes abuse traceable. And publish the limits and remaining quota so clients can behave.
Source: GitHub Docs: Rate limits for the REST API(opens in a new tab)
Case file #03

Cloudflare

Big tech (network) · 2017

approximate, but at planet scale

The problem
Cloudflare wanted to offer rate limiting to every customer, enforced at its edge data centres around the world. A client's requests can be spread across many servers, so per-server counters in memory don't see the full picture, and storing a timestamp for every request is too expensive at that scale.
The fix
Cloudflare described sharing counters between servers within each data centre and using the sliding-window-counter approximation: two counters per key, with the previous window weighted by its overlap. It reported that in an analysis of 400 million requests, only 0.003% were wrongly allowed or rate limited compared with an exact sliding window.
The lesson
Exactness is expensive. A cheap approximation that's almost always right can beat a perfect algorithm you can't afford to run.
Source: Cloudflare: Counting things, a lot of different things(opens in a new tab)
Case file #04

Shopify

Big tech (e-commerce) · ongoing

a real leaky bucket

The problem
Thousands of third-party apps call Shopify's Admin API for millions of stores. Apps naturally make bursts of requests (syncing a catalogue, say), but the platform needs a steady, fair load.
The fix
Shopify's REST Admin API uses a leaky bucket: on standard plans, each app gets a bucket of 40 requests per store that drains at 2 requests per second (higher on Shopify Plus). For its GraphQL Admin API, Shopify moved to calculated query costs, limiting points instead of request counts.
The lesson
The bucket size allows natural bursts; the leak rate guarantees a sustainable average. And when requests vary hugely in cost, count cost, not requests.
Source: Shopify Engineering: Rate limiting GraphQL APIs(opens in a new tab)
Case file #05

Zerodha (Kite Connect)

Indian fintech · ongoing

different limits for different doors

The problem
Zerodha's Kite Connect API lets traders and developers build their own trading tools, including automated strategies. Market data and order endpoints are hit by bots that could easily flood the system during market hours.
The fix
Kite Connect sets limits per endpoint: about 1 request per second for live quotes, 3 per second for historical candle data, and 10 per second for most other endpoints, with additional caps on order placement. Requests over the limit get HTTP 429.
The lesson
Limits should match the cost and risk of each endpoint. Heavy data endpoints and order placement need tighter controls than cheap lookups.
Source: Kite Connect docs: exceptions and rate limits(opens in a new tab)

Learn next and sources

  • Next ideas: load shedding and backpressure; circuit breakers; API gateways and edge rules (see the traffic patterns post); the IETF RateLimit headers draft (source 3).
  • Skip for now: building your own distributed limiter from scratch. Use your gateway's or a well-known library's, and spend the time choosing the key and the numbers.
  1. Wikipedia, "Leaky bucket" (opens in a new tab) (history, including Turner's 1986 description).
  2. M. Nottingham and R. Fielding, "RFC 6585: Additional HTTP Status Codes" (opens in a new tab), IETF, 2012 (429 Too Many Requests).
  3. IETF HTTPAPI working group, "RateLimit header fields for HTTP" (opens in a new tab) (Internet-Draft).
  4. Paul Tarjan, "Scaling your API with rate limiters" (opens in a new tab), Stripe, 2017.
  5. GitHub Docs, "Rate limits for the REST API" (opens in a new tab).
  6. Julien Desgats, "Counting things, a lot of different things…" (opens in a new tab), Cloudflare, 2017.
  7. Shopify, "REST Admin API rate limits" (opens in a new tab), and the Shopify Partners blog on rate limits (opens in a new tab).
  8. Shopify Engineering, "Rate limiting GraphQL APIs by calculating query complexity" (opens in a new tab).
  9. GitHub Docs, "Rate limits and node limits for the GraphQL API" (opens in a new tab).
  10. Zerodha, "Kite Connect API: exceptions and rate limits" (opens in a new tab).