Designing a Distributed Rate Limiter
Rate limiting is simple until it isn't. Explore the requirements, design options, and failure modes of building a rate limiter that works at scale.
A rate limiter caps how many requests a client may make in a given period. It protects services from overload, shields expensive resources, enforces fair use between tenants, and limits abuse such as credential stuffing or scraping. On a single server it is a few lines of code. Across a fleet of stateless servers, with latency budgets and partial failures, it becomes a real distributed systems problem.
Requirements
Start by being precise about what you need:
- Correctness of limits: a client limited to 100 requests per minute should not receive 400 because four servers each counted separately.
- Low latency: the check sits on the hot path, so it should add only a millisecond or two.
- Burst handling: decide whether short spikes are allowed or the traffic must be smoothed.
- Granularity: limit by user, API key, IP address, endpoint, or tenant, possibly several at once.
- Availability: the limiter must not become the reason the API goes down.
- Clear feedback: clients should learn their limit and remaining quota.
There is a fundamental tension between strict global consistency and low latency. Most production systems accept approximate limits in exchange for speed and resilience.
Core Algorithms
| Algorithm | Idea | Pros | Cons | |---|---|---|---| | Fixed window | Counter per time window, reset at boundary | Trivial, tiny memory | Boundary burst: up to double the limit across a window edge | | Sliding window log | Store a timestamp for every request | Exact | Memory grows with the limit | | Sliding window counter | Weighted blend of current and previous window counts | Good accuracy, small memory | Approximate | | Token bucket | Tokens refill at a steady rate; each request spends one | Allows controlled bursts, widely used | Two values to track per key | | Leaky bucket | Requests queue and drain at a constant rate | Smooth output | Adds queueing delay, bursts are dropped |
Token bucket is the most common general choice. A bucket holds up to a capacity of tokens and refills at a fixed rate. The capacity sets the allowed burst, and the refill rate sets the sustained limit.
Implementing It With Redis
A shared in-memory store such as Redis is the usual place for counters. The critical detail is atomicity. A naive read, compute, write sequence races when two servers process the same key concurrently and lets extra requests through. Perform the whole check inside a single Lua script, which Redis runs atomically:
-- KEYS[1] = bucket key; ARGV = capacity, refill_per_sec, now_ms, cost
local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local tokens = tonumber(data[1]) or capacity
local ts = tonumber(data[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], 120000)
return allowed and 1 or 0
Set expirations so idle keys disappear. Use a server-side or shared time source, since client clock skew corrupts refill math.
Scaling the Architecture
A few placement and scaling choices dominate the design:
- Where to enforce. An API gateway or edge proxy applies limits before traffic reaches services. Application-level limits can add business-aware rules, such as per-plan quotas.
- Sharding the counters. Hash the client key across a Redis cluster so no single node is a bottleneck, keeping every key on exactly one shard.
- Local plus global. Each server keeps a local token allowance and syncs with the central store periodically or in batches. This cuts network calls dramatically at the cost of some overshoot.
- Multi-region. Strict global limits across regions need cross-region round trips. Often it is better to split the quota per region, or accept eventual reconciliation.
Client -> Gateway --(Lua check)--> Redis cluster (sharded by key)
| |
allowed / 429 replicated for failover
Failure Modes
Most rate limiters fail under burst traffic or partial outages, and the failure behavior should be a deliberate design decision.
- Limiter store unavailable. Fail open (allow traffic) protects availability but removes protection exactly when load is high. Fail closed protects backends but turns a Redis blip into a full outage. Many teams fail open with a conservative local fallback limit.
- Hot keys. A single abusive or very large client can overload one shard. Add local pre-limiting and monitor the top keys.
- Retry storms. Rejected clients that retry immediately amplify load. Return
429 Too Many Requestswith aRetry-Afterheader and exposeRateLimit-LimitandRateLimit-Remaining, and encourage exponential backoff with jitter. - Clock and replication lag. Replica reads can undercount. Always run the check against the primary for that key.
- Misconfiguration. A wrong limit can lock out legitimate traffic, so support dry-run mode that logs what would be blocked before enforcing.
Key Takeaways
- Choose the algorithm by behavior: token bucket for controlled bursts, sliding window counter for accuracy at low memory.
- Make each check atomic, using a Lua script or equivalent, to avoid race conditions.
- Accept approximate global limits in exchange for latency and resilience, using local allowances to reduce round trips.
- Decide explicitly whether the limiter fails open or closed, and monitor hot keys.
- Give clients clear signals with 429 responses and rate limit headers, and roll out new rules in dry-run mode first.
Get the Design Review Checklist
One practical architecture lesson a week, plus the checklist we use to review designs. No spam.
Want this applied to your own system? Book an architecture design review.