Rate Limiting
Why and where to rate limit, the main algorithms (token bucket, leaky bucket, fixed and sliding windows) with code, distributed rate limiting with Redis, and how to communicate limits.
Rate limiting caps how many requests a client can make in a period. It protects services from abuse and accidental overload (a buggy client in a retry loop), keeps usage fair between tenants, controls costs, and blunts brute-force and scraping attacks.
Where to limit
- Edge / API gateway — per IP, API key or user, before traffic reaches your services.
- Per service — protect expensive endpoints (search, login, exports).
- Outbound — respect third-party limits when calling others.
- Per key — the limit key can be IP, user ID, API key, tenant, or a combination (user + endpoint).
Algorithms
Token bucket (most common)
A bucket holds up to B tokens and refills at r tokens per second. Each request takes a token; with no tokens left, it's rejected. It allows bursts up to B while enforcing an average rate r.
class TokenBucket {
private final double capacity, refillPerSec;
private double tokens;
private long last = System.nanoTime();
TokenBucket(double capacity, double refillPerSec) {
this.capacity = capacity; this.refillPerSec = refillPerSec; this.tokens = capacity;
}
synchronized boolean tryAcquire() {
long now = System.nanoTime();
tokens = Math.min(capacity, tokens + (now - last) / 1e9 * refillPerSec); // lazy refill
last = now;
if (tokens < 1) return false;
tokens -= 1;
return true;
}
}import time, threading
class TokenBucket:
def __init__(self, capacity: float, refill_per_sec: float):
self.capacity, self.rate = capacity, refill_per_sec
self.tokens, self.last = capacity, time.monotonic()
self.lock = threading.Lock()
def try_acquire(self) -> bool:
with self.lock:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens < 1:
return False
self.tokens -= 1
return Trueclass TokenBucket {
private tokens: number;
private last = performance.now();
constructor(private capacity: number, private refillPerSec: number) {
this.tokens = capacity;
}
tryAcquire(): boolean {
const now = performance.now();
this.tokens = Math.min(this.capacity, this.tokens + ((now - this.last) / 1000) * this.refillPerSec);
this.last = now;
if (this.tokens < 1) return false;
this.tokens -= 1;
return true;
}
}The others
| Algorithm | How | Pros | Cons |
|---|---|---|---|
| Token bucket | Tokens refill at rate r up to B | Allows bursts; smooth average; tiny state | Two parameters to tune |
| Leaky bucket | Requests queue and drain at a constant rate | Perfectly smooth output | Bursts are delayed or dropped; adds latency |
| Fixed window counter | Count per calendar window (per minute) | Simplest: one counter with an expiry | Boundary burst: 100 at 0:59 + 100 at 1:00 = 200 in two seconds |
| Sliding window log | Store each request's timestamp; count those in the last window | Exact | Memory per request |
| Sliding window counter | Weighted mix of the current and previous window counts | Close to exact, tiny state | Approximate |
Sliding window counter estimate:
Distributed rate limiting
With many API servers, limits must be shared. The usual approach is Redis with atomic operations:
-- Fixed-window limiter as a Redis Lua script (atomic)
local current = redis.call("INCR", KEYS[1])
if current == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[1]) -- window length in seconds
end
if current > tonumber(ARGV[2]) then -- limit
return 0
end
return 1Token buckets can be implemented the same way (store tokens and last refill time; update in a Lua script). Considerations:
- Redis adds a network round trip per request; keep it close (same zone), or batch with local limiters that sync periodically (approximate, but cheap).
- Decide what happens when Redis is down: fail open (allow — favours availability) or fail closed (deny — favours protection).
- Gateways and proxies often have this built in: Envoy, Kong, nginx
limit_req, Cloudflare and AWS API Gateway.
Communicating limits
HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 30Clients should honour Retry-After and back off exponentially with jitter, so throttled clients don't all retry in sync.
Related: load shedding and backpressure
Rate limiting enforces per-client fairness. Load shedding protects the service as a whole: when overloaded (queue too long, latency too high), reject or deprioritise low-priority traffic early so important traffic still succeeds. Both belong in a robust system (Reliability patterns).
- Rate limiting protects against abuse and overload and enforces fairness.
- Token bucket: bursts up to B, average rate r — the usual default.
- Fixed windows are simple but allow boundary bursts; sliding windows fix that.
- Distributed limits use Redis with atomic scripts; decide on fail-open or fail-closed.
- Return 429 with Retry-After; clients back off with jitter.
QDesign a rate limiter for an API with 10 million users.hard
Limit at the API gateway by API key or user, using a token bucket per key stored in a Redis cluster (sharded by key) and updated atomically with a Lua script. Configure limits per plan and per endpoint. Add a small local in-memory limiter to absorb extreme bursts cheaply. Return 429 with Retry-After and rate-limit headers, and decide fail-open behaviour if Redis is unavailable. Monitor rejections per key to spot abuse.