Design a Rate Limiter: Algorithms, Redis and Failure Modes
Fixed window, sliding window and token bucket explained with their real weaknesses, plus how to make the limiter correct across many servers and what to do when Redis goes down.
A rate limiter controls how many requests a client is allowed to make in a given period of time. When an app tells you 'Too many attempts, try again after thirty minutes', a rate limiter has counted your requests and decided to block further ones. It protects services from abuse, brute-force attacks and accidental overload, and it keeps one heavy client from degrading the experience of everyone else.
These notes cover where a rate limiter sits, the three algorithms you are expected to know with their strengths and weaknesses, how to keep the limiter correct when it runs on many servers, and how it should behave when its own storage fails.
1. Clarify the requirements
- Functional: limit the number of requests a client can make in a time window, for example 100 requests per minute per user. Different endpoints can have different limits.
- Functional: when the limit is exceeded, reject the request with a clear response so the client knows when to retry.
- Non-functional: the check sits in front of every request, so it must add very little latency (a millisecond or two).
- Non-functional: it must be accurate in a distributed setup where requests from one user reach many servers.
- Non-functional: the limiter itself must not become a single point of failure.
- Questions to ask: what identifies a client (user ID, API key, IP address)? Is the limit hard or is a small overshoot acceptable?
2. Where does the limiter live?
The limiter should run before the request reaches your application servers, so that rejected traffic costs you almost nothing. The natural place is the API gateway, as middleware. Every request passes through it, it identifies the client, checks the counter, and either forwards the request or returns HTTP 429 (Too Many Requests).
A good 429 response tells the client what to do next.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1767225630
{ "error": "rate_limit_exceeded", "message": "Try again in 30 seconds." }3. Algorithm one: fixed window counter
Divide time into fixed windows, for example each calendar minute, and keep one counter per client per window. Each request increments the counter. If the counter exceeds the limit, reject.
It is simple and uses very little memory, but it has a well-known flaw called the boundary burst problem. With a limit of 100 per minute, a client can send 100 requests in the last second of one window and 100 more in the first second of the next. Each window is within its limit, yet the system received 200 requests in two seconds, double what you intended to allow.
4. Algorithm two: sliding window
Instead of calendar windows, look at the last 60 seconds from the moment of each request. The sliding window log stores the timestamp of every request (for example in a Redis sorted set), removes timestamps older than the window, and counts what remains. It is exact, but it stores one entry per request, which is expensive for high limits.
The sliding window counter is the practical compromise. Keep the counters for the current and the previous fixed window, and estimate the rolling count as: current count plus previous count multiplied by the fraction of the previous window that still overlaps. It uses two numbers per client and removes most of the boundary burst.
5. Algorithm three: token bucket
The token bucket is the most widely used algorithm. Each client has a bucket with a maximum capacity. Tokens are added at a fixed rate. Every request removes one token. If the bucket is empty, the request is rejected.
Two parameters give you precise control: the refill rate sets the long-term average, and the capacity sets how large a burst you tolerate. A real user who opens the app and fires ten requests at once is served, while the sustained rate stays bounded. You do not need a background job to add tokens; you compute the refill lazily from the time elapsed since the last request.
A related algorithm, the leaky bucket, puts requests in a queue and processes them at a constant rate. Token bucket allows bursts; leaky bucket smooths them out.
function allow(bucket, now, capacity, refillPerSec) {
// Add the tokens earned since the last request
const elapsed = (now - bucket.lastRefill) / 1000;
bucket.tokens = Math.min(capacity, bucket.tokens + elapsed * refillPerSec);
bucket.lastRefill = now;
if (bucket.tokens < 1) return false; // reject with 429
bucket.tokens -= 1;
return true;
}6. Distributed rate limiting with a shared store
If each gateway node keeps its own in-memory counter, a client whose requests are spread over ten nodes effectively gets ten times the limit. The state must be shared.
The standard answer is a centralized store, usually Redis, keyed by client and window. But 'read the counter, check it, then write it' is three steps, and two requests arriving together can both read 99 and both pass. This is a race condition. The fix is to make the operation atomic: either use the INCR command, which increments and returns the new value in one step, or run the whole token bucket calculation inside a Lua script, which Redis executes atomically. Set a TTL on every key so that counters for inactive clients disappear on their own.
# key = rate:{userId}:{currentMinute}
INCR rate:42:29453760 -> returns the new count
EXPIRE rate:42:29453760 60 NX -> set the TTL only on first use
# if the returned count > limit -> reject with 429Client --> Load balancer --> API gateway (rate limit middleware) --> Services
|
v
Redis cluster (counters / buckets)
^
Rules config (limits per endpoint, cached locally)7. Failure handling: fail-open and fail-closed
The limiter depends on Redis, so you must decide its behaviour when Redis is unreachable. There are two policies and the right one depends on the endpoint.
Fail-open means that if the limiter cannot decide, it allows the request. Use this for ordinary APIs: a short period without rate limiting is better than taking the whole product down. Fail-closed means that if the limiter cannot decide, it rejects the request. Use this for login, OTP verification and other security-sensitive endpoints, where allowing unlimited attempts is the worse outcome.
To reduce the chance of ever reaching that decision, run Redis with replicas and automatic failover, keep a short timeout on the limiter call, and optionally fall back to a coarse local in-memory limit per node.
8. Additional considerations
- Latency: one Redis round trip per request is usually acceptable. For very high throughput, nodes can take a batch of tokens locally and synchronise periodically, trading a little accuracy for speed.
- Multiple dimensions: apply limits per user, per IP and per endpoint together; the request passes only if all of them pass.
- Rules: store limits in configuration that the gateway caches and reloads, so limits can change without a deployment.
- Multi-region: either accept slightly loose limits with per-region counters, or replicate counters asynchronously. Strict global limits are expensive and rarely needed.
- Client behaviour: well-behaved clients read Retry-After and back off exponentially with jitter.
Interview summary
- Requirements: per-client limits, very low latency, correct in a distributed setup.
- Placement: middleware at the API gateway, before application servers.
- Algorithm: token bucket for burst tolerance, or sliding window counter for accuracy; mention the boundary burst of fixed windows.
- Storage: Redis with atomic operations (INCR or a Lua script) and a TTL on each key.
- Response and failure: HTTP 429 with Retry-After; fail-open for normal APIs, fail-closed for login and OTP.
Summary
A rate limiter counts requests per client and rejects the excess with a 429. Fixed windows are simple but allow bursts at the boundary, sliding windows fix that, and token buckets give you controlled bursts with a bounded average. In a distributed system the counter must live in a shared store and be updated atomically, and you must decide in advance whether each endpoint fails open or fails closed.
Puneet Tiwari
Full Stack Developer
