- #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 buttonon 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
whileloop. 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.
requests
200 OK
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?
- 01
Request arrives
GET /quotes
- 02
Find the key
API key, user ID or IP
- 03
Check its count
window, log, or bucket
- 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.
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 rejectThe famous flaw is the boundary. Fire the burst below, then switch to the sliding log to see the fix.
Minute 1 5/5
Minute 2 5/5
resets
10 allowed in a few seconds Each minute only ever counted 5, so twice the limit got through.
2. Sliding window log
Instead of counting per block, remember the timestamp of every accepted request.
- 01
Request at 10:00:40
look up this key's log
- 02
Drop old stamps
anything before 09:59:40
- 03
Count what's left
stamps in the last 60 s
- 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.
// 15 s into the current minute, the previous minute still overlaps by 45 s (75%).const estimate = previousCount * 0.75 + currentCount;return estimate < LIMIT;Previous minute 9
Current minute 4
Estimate (two counters)9 × 0.75 + 4 = 10.8 ≥ 10: next request gets 429
Exact (sliding log)11 requests in the last 60 s
- 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.
requests
+2 tokens / sfull: extras spill
5.0 / 5tokens
- No requests yet. Press a button.
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.
requests
leaks 2 / s
0.0 / 5queued
- No requests yet. Press a button.
- 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 window | Sliding log | Sliding counter | Token bucket | Leaky bucket | |
|---|---|---|---|---|---|
| Remembers per key | One counter | A timestamp per accepted request | Two counters | Tokens left + last refill time | Queue level + last leak time |
| Accuracy | Leaks up to 2× at a boundary | Exact | Near-exact estimate | Exact for its rule | Exact for its rule |
| Bursts | Allowed, even double ones at the edge | Never above the limit | Never much above the limit | Up to the capacity, at once | Queued and smoothed out |
| Over the limit | 429 | 429 | 429 | 429 | Wait in the queue; 429 when it's full |
| Pick it when | You want the simplest thing, and edge bursts don't hurt | Limits are small and must be exact | You need it cheap at huge scale | You want a steady average but allow short bursts | The thing behind you needs a constant pace |
| Seen in this post | The two-command Redis version | — | Cloudflare | Stripe's per-user limiter | Shopify'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.
Things to try:
- Burst ×10 on a fresh start. The token bucket lets 5 through and turns 5 away.
- 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.
- Leaky bucket: Burst ×10. One goes straight through, four wait in the queue, five get 429.
- 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
Gateway / edge
Your service
- 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:
// 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:
- #1
- #2
- #3
- #4
- #5
- #6
- #7
- #8
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.
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
One shared counter
- Fixed window in Redis is two commands:
INCRthe 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
One Lua script in Redis
-- 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 0A shared limiter brings one more decision: what if Redis is down?
| Fail open | Fail closed | |
|---|---|---|
| When the limiter is down | Allow everything | Reject everything |
| You keep | Your API up | Your protection |
| You lose | Protection, until it's back | Availability, until it's back |
| Most teams use it for | General traffic | Expensive 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/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-Aftertells 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
| Approach | What it does | Like | Where it falls short |
|---|---|---|---|
| Just scale up | Autoscaling adds servers when load rises. Wonderful for genuine growth. | Building more turnstiles | It 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 everything | Nobody is turned away; requests wait their turn. | A line outside the club | If requests arrive faster than you serve them, the queue grows without end, waits grow, and requests time out anyway after using up memory. |
| Load shedding | Watches your own servers' health, not each client. When overloaded, drops the least important traffic first. | Triage in an emergency room | It can't tell a fair client from a greedy one. Use it with rate limits, not instead of them. |
| CAPTCHA / proof of work | Makes abuse expensive instead of counting requests. | A quiz at the door | Machine-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 cost | Gives each request a cost based on how much work it does, and limits the total. | Paying by weight at the post office | More 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):
Per client
Whole 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.
- 01
Query arrives
fields it asks for
- 02
Add up its cost
every field has a cost
- 03
Check the points bucket
before the query runs
- 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
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.
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.
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.
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.
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.
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.
- Wikipedia, "Leaky bucket" (opens in a new tab) (history, including Turner's 1986 description).
- M. Nottingham and R. Fielding, "RFC 6585: Additional HTTP Status Codes" (opens in a new tab), IETF, 2012 (429 Too Many Requests).
- IETF HTTPAPI working group, "RateLimit header fields for HTTP" (opens in a new tab) (Internet-Draft).
- Paul Tarjan, "Scaling your API with rate limiters" (opens in a new tab), Stripe, 2017.
- GitHub Docs, "Rate limits for the REST API" (opens in a new tab).
- Julien Desgats, "Counting things, a lot of different things…" (opens in a new tab), Cloudflare, 2017.
- Shopify, "REST Admin API rate limits" (opens in a new tab), and the Shopify Partners blog on rate limits (opens in a new tab).
- Shopify Engineering, "Rate limiting GraphQL APIs by calculating query complexity" (opens in a new tab).
- GitHub Docs, "Rate limits and node limits for the GraphQL API" (opens in a new tab).
- Zerodha, "Kite Connect API: exceptions and rate limits" (opens in a new tab).