Every public API will meet, sooner or later, a client that sends way too many requests. Sometimes it's an attack. Almost always it's a script with while (true), an app with a loop bug or an integration that retries without waiting. With no limit, one client like that takes the service down for everyone else.
This article explains the algorithms with animations, shows what the big APIs do (GitHub, Stripe, AWS, OpenAI), and gets into the details that break real implementations: the race condition in Redis, the wrong trust proxy and the shared IP. I checked everything against the official sources on November 21, 2026.
It continues the "Traffic" topic from the API concepts guide and ties into the resilience patterns, because whoever gets a 429 needs to know how to retry the right way.

Rate Limiting, Throttling, Quota and Backpressure
The terms get mixed up, and every vendor uses them differently. It's worth knowing the differences:
| Term | What it is | Example |
|---|---|---|
| Rate limiting | A cap on requests per interval, per client | 100 per minute per user |
| Throttling | Server side load control, which can reject, queue or degrade | Skip the expensive part of the response under load |
| Quota | A usage cap over a long period, almost always tied to the plan | 10,000 calls per month |
| Concurrency limit | How many requests can be in flight at the same time | 20 concurrent |
| Backpressure | The overloaded component tells whoever is upstream to slow down | The queue consumer asks for fewer messages |
Microsoft, in the Azure Architecture Center, uses "throttling" for the server side and "rate limiting" for the client controlling its own pace. NGINX, Express and ASP.NET call the server side rate limiting. There's no standard; what matters is being clear about what your system does.
Stripe says it uses four different limiters: a per user request rate (the most important one), concurrent requests, a capacity reserve for critical operations and a last line of defense that sheds traffic when the workers are maxed out.
Token Bucket: The Bucket of Tokens
It's the most widely used algorithm. Stripe uses it, AWS API Gateway uses it, Envoy uses it.
Each client has a bucket with a maximum number of tokens. Tokens drip in at a fixed rate, and each request spends one. Empty bucket, request rejected.
The nice part is the burst: a client that sat idle for a while builds up tokens and can make several calls at once. That matches real usage, where a screen opens and fires five calls together.
Two numbers define the bucket. In AWS API Gateway they're called rate (tokens per second) and burst (bucket size). The default limit per account and region is 10,000 requests per second with a burst of 5,000. AWS itself warns that these limits are "targets", applied on a best effort basis, not a guaranteed ceiling.
Leaky Bucket: The Funnel
The leaky bucket is a bucket with a hole: water comes in at whatever pace, but always drips out at the same rate. Fill it too much and it overflows.
It's the algorithm behind NGINX's limit_req:
http {
limit_req_zone $binary_remote_addr zone=uma:10m rate=1r/s;
server {
location /busca/ {
limit_req zone=uma burst=5;
}
}
}burst=5 creates a queue of five: the excess waits its turn instead of being rejected. With nodelay, whatever fits in the burst goes through right away. One gotcha: NGINX responds with 503 by default, not 429. To change it, use limit_req_status 429;.
The practical difference from the token bucket: the leaky bucket delivers a constant output, good for protecting a back end that can't handle spikes. The token bucket accepts the spike if there's balance left.
Fixed Window and the Boundary Problem
The fixed window is the simplest to implement: one counter per client per minute (or hour). Over 100, reject until the minute is up.
The problem is at the boundary. The Figma team put it this way: the scheme can let twice the allowed amount through. The client spends 100 in the last seconds of one minute and another 100 in the first seconds of the next.
Another effect: if everyone resets at the same time, everyone comes back at the same time. Upstash calls this a "stampede" at the start of each window.
Sliding Window: Looking Back from Now
The sliding window asks "how many requests in the last 60 seconds?" instead of "in this clock minute?". There are two ways to do it:
- Log: stores the timestamp of each request. It's exact, but expensive in memory. Figma estimated about 20 MB for 10,000 users making 500 requests a day.
- Counter: stores only the previous minute's counter and the current one, and weights the previous one by the part that still fits in the window.
Cloudflare explained the counter with an example worth memorizing: a limit of 50 per minute, we're 15 seconds into the current minute, there were 42 requests in the previous minute and 18 in the current one.
rate = 42 × (45 / 60) + 18 = 49.5 → still allowed
It looks too approximate, but Cloudflare measured it over 400 million requests: 0.003% were wrongly allowed or blocked. That's why it's the pick for a lot of people who want fairness without paying for the log.
The Four Side by Side
| Algorithm | Burst | Memory per client | Weak spot | Who uses it |
|---|---|---|---|---|
| Token bucket | Accepts, up to the bucket size | 2 numbers | Needs an atomic operation | Stripe, AWS, Envoy, Bucket4j |
| Leaky bucket | Queues or rejects | Queue | Can delay legitimate requests | NGINX |
| Fixed window | Up to double at the boundary | 1 counter | Window edge | express-rate-limit, Redis INCR |
| Sliding window (counter) | Smoothed | 2 counters | It's an approximation | Cloudflare, Upstash |
There's also GCRA, a leaky bucket variant that comes from ATM networks and stores a single theoretical time per client. It shows up in libraries that want precision with little state; Brandur Leach's post in the references explains it well.
Responding Properly: 429 and Retry-After
The right code is 429 Too Many Requests, from RFC 6585. Along with it, send the Retry-After header with the seconds to wait:
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/problem+json
{ "title": "Rate limit reached", "detail": "Try again in 30 seconds." }Two details from the RFC: it doesn't define how to identify the client or how to count, and a 429 response must not be cached.
To tell the client how much balance it has left, there's an IETF draft, "RateLimit header fields for HTTP", which reached version 12 on November 20, 2026 and isn't an RFC yet. It defines two headers:
RateLimit-Policy: padrao;q=100;w=60
RateLimit: padrao;a=42;w=18The first describes the policy (100 every 60 seconds). The second describes the current state: the a parameter says how many requests are still available (42). Libraries track different versions of the draft, so check which one yours generates. Many APIs still use the old X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers, like GitHub.
On the caller's side, the rule is the same as in the resilience article: treat Retry-After as the minimum wait, add some random jitter and, without the header, use exponential backoff. OpenAI points out that rejected requests also count toward the limit, and GitHub warns that continuing to hit the API after the limit can get the integration banned.
What the Big APIs Publish
| API | Published limit | Note |
|---|---|---|
| GitHub REST | 60 per hour unauthenticated (per IP); 5,000 per hour authenticated | Secondary limits: 100 concurrent, points per minute (GET costs 1, writes cost 5) |
| AWS API Gateway | 10,000 per second, burst of 5,000, per account and region | Token bucket, "best effort" |
| OpenAI | By requests and by tokens, per minute and per day | Varies by model and account tier |
| Stripe | Per user token bucket and concurrency limit | Uses 429 or 503 depending on the case |
Look at GitHub: a write costs five times more than a read. Giving each operation a different cost is one of the most useful ideas in this whole topic, and Microsoft recommends the same.
Multiple Servers: The Counter Has to Be Shared
With a single server, an in memory counter does the job. With three behind a load balancer, each one counts on its own. The ASP.NET Core documentation does the math: 100 per minute across three instances lets up to 300 through.
The usual fix is to keep the counter in Redis. And here's the trap: read, decide and write have to be a single operation.
The INCR command page itself shows the problem in a fixed window pattern: if the client runs INCR and crashes before EXPIRE, the key never expires and the client stays blocked forever. The official fix is a Lua script, which Redis runs atomically:
local atual = redis.call("incr", KEYS[1])
if atual == 1 then
redis.call("expire", KEYS[1], 60)
end
return atualFigma reported the same race in a token bucket: two requests read the same balance and both go through. Mature libraries already handle this, which is why it's worth using one instead of writing it from scratch.
What if Redis goes down? Stripe's answer: fail open. The limiter catches any error and lets the request through, because the limiter can't be the reason the API goes down. Stripe also turns on each new limit in log only mode first, to see who would be blocked before blocking anyone.
The Limit Key: IP, User or API Key
Limiting by IP feels natural and it's the default in almost every library. It has three problems:
1. Shared IP. Mobile carriers and many ISPs put hundreds of customers behind the same IP (CGNAT). Cloudflare measured in 2025 that IPs like these get rate limited three times more than others. Blocking the IP punishes everyone because of one person.
2. IPv6. Each client usually gets a whole range of addresses and can switch addresses at will to dodge the limit. That's why express-rate-limit, since version 8, groups IPv6 by /56 range.
3. Reverse proxy. Behind NGINX, Cloudflare or a load balancer, the IP that arrives is the proxy's. If the app doesn't read X-Forwarded-For, everyone lands in the same bucket. If it reads it carelessly, an attacker writes whatever IP they want in that header.
The rule of thumb: by user or by API key when there's a login; by IP (with the proxy configured and IPv6 grouped) only for anonymous routes, like login and sign up. And never partition by a value the client controls freely: the ASP.NET docs warn that each new key creates a counter in memory, and an attacker can exhaust memory by sending different keys.
At the Gateway or in the App?
Both, with different roles. Microsoft sums it up well: DDoS protection doesn't stop a legitimate user from overloading the service, and application throttling can't withstand a volumetric attack.
- At the edge (CDN, WAF, gateway): stops raw volume and abuse by IP, before spending the app's CPU. "Make rejection cheaper than the work it avoids."
- In the app: uses business context the edge doesn't have: user, plan, cost of each operation.
In Practice, in Each Stack
// Node + Express (express-rate-limit 8.7)
import { rateLimit } from 'express-rate-limit';
app.set('trust proxy', 1); // one proxy in front; never true
app.use('/api', rateLimit({
windowMs: 60 * 1000,
limit: 100,
standardHeaders: 'draft-8',
legacyHeaders: false,
ipv6Subnet: 56,
}));// ASP.NET Core (built in since .NET 7)
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
o.AddTokenBucketLimiter("api", t =>
{
t.TokenLimit = 100;
t.TokensPerPeriod = 20;
t.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
});
});Other options I checked: rate-limiter-flexible 11.5 (Node, with Redis, Postgres and others), @fastify/rate-limit 11.3, @upstash/ratelimit 2.2 (serverless), slowapi 0.1.10 (FastAPI, still flagged as alpha) and Bucket4j 8.22 (Java, token bucket with several backends).

Quick check
Frequently Asked Questions
Which algorithm should I pick?
Token bucket for most APIs, because it accepts the natural burstiness of real usage. Sliding window if fairness is what matters and there are no bursts. Leaky bucket to protect a back end that needs a steady input.
429 or 503?
429 when the client went over its own limit. 503 when the whole service can't keep up right now, no matter who's calling.
Do I need Redis?
Only with more than one instance. With one, memory is enough. On serverless, a managed Redis or the gateway's own limit.
Does rate limiting replace authentication?
No. And AWS warns: an API key used for quotas is not authentication.
How do I test it?
With a test that fires N+1 requests and checks for the 429 and the Retry-After. For distributed limits, an integration test with a real Redis, as I show in the back end testing article.
References
Checked on November 21, 2026:
- IETF, RFC 6585, section 4: 429 Too Many Requests, RFC 9110: Retry-After and the draft RateLimit header fields for HTTP, version 12
- Microsoft, Throttling pattern, Rate limiting pattern and rate limiting in ASP.NET Core
- Stripe, Scaling your API with rate limiters, 2017
- Figma, An alternative approach to rate limiting, 2017
- Cloudflare, Counting things, a lot of different things and Detecting CGN to reduce collateral damage, 2025
- Brandur Leach, Rate limiting, cells, and GCRA, 2015
- NGINX, ngx_http_limit_req_module
- AWS, API Gateway throttling and quotas
- Envoy, local rate limit
- Redis, rate limiter and INCR
- GitHub, REST API rate limits; OpenAI, rate limits
- express-rate-limit, rate-limiter-flexible, @fastify/rate-limit, Upstash ratelimit, slowapi, Bucket4j