Designing a distributed rate limiter
A rate limiter looks like a counter with an if in front of it. Then you run it on twenty servers at once, put it in the path of every request, and ask it to stay correct when its own database goes away. This note walks through the whole design: requirements, the choice of algorithm, the maths, the atomic Redis script, and the failure modes that decide whether it helps or hurts in production.

Requirements
- Limit each API key to 100 requests per minute, with short bursts of up to 20 allowed.
- The API runs on 20 gateway servers behind a load balancer, so the limit must hold across all of them, not per server.
- A decision must take under 2 ms at p99. The limiter sits in front of every request, so its latency is everyone's latency.
- If the limiter's storage is unavailable, fail open: let traffic through at a reduced, local limit rather than taking the API down.
- Rejected requests get
429 Too Many Requestswith aRetry-Afterheader, and every response carries the remaining quota.
Choosing an algorithm
There are four classic options. They differ in how exact they are, how much state they keep per key, and how they treat bursts.
| Algorithm | State per key | Accuracy | Bursts |
| Fixed window | 1 counter | Poor at window edges | Up to 2× the limit |
| Sliding log | Every timestamp, | Exact | None beyond the limit |
| Sliding window counter | 2 counters | Close (weighted estimate) | Smoothed |
| Token bucket | 2 numbers, | Exact for its model | Controlled by |
Fixed window counts requests per calendar minute. A client can send 100 requests at 12:00:59 and another 100 at 12:01:00, which is 200 requests in two seconds while never breaking the rule.
Sliding log stores the timestamp of every request and counts those inside the last 60 seconds. It is exact, but a key at its limit holds 100 timestamps, and a busy API with a million keys holds a lot of them.
Sliding window counter keeps the current and previous window counts and blends them. With window length and seconds elapsed in the current window:
It is cheap and usually within a few percent, which is why many CDNs use it.
Token bucket is our pick. It needs two numbers per key, allows a burst we choose explicitly, and gives a natural answer to "when can I retry?".
Token bucket maths
A bucket holds at most tokens and refills continuously at tokens per second. If it held tokens at the last update , then at time :
A request is allowed when , and one token is removed. When it is denied, the client must wait until a whole token has refilled:
Over any interval of length , at most requests pass: the full bucket plus everything that refills during the interval. For 100 per minute with bursts of 20:
So a client that has been idle can send 20 requests at once, then settles to one request every 0.6 seconds. In the worst case a full minute lets through requests. If the contract says "never more than 100 in any minute", set instead, for example and .

Where the state lives
Each gateway could keep its own buckets, but with 20 gateways and a round-robin load balancer a client would get roughly 20 times its limit. The buckets have to be shared, and they have to be fast. That points to Redis:
- One hash per API key,
rl:{key}, with two fields:tokensandts. - Redis Cluster spreads keys over shards by hash slot, so capacity grows by adding shards.
- An in-region round trip is well under a millisecond, which leaves room inside the 2 ms budget.
The trap is a race. If two gateways read tokens = 1 at the same moment, both allow the request and both write 0. The fix is to do the read, the refill and the write in a single Lua script, which Redis runs atomically.

The Lua script
-- KEYS[1] = bucket key, ARGV[1] = rate (tokens per second), ARGV[2] = burst
local rate = tonumber(ARGV[1])
local burst = tonumber(ARGV[2])
-- One clock for every gateway: Redis's own
local t = redis.call("TIME") -- { seconds, microseconds }
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
local b = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(b[1]) or burst
local ts = tonumber(b[2]) or now
tokens = math.min(burst, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
end
redis.call("HSET", KEYS[1], "tokens", tokens, "ts", now)
-- An idle bucket is full again after burst / rate seconds, so drop it then
redis.call("PEXPIRE", KEYS[1], math.ceil(burst / rate * 1000))
if allowed == 1 then
return { 1, math.floor(tokens) } -- remaining
end
return { 0, math.ceil((1 - tokens) / rate * 1000) } -- wait in msTwo details matter here:
- Redis turns Lua numbers into integers when it returns them. Returning
0.6seconds would arrive as0. That is why the script returns whole tokens and the wait in milliseconds. - Calling
TIMEinside a script is safe on Redis 5 and later, where scripts replicate their effects rather than the script itself. Using Redis's clock means twenty gateways with slightly different clocks cannot disagree about how many tokens have refilled.
The gateway loads the script once and calls it by hash with EVALSHA, so each request sends a 40-character hash instead of the script body:
redis.defineCommand("tokenBucket", { numberOfKeys: 1, lua: TOKEN_BUCKET_LUA });
export async function check(apiKey: string, plan: Plan): Promise<Decision> {
try {
const [allowed, value] = await withTimeout(
redis.tokenBucket(`rl:{${apiKey}}`, plan.rate, plan.burst),
2, // ms
);
return allowed === 1
? { allow: true, remaining: value }
: { allow: false, retryAfterSeconds: Math.ceil(value / 1000) };
} catch {
metrics.increment("ratelimit.fail_open");
return localBucket.check(apiKey, plan.rate / 20, Math.max(1, plan.burst / 20));
}
}Failure modes

- Redis is slow or down. Fail open, but not unlimited. Each gateway falls back to an in-memory bucket at of the limit, which is roughly the right share when the load balancer spreads traffic evenly. Alert on the
fail_opencounter, because a silent fallback hides an outage. - A hot key. One abusive client hammering a single key sends every request to one shard. Once a key is denied, cache "denied until " in the gateway's memory and answer the next requests locally until the retry time passes.
- Clock skew. Never compute refills from app server clocks. A gateway whose clock runs a second ahead would hand out extra tokens. The script reads
TIMEfrom Redis for exactly this reason. - Failover. Redis replication is asynchronous, so a shard failover can lose the last few writes. A few buckets briefly refill early, which is acceptable for rate limiting and not worth a consensus protocol.
Telling clients what happened
A limiter that only says "no" creates retry storms. Every response should carry the quota, and every rejection should say when to come back:
HTTP/1.1 429 Too Many Requests
Retry-After: 1
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 1Retry-After is standard HTTP. The RateLimit-* fields follow the IETF draft, and many APIs send the older X-RateLimit-* names instead. Well-behaved SDKs wait for Retry-After and add jitter, so a thousand clients do not all retry in the same millisecond.
Launch checklist
- Shadow mode: log decisions for a week without blocking anyone
- Dashboards: allowed vs blocked per key, limiter p99 latency, fail-open count
- Per-plan limits loaded from config, not code
- Alert when more than 5% of traffic is blocked
- Load test with Redis killed mid-run to prove the fallback works
Start in shadow mode. A rate limiter that blocks real customers on day one is worse than having none.