Rate Limiter in Distributed Systems
A rate limiter controls how many requests a client, user, IP address, or API key can send to a service within a given time window (for example, 100 requests per minute). When a caller exceeds its quota, the rate limiter rejects excess requests early — usually with HTTP 429 Too Many Requests — protecting backend servers, databases, and third-party APIs from overload, abuse, and runaway retry storms.
How a Rate Limiter Works
Rate limiting is typically enforced at the edge inside an API Gateway, CDN, or reverse proxy before requests ever touch application servers.
When a request arrives, the limiter extracts a key (such as userId, apiKey, or client IP), atomically checks and updates that key’s counter in a fast in-memory store like Redis (see Caching), and either forwards the request or returns 429 with helpful response headers:
X-RateLimit-Limit— total requests allowed per windowX-RateLimit-Remaining— requests left in the current windowRetry-After— seconds the client should wait before retrying
Core Rate Limiting Algorithms
Each algorithm trades off burst tolerance, memory usage, and boundary accuracy:
| Algorithm | How It Works | Burst Handling | Memory per Key | Best For |
|---|---|---|---|---|
| Token Bucket | Bucket refills at a steady rate up to a max capacity; each request takes 1 token | Allows short bursts up to bucket size | Low (2 numbers: tokens + timestamp) | General APIs (Stripe, AWS, Envoy default) |
| Leaky Bucket | Requests enter a fixed-size queue and drain at a constant output rate | Smooths out bursts completely | Low–Medium (queue depth) | Protecting downstream systems that need strictly steady traffic |
| Fixed Window Counter | Increments a counter per fixed slot (e.g., 12:01:00–12:01:59) |
Can allow 2× burst across a window boundary | Lowest (1 integer) | Simple coarse quotas where edge spikes are acceptable |
| Sliding Window Log | Stores timestamps of every request in the last T seconds (e.g., Redis Sorted Set) |
Strictly accurate — no boundary spikes | High (stores every timestamp) | Low-volume, strict security endpoints (login, OTP) |
| Sliding Window Counter | Weighted average of the previous and current fixed window counters | Very accurate with almost no edge spike | Lowest (2 integers) | High-throughput APIs needing accuracy + tiny memory |
Distributed Rate Limiting Challenges
Running a rate limiter on one server is trivial. Running it across a fleet of stateless gateways behind a load balancer introduces two classic problems:
- Race conditions across concurrent reads/writes: If two gateway instances read
remaining = 1from Redis at the exact same millisecond, both may allow the request. Solve this using Redis Lua scripts (which execute atomically on a single thread) or atomicINCR+EXPIREcommands. - Synchronization & Redis latency: Querying a single central Redis cluster on every request adds a network hop. High-scale systems either shard counters across Redis nodes with consistent hashing or batch local in-memory counters periodically (trading tiny accuracy for lower latency — a classic CAP / PACELC trade-off).
- Fail-open vs. Fail-closed: Decide upfront what happens if Redis goes down. Most consumer APIs fail open (let traffic through so a Redis outage doesn’t take down checkout), whereas login or payment endpoints may fail closed (or fall back to conservative local per-node limits).
Why Rate Limiting Matters Beyond Security
- Stops retry storms: When a downstream service slows down in a system with temporal coupling, aggressive client retries can multiply traffic by 10×. Rate limiting sheds excess load before the whole cluster collapses.
- Enforces fair multi-tenancy: Prevents one noisy customer or buggy integration from starving shared databases and queues.
- Controls cloud and third-party costs: Caps calls to paid APIs (SMS gateways, LLM APIs, payment processors) before a bug creates a surprise bill.
FAQs
Which rate limiting algorithm should I pick by default?
Token Bucket or Sliding Window Counter. Token Bucket is simple, uses minimal memory, and naturally allows legitimate short bursts (like a page loading 6 API calls at once) while capping sustained traffic. Sliding Window Counter is ideal when you want strict per-minute limits without the boundary spike of Fixed Window.Where should rate limiting live — API Gateway, app code, or CDN?
Layer it: put coarse IP/DDoS rate limits at the CDN edge, per-user and per-API-key quotas at the API Gateway, and fine-grained business limits (like “max 3 password resets per hour”) inside the owning service.What HTTP status code should a rate limiter return?
Return429 Too Many Requests along with a Retry-After header so well-behaved clients back off cleanly instead of retrying immediately in a tight loop.Should excess requests always be dropped, or can they be queued?
For interactive user APIs, failing fast with429 is usually better than holding connections open. For background jobs or webhooks, you can buffer excess work into an asynchronous messaging queue so consumers drain it at a steady pace.