Rate limiting
A rate limit says no early and cheaply, so one noisy client cannot take your service down for everyone else.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
This story is made up, but it is common. A small company sells a public API for sending text messages. Most customers send a few requests a second.
One Monday, a new customer starts a data import. Their script has a bug: when a request is slow, it retries at once, in a loop, with no wait. Soon this one customer sends 3,000 requests a second.
The API servers pass every request to the database. The database slows down, so requests get slower. Slower requests make the script retry even more.
Within ten minutes, every customer sees timeouts. The team blocks the customer by hand, and things recover. Then the next question comes: "Why could one customer do this at all?"
There was no rate limit. The service said yes to every request until it could not say anything.
The idea in simple words
A rate limit is a rule like "each API key may make 100 requests a minute". The service counts requests. When a client goes over the limit, the service rejects the extra requests at once, before doing any real work.
A rate limit protects you in three ways:
- Safety. One client, a bug or an attack cannot use all your capacity.
- Fairness. Every customer gets their share.
- Cost. You do not pay for work that nobody planned for.
The key idea. A fast, cheap "no" is better than a slow "yes" that ends in a timeout. Rejecting early keeps the service healthy for everyone else.
How it works
Token bucket
Picture a bucket of tokens for each client. Each request takes one token. Tokens drip back in at a fixed rate, up to the size of the bucket. If the bucket is empty, the request is rejected.
Two numbers set the rule. The bucket size sets the biggest burst. The refill rate sets the average. Stripe uses a token bucket for its main limiter, with the buckets stored in Redis. 1
Step through a burst. Use Next and Back, or the ← and → keys.
- Each API key has its own bucket. It holds at most 5 tokens, and it gets 1 new token every second. At the start it is full.
- A burst of 7 requests arrives at once. Each request takes one token. Requests 1 to 5 get a token and go through. Now the bucket is empty.
- Requests 6 and 7 find no token. The server answers at once with 429 Too Many Requests and Retry-After: 1, meaning: try again in 1 second.
- One second later, one token has been added. Request 8 takes it and goes through. The bucket is empty again.
- The client goes quiet for 6 seconds. The bucket refills, but it stops at 5 tokens. So a client can send a burst of up to 5, but on average only 1 request a second.
Now try it yourself. Change the bucket size and refill rate, then send a burst.
Try it: send a burst into a token bucket
Leaky bucket
A leaky bucket smooths traffic instead of allowing bursts. Requests join a queue, and the queue drains at a fixed rate. When the queue is full, new requests are rejected.
NGINX's limit_req module uses this method. With rate=1r/s burst=5, NGINX lets through 1 request a second on average. Up to 5 extra requests wait in line, and more than that get an error. With nodelay, the queued requests are not delayed. By default the error is 503, but you can change it with limit_req_status. 5 Set it to 429, so clients know they hit a limit.
Fixed window
Count requests per client per minute. The key could be user42:12:01. When the minute ends, start a new counter.
In Redis this is a few lines: INCR the key and set it to expire. 6 It is cheap and easy to explain to customers.
But the edges are weak. With a limit of 100 a minute, a client can send 100 requests at 12:00:59 and 100 more at 12:01:00. That is 200 requests in two seconds.
Sliding window
A sliding window log stores the time of every request. To decide, it counts the times in the last 60 seconds. It is exact, but it stores one entry per request, which uses a lot of memory for busy clients.
A sliding window counter keeps only two counters: this minute and last minute. It guesses the rate by weighting last minute's count by how much of it is still inside the window.
Cloudflare gives an example. The limit is 50 a minute. Last minute had 42 requests, and this minute has 18 so far, 15 seconds in. The estimate is 42 × 0.75 + 18 = 49.5, just under the limit. 2 It is only an estimate. But on 400 million requests, Cloudflare found just 0.003% were wrongly allowed or wrongly limited. 2
Limits across many servers
If each server counts in its own memory, the limit multiplies. With 20 servers and a limit of 100, a user can make up to 2,000 requests.
So most teams keep counters in a shared store like Redis. Be careful with races. If you INCR a key and set its expiry in a separate step, a crash between them can leave the key with no expiry. Redis suggests MULTI/EXEC or a small Lua script, so both happen together. 6
A shared store adds a network call to every request, so it can become a bottleneck. Envoy's answer is a separate rate limit service, plus a local token bucket on each proxy. Its reference service uses Redis. The local limit absorbs large bursts and cuts the load on the shared service. 7
What if the limiter itself fails, because of a bug or because Redis goes down? Stripe's advice is to fail open: catch errors at all levels and let the request through. 1 The limiter should never become the outage.
Where to enforce it
- At the edge or API gateway. Reject by IP address or API key before any real work. This is cheap and stops floods early.
- In the service. The service knows the user, their plan and how costly each call is. A search can cost much more than a read by ID.
Our advice is to use both: a coarse limit at the gateway and finer limits in the service.
Per-user and global limits
A per-user limit keeps things fair. A global limit protects a shared resource, such as the database, whoever the traffic comes from.
Stripe runs four kinds. A request rate limiter caps each user's requests per second. A concurrent requests limiter caps how many requests can run at once, such as 20. Two load shedders protect the whole system: one keeps capacity for critical requests, and the other sheds traffic when workers are overloaded. 1
Telling the client
The HTTP status for this is 429 Too Many Requests. The response may include a Retry-After header that says how long to wait. 3 Retry-After can be a number of seconds, like Retry-After: 120, or a date. 4
Tell clients their budget too. GitHub's REST API sends headers like x-ratelimit-remaining and x-ratelimit-reset. A logged-in user gets 5,000 requests an hour. 8 After a primary limit, GitHub says to wait until the reset time. After a secondary limit, wait for retry-after if sent. Otherwise wait for the reset time, or at least one minute. 8
Trade-offs
| Algorithm | Allows bursts? | Memory per client | Accuracy | Use it when |
|---|---|---|---|---|
| Token bucket | Yes , up to the bucket size. | Two numbers. | Good. | Most APIs. Clients are bursty but you want a fair average. |
| Leaky bucket | No Output is smooth. | A queue. | Good. | You must protect a backend that needs a steady rate. |
| Fixed window | Yes , up to 2x at window edges. | One counter. | Weak at the edges. | Simple limits, like daily quotas. |
| Sliding window log | Up to the limit, never more in any window. | One entry per request. | Exact. | Low limits where exactness matters, like login attempts. |
| Sliding window counter | Up to about the limit. | Two counters. | Close estimate. | High traffic, many clients. |
Our simple rule: use a token bucket per API key in a shared store, plus a coarse limit at the gateway.
At work: how a senior uses this
- Ask about every public endpoint: "What stops one client from using all of it?"
- Choose the key with care: API key, user, account or IP address. Many users can share one office IP address.
- Dark launch a new limit first. Log who would be blocked, then turn it on. Stripe does this, and adds a kill switch. 1
- Put limits in your API docs. Send 429 with
Retry-After, and headers that show what is left. - Alert when limits fire a lot. It can mean an attack, a client bug or a limit that is too low.
- Treat limiting a customer as a product decision, with an owner and a clear process. In 2023, an unapproved throttle applied by hand made one Cloudflare customer's site unusable. It stayed on for almost 13 hours. Afterwards, Cloudflare said such actions would need several levels of approval. 9 See the incident.
- Check your own clients: they should back off with jitter, not retry in a loop.
With AI
What to ask the agent
"Add a token bucket rate limiter to this API, per API key, stored in Redis. Use a Lua script so the check and the update happen together. Return 429 with Retry-After."
"Write tests for the limiter: a burst up to the bucket size passes, the next request gets 429, and one request passes after one refill interval."
"Make the limiter fail open if Redis is down or slow for more than 20 ms. Log and count every fail-open."
What to check yourself
- The read and the update of the counter happen in one atomic step, not two.
- Every Redis key has an expiry, so idle clients do not fill memory.
- The limit key is right: per API key, not per server, and not shared by accident.
- Retry-After is in seconds and matches when a token will really be free.
- The agent did not use the server's local clock in a way that breaks across many servers.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 9 sources and related lessons
- Paul Tarjan, “Scaling your API with rate limiters”, Stripe blog, 2017 (opens in a new tab)
Stripe's four limiters, the token bucket in Redis, and how to roll out limits safely. - Cloudflare, “How we built rate limiting capable of scaling to millions of domains”, Cloudflare blog, 2017 (opens in a new tab)
The sliding window counter, with a worked example and accuracy measured on real traffic. - Nottingham and Fielding, RFC 6585: Additional HTTP Status Codes (IETF, 2012), section 4 (opens in a new tab)
The definition of 429 Too Many Requests. - Fielding, Nottingham and Reschke, RFC 9110: HTTP Semantics (IETF, 2022), section 10.2.3 (opens in a new tab)
The Retry-After header and its two formats. - NGINX documentation, “Module ngx_http_limit_req_module” (opens in a new tab)
A real leaky bucket limiter, with burst, nodelay and the status code it returns. - Redis documentation, “INCR”, section “Pattern: rate limiter” (opens in a new tab)
Two counter-based limiters in Redis, and the race condition to avoid. - Envoy proxy documentation, “Global rate limiting” (opens in a new tab)
A shared rate limit service backed by Redis, and why to add a local limit in front of it. - GitHub Docs, “Rate limits for the REST API” (opens in a new tab)
A public API's limits, headers and advice for clients that hit them. - Cloudflare, “How Cloudflare erroneously throttled a customer’s web traffic”, Cloudflare blog, 2023 (opens in a new tab)
A manual throttle that made one customer's site unusable, and the process fixes that followed.
Real incident: Cloudflare, 2 Feb 2023: Cloudflare wrongly throttled one customer's traffic
Case studies: Shopify: Surviving flash sales with a checkout queue at the load balancer · Stripe: Two rate limiters and two load shedders that protect an API
Related: API gateways and edge concerns · Load shedding and graceful degradation · Backoff, jitter and retry budgets · Redis in depth · Abuse prevention at scale (coming soon) · Circuit breakers, bulkheads and fallbacks
Related lessons: API gateways, Load shedding, Backoff and jitter and Redis in depth.