Rate limiting: token bucket, fixed and sliding windows
How an API decides that a client is asking too much, the three classic algorithms, and where the limiter lives in a real system.
In one sentence
A rate limiter caps how many requests a client can make in a period ("100 per minute") and answers the rest with 429 Too Many Requests, so one client can't take the system down for everyone.
Why limit requests?
- Protect the system: a buggy script in a loop, a scraper or an attack shouldn't eat all your capacity.
- Fairness: every customer gets their share, especially in multi-tenant SaaS.
- Cost control: calls to paid APIs (SMS, AI models, maps) cost money per request.
- Security: slow down password guessing and enumeration on login or reset endpoints.
The limit is applied per key: user ID, API key, IP address, or a combination ("5 login attempts per account and per IP every 15 minutes").
The algorithms, side by side
| Algorithm | How it works | Good | Watch out |
|---|---|---|---|
| Token bucket | A bucket of N tokens refills at a fixed rate; each request spends one | Allows short bursts, smooth on average. The most common choice (AWS, Stripe) | Two numbers to tune: size and refill rate |
| Fixed window | Count per clock minute (or second) and reset | Trivial: one counter with an expiry in Redis | Bursts at the boundary can let through 2× the limit |
| Sliding window | Count requests in the last N seconds from now | Accurate at any moment | Needs timestamps, or an approximation from two windows |
| Leaky bucket | Requests queue and leave at a constant rate | Perfectly smooth output | Adds waiting instead of rejecting |
Where the limiter lives
With one server, a counter in memory is enough. With twenty servers behind a load balancer, each one only sees part of the traffic, so the counters must be shared: usually in Redis, with an atomic increment and an expiry.
// fixed window in Redis: one key per user per minute
const key = `rl:${userId}:${Math.floor(Date.now() / 60_000)}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, 60);
if (count > 100) return new Response("Too many requests", { status: 429, headers: { "Retry-After": "60" } });In practice you stack several layers: the CDN or WAF blocks abusive IPs at the edge, the API gateway applies per-key limits, and expensive endpoints add their own.
Being a good citizen
- Answer with 429 and a
Retry-Afterheader, never a generic 500. - Expose the remaining quota (
RateLimit-Remaining) so clients can slow down before hitting the wall. - Decide what happens if Redis is down: fail open (let traffic through) for normal APIs, fail closed for login.
- Clients should retry with exponential backoff and jitter, not immediately.
Key takeaways
- 01Rate limiting protects capacity, fairness, cost and security by capping requests per key.
- 02Token bucket allows short bursts and is the usual default; fixed windows are simplest but leak at the edges.
- 03With many servers, keep the counters in a shared store like Redis.
- 04Reply 429 with Retry-After, and let clients back off.
Check your understanding
1 of 3
What does a rate limiter answer when a client exceeds the limit?
Related concepts
API gateway
An API gateway is one entry point for all your APIs. It handles the cross-cutting work (TLS, authentication, rate limiting, routing, logging) once, so each service only does its own job.
5 min read →Load balancers
A load balancer is the single entry point that receives every request and forwards it to one of many healthy servers, so no single server is overloaded and failures stay invisible to users.
8 min read →Caching
A cache stores copies of data that are expensive to get (slow query, far away server) so the next request can be answered from somewhere fast and close.
9 min read →