Designing a Distributed Rate Limiter: GCRA, Hybrid Coordination, and Production Gotchas
An API key has a limit of 100 requests/min. The gateway passes a load test with one replica. Then you add a second replica, rerun the test, and the same key can make 200 requests/min if traffic is distributed evenly. Nothing is wrong with either counter: the bug is that each replica thinks it owns the whole budget.
The previous post covered how to count requests. In production you have two more decisions: who owns the counter, and what do you do when you can’t reach it? I’d start with one shared Redis check per request and move decisions closer to the gateway only when measurements show that the check is the bottleneck.
Start With One Atomic Decision
Moving the counter to Redis fixes the per-replica problem, but a separate read and increment doesn’t fix concurrency. With 99 requests counted against a limit of 100, two workers can both read 99, both allow the request, and leave the counter at 101. The decision and the state change have to happen together.
Use a short Redis Lua script to read the state, decide, and update it with an expiry. On Redis Cluster, every key the script touches must be in the same hash slot. If a sliding window counter uses two keys, names like {user:123}:previous and {user:123}:current keep them together. Use the Redis clock inside the script so two gateway hosts with slightly different clocks don’t disagree about the window.
The first integration test I’d write sets the counter to 99 in an active window, then sends two requests for the same key through different gateway replicas. Exactly one should pass. A sequential localhost test won’t catch the read-before-write race.
I’d also test the same key across a Redis failover. Atomicity on the primary doesn’t guarantee that a newly promoted replica has every recent update: Redis replication is asynchronous. If losing recent counts would let callers spend money twice, the rate limiter is the wrong place to keep the only record of spending. Keep that record in the system that actually authorizes or charges the work.
GCRA: A Burst Limit in One Timestamp
For steady traffic with an allowance for short bursts, GCRA (Generic Cell Rate Algorithm) is a token-bucket-style limiter that stores one timestamp per key. It’s not an exact sliding window log: it controls a rate plus a burst allowance, not a hard count in every possible rolling interval.
The timestamp is the Theoretical Arrival Time (TAT), or when the next request would be due at the configured pace. If the limit is 30/min, the interval T is 2 s. If you want a total burst of B requests from idle, let a request arrive up to (B - 1) × T early:
T = period / requests_per_period
burst_tolerance = (B - 1) * T
TAT = stored timestamp, or now for an idle key
if now < TAT - burst_tolerance:
reject; retry in (TAT - burst_tolerance) - now
else:
allow; store max(now, TAT) + T
For B = 3, three requests at the same instant are allowed. The fourth needs to wait 2 s. There is no timer refilling a bucket in the background. For a Redis implementation, expire the key no earlier than the updated TAT; at that point treating it as idle gives the same result as keeping the timestamp. Round any delay you send as Retry-After up to whole seconds.
If you can load redis-cell, CL.THROTTLE user:123 2 30 60 1 checks a sustained rate of 30 requests per 60 seconds with a total idle burst of three. Its burst argument is the extra allowance beyond the initial request. If the Redis provider doesn’t support the module, the same decision can live in a Lua script.
Move Work Off Redis Only When There Is a Reason
Check limiter latency at p99 alongside Redis load and per-tenant traffic. If the shared check is healthy across the normal traffic profile but one tenant spikes a single shard, adding shards won’t help that key. If every shard is busy or the network hop dominates, reducing the number of shared checks can make sense. These are different problems.
Local counters with periodic sync
A gateway can count locally and flush its deltas to Redis every 100 ms. The catch is that the next gateway can’t see those unsynced admissions. If the shared budget has already been exhausted elsewhere and ten gateways still think traffic can pass, at 1,000 req/s each they can admit up to 1,000 more requests in that 100 ms gap. That’s an illustration under those traffic and timing assumptions, not a hard bound if synchronization stalls.
That may be fine for coarse abuse throttling. It isn’t fine if every admitted call incurs a third-party charge. If you accept stale decisions, define how old the shared state is allowed to get before switching to a fallback or refusing new work.
Token leasing and hot keys
With token leasing, the gateway reserves a batch from the shared budget before spending it locally. If the store atomically deducts the lease and the gateway doesn’t spend it beyond its validity window, local admission doesn’t overshoot the allocation. The trade-off is stranded capacity: an idle or crashed gateway may hold tokens that a busy one could use. Smaller leases reduce that waste but bring back more Redis round-trips. The same idea can allocate slices of a long-lived quota to different regions without a cross-region call on every request. The awkward case is a crashed gateway: if it already spent some of its lease, expiry alone doesn’t tell you how much can safely go back into the budget. For a strict quota, don’t recycle that allocation in the same window without reliable usage accounting.
A hot key is a separate issue. For a soft limit of 10,000/s you might split traffic over ten counters on different shards, each with 1,000/s, by hashing a request ID. One shard no longer sees every request, but uneven traffic can fill one counter while another still has capacity. Don’t do this if callers expect to share every last unit of a strict quota.
Decide What Happens on the Bad Day
Redis is down. A read timeout is not evidence that a caller exceeded a quota. For a low-risk endpoint, I’d consider falling back to a coarse in-process limiter so a Redis timeout doesn’t take the API down. Size that emergency budget for the fleet, not as if each replica were the only one. For a billing-sensitive endpoint, I’d reject work I can’t account for: return 503 when the check is unavailable, and reserve 429 for a limit you actually know was reached. Also test a timeout after Redis has applied the decision; blindly retrying the check can count the same request twice.
Clients retry together. Telling every throttled client to retry in five seconds can turn one burst into two. If you control the client, have it honor Retry-After as a minimum and add jitter. If you queue excess requests instead, cap the wait against the caller’s deadline. A 3 s queue behind a client with a 2 s timeout just starts work the client has already given up on.
A new rule looks good on paper. Run it in shadow mode first: count would-be rejections without blocking requests, and look at which routes and tenants would have been affected. Before enforcing it, test the concurrent last request, a retry after an ambiguous timeout, and a Redis outage. Watch limiter latency and fallback usage alongside 429 rates. Otherwise a quiet 429 graph can mean either that traffic is healthy or that the limiter has stopped enforcing the rule.