Skip to content

Rate limiting explained: token bucket, leaky bucket, fixed and sliding windows, 429 and Redis limits

The four rate limiting algorithms, animated, how to answer with 429 and Retry-After, what GitHub, Stripe, AWS and OpenAI publish and why the counter has to be shared across servers.

Ramon Gomes 15 min read Level: Intermediate

Also available in: Español, Français, Português

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.

Subway station turnstiles at rush hour, with people going through one at a time and a line forming behind them
The turnstile doesn't stop anyone from getting in. It sets the pace.

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.

Three buckets show a reserve of 5 tokens, a burst that empties the balance and causes 429, and a refill of one token every 2 seconds that allows requests through to the API again. Each request consumes one token.
The burst goes through as long as there are saved tokens. After that, the pace is the refill rate.

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.

Irregularly spaced requests arrive from the client at a funnel with a queue capacity of 5. A red branch indicates drops when the queue is full; output to the server runs at one request every 1.6 seconds.
In at the client's pace, out at the server's pace.

It's the algorithm behind NGINX's limit_req:

nginx
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.

Animation of a timeline split into 60 second blocks; a hundred requests arrive at 59 seconds and another hundred at 61 seconds; a highlight shows 200 requests in 2 seconds, all accepted
Within each window, all good. Add up both edges and you get double.

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.

text
rate = 42 × (45 / 60) + 18 = 49.5   → still allowed
Two cards show 42 requests in the previous minute and 18 in the current minute. The last-60-seconds ruler leaves 75% of the previous minute in the count at 15 seconds into the current minute: 42 × 0.75 + 18 = 49.5, below the limit of 50.
The previous minute only counts for the part still inside the window.

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
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:

http
RateLimit-Policy: padrao;q=100;w=60
RateLimit: padrao;a=42;w=18

The 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.

Two panels compare the Redis counter. Without atomicity, A and B read balance 1 and allow two requests with one token. With atomic Lua, A is allowed and B receives balance zero and 429.
Separate reads and writes let two requests spend the same token.

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:

lua
local atual = redis.call("incr", KEYS[1])
if atual == 1 then
    redis.call("expire", KEYS[1], 60)
end
return atual

Figma 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.

Two panels show four homes sharing public IP 200.10.0.1. With a per-IP limit, abuse by home 3 blocks all of them. With a per-user limit, only home 3 is blocked and the others receive a check mark.
By IP, the whole building pays. By user, only the abuser does.

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

ts
// 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,
}));
csharp
// 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).

Cartoon of a building doorman shutting the gate on every resident because of a single noisy one, while the others stand outside holding grocery bags
Limiting by IP is sometimes this.

Quick check

1. Which algorithm lets up to twice the limit through at the interval boundary?
Show answer

Answer: Fixed window

The client spends everything at the end of one window and everything again at the start of the next.

2. Three instances with an in memory limit of 100 per minute let how much through in total?
Show answer

Answer: Up to 300

Each instance counts on its own. For the limit to hold overall, the counter has to be shared.

3. What code does NGINX return by default when limit_req rejects a request?
Show answer

Answer: 503

You have to set limit_req_status 429; to change it.

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:

Source: https://ramongomessilva.com.br/blog/rate-limiting-explained · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. Rate limiting explained: token bucket, leaky bucket, fixed and sliding windows, 429 and Redis limits. Ramon Gomes, 28 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/rate-limiting-explained. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 28). Rate limiting explained: token bucket, leaky bucket, fixed and sliding windows, 429 and Redis limits. Ramon Gomes. https://ramongomessilva.com.br/blog/rate-limiting-explained

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026ratelimitingexplained,
  author = {Gomes, Ramon},
  title = {{Rate limiting explained: token bucket, leaky bucket, fixed and sliding windows, 429 and Redis limits}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-28},
  url = {https://ramongomessilva.com.br/blog/rate-limiting-explained},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles