TL;DR
- Rate limiting with an in-memory counter stops working the moment you run more than one instance. Each instance counts on its own, so three instances allow three times the limit.
- Moving the counter into Redis isn't enough on its own. A read-then-write version let 1,200 of 1,200 requests through a limit of 100 in my test.
- The fix: one Lua script that reads, refills and takes a token in a single atomic step, using Redis's clock. Same test: exactly 100 of 1,200.
- When Redis goes down, a circuit breaker switches each instance to a smaller local limit instead of letting everything through.
- About 1 ms per decision at the median. Code: github.com/Rimaz17/RateGuard.
When an application runs on a single server, rate limiting is easy. You keep a counter in memory, add one for each request, and refuse requests once the counter passes the limit.
The trouble starts when you add a second server. I wanted to understand that problem properly, so I built RateGuard : a standalone rate-limiting service in Go. Your application asks it over HTTP, "should I allow this request?", and it answers yes or no. In this article I'll walk through the problems I ran into making that answer correct across several instances, and the decisions I made along the way.
The problem: three servers, three limits
Here's the setup I used to test it. One client has a limit of 100 requests an hour. Three RateGuard instances sit behind an nginx load balancer, and the client sends 300 requests at once.
With a normal in-memory limiter, this is what my integration test printed:
300 requests in 110ms: 300 allowed, 0 refused; instances served [100 100 100] Every single request was allowed. The load balancer spread the 300 requests evenly, so each instance saw 100. Each instance had its own counter with its own limit of 100, so each one happily allowed all of them. The client got three times its limit, and nothing looked wrong from inside any one instance.
The fix sounds obvious: keep the counter in one place that every instance can see. I used Redis.
The obvious Redis version, and why it breaks
My first thought was to read the counter from Redis, check it, and write it back:
func naiveTake(ctx context.Context, rdb *redis.Client) bool { tokens, _ := rdb.Get(ctx, key).Int() if tokens > 0 { rdb.Set(ctx, key, tokens-1, 0) return true } return false } Before going further, I wanted to see how badly this could go wrong, so I wrote a small test. Three Redis clients (standing in for three instances), 16 workers each, 1,200 attempts in total, on a bucket of 100 tokens. I ran it five times:
naive allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 48 naive allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 45 naive allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 46 naive allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 43 naive allowed 1200 of 1200 attempts (capacity 100), tokens left in Redis: 46 It allowed every request , and Redis still thought there were about 45 tokens left.
The problem is the gap between GET and SET. With 48 workers running at once, many of them read the same value before any of them writes. Here's what that looks like with just three:
Three requests were allowed, but the counter only went down by one. This is called a lost update, and under enough concurrency it happens on almost every request. Each command is atomic on its own, but the read-check-write sequence as a whole is not.
Choosing how to make it atomic
I looked at three ways to fix it:
| Option | How it works | Why I did or didn't use it |
|---|---|---|
INCR with a fixed window | Increment a counter per minute or hour; refuse when it's over the limit | Atomic, but it isn't a token bucket. A client can send its whole limit at the end of one window and again at the start of the next. |
WATCH / MULTI | Optimistic locking: the write fails if the key changed, and you retry | Correct, but under heavy contention on one key most attempts fail and retry, which is exactly when you need speed |
| A Lua script | Redis runs the whole script as one step, and nothing else runs on that key in between | Atomic, one round trip, and the whole token-bucket logic lives in one place |
I went with the Lua script. Before showing it, here's the algorithm it runs.
The token bucket, in plain terms
Picture a bucket that holds up to capacity tokens. Each request takes one token. If the bucket is empty, the request is refused. Tokens drip back in at a steady rate, for example 100 an hour, until the bucket is full again.
This allows short bursts (a full bucket can serve 100 requests at once) while keeping the long-run average at the limit.
There's no background timer refilling anything. Instead, the bucket stores two numbers: how many tokens it had, and when it last refilled. On each request it works out how much time has passed and adds the tokens that would have dripped in since then. This is called lazy refill, and it means an idle client costs nothing at all.
The Lua script
Here's the core of the script, trimmed for the article. The full version, with input validation, is in internal/limiter/scripts/bucket.lua.
local capacity = tonumber(ARGV[1]) local rate = tonumber(ARGV[2]) -- tokens per second -- One clock for every instance: Redis's own. local clock = redis.call('TIME') local now = tonumber(clock[1]) * 1000000 + tonumber(clock[2]) local state = redis.call('HMGET', KEYS[1], 'tokens', 'last_refill_us') local tokens = capacity local last = tonumber(state[2]) if last == nil then last = now -- never used, or expired because it was full else tokens = math.min(capacity, tonumber(state[1])) local elapsed = now - last if elapsed > 0 then -- lazy refill tokens = math.min(capacity, tokens + elapsed / 1000000 * rate) last = now end end local allowed = tokens >= 1 - 1e-9 if allowed then tokens = math.max(tokens - 1, 0) local ttl = math.ceil((capacity - tokens) / rate * 1000) redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_refill_us', last) redis.call('PEXPIRE', KEYS[1], math.max(1, ttl)) end return {allowed and 1 or 0, tostring(tokens)} A few decisions in here weren't obvious at first:
It uses Redis's clock, not the server's. Lazy refill depends on the current time. If each instance passed in its own clock, a few hundred milliseconds of drift between servers would give different token counts for the same bucket, and the shared limit would quietly stop being shared. Calling redis.call('TIME') inside the script means there's exactly one clock. I also handle the case where that clock goes backwards: nothing refills, so no time is counted twice.
A refused request writes nothing. Refill is calculated from the stored state each time, so leaving a refused bucket untouched gives the same answer on the next request as writing the refilled value would. The result: a client hammering the API after hitting its limit costs Redis reads only, no writes.
The key deletes itself once the bucket is full. PEXPIRE is set to the moment the bucket will be full again. A missing key and a full bucket behave the same way, so expiring it changes no decision, and Redis only holds buckets that are actually in use.
The 1e-9 tolerance. Floating-point refill can leave a bucket at 0.9999999999 tokens when it should be at exactly 1. Without the tolerance, that request would be refused for a rounding error.
Calling it from Go
On the Go side, go-redis's Script type sends the script with EVALSHA (just its hash) and falls back to sending the full script if Redis doesn't have it cached, for example after a restart:
func NewRedis(rdb redis.Scripter) *Redis { return &Redis{rdb: rdb, script: redis.NewScript(bucketScript)} } reply, err := s.script.Run(ctx, s.rdb, []string{key}, l.Capacity, strconv.FormatFloat(l.RefillRate, 'g', -1, 64), mode).Slice() One detail here took me a while to notice. go-redis retries failed commands by default. Normally that's helpful, but think about what a retry means here: if the script ran and took a token, and then the reply got lost on the network, the retry runs the script again and takes a second token. So I turned retries off on RateGuard's Redis client. A failed call counts as a failure, and the circuit breaker (next section) decides what happens.
With the Lua script in place, the same 1,200-attempt test gives:
lua allowed 100 of 1200 attempts (capacity 100), tokens left in Redis: 0 Exactly 100, every run. And the three-instance test from the start of the article:
300 requests in 432ms: 100 allowed, 200 refused; instances served [100 100 100] Each instance still served 100 requests, but together they allowed exactly 100.
What happens when Redis goes down?
Now every decision depends on Redis, so Redis being down is a real question. There are three choices:
| Option | What happens during an outage | The problem |
|---|---|---|
| Fail open | Allow everything | Anyone gets unlimited access the moment Redis has a hiccup |
| Fail closed | Refuse everything | A rate limiter outage becomes an outage of every service behind it |
| Degrade to a local bucket | Each instance enforces a smaller limit from memory | Enforcement becomes approximate |
I went with the third, and made the other two available as a setting for anyone who prefers them.
A circuit breaker (sony/gobreaker) wraps every Redis call, and each call has a 100 ms timeout. After 5 failures in a row, the breaker opens and decisions switch to an in-memory bucket. That local bucket gets capacity / N, where N is the number of instances, so three instances together still roughly match the real limit. Every 5 seconds the breaker lets one request through to check whether Redis is back.
I tested this by killing Redis mid-test. The client had a limit of 30 and had already used 15. With Redis gone, 60 more requests went to the three instances:
with redis down: map[200:30 429:30] after redis returned: map[200:15 429:6] Each instance's local bucket held 30 / 3 = 10, so 30 requests were allowed and 30 refused. Every request still got an answer, and nothing became unlimited. When Redis came back, its bucket still held the 15 tokens from before the outage, so exactly 15 more were allowed.
The degraded mode is never silent. Each degraded decision increments a Prometheus counter, and the breaker opening logs a warning. I deliberately didn't log every degraded decision, because during an outage that would mean thousands of log lines a second at exactly the moment the service is under strain. Instead it logs at most one warning every 10 seconds, with a count.
How fast is it?
I load-tested it with k6 on my laptop (Intel i5-10210U, 4 cores), with k6, RateGuard, Redis and PostgreSQL all on the same machine:
| Test | Result |
|---|---|
| Median latency per decision | About 1 ms |
| One instance, 100 virtual users | ~4,900 requests/s |
| Redis running just the bucket script on one key | ~19,700/s |
Two honest caveats. First, the p99 latency ranged from 9 to 92 ms, mostly because the load generator was competing with the service for the same 4 CPU cores. Second, three instances behind nginx reached about 2,500 requests/s in total, lower than one instance, for the same reason: everything was sharing one laptop. Neither number says much about a real deployment across separate machines, so I've published them with that context instead of picking the best-looking one.
The bigger point is the hot path. A decision does one Redis call and nothing else: API keys and policies come from in-memory caches, and usage analytics are batched to Redis every second and PostgreSQL every 10 seconds, off the request path.
Trade-offs I accepted
- One hot key has a ceiling. Redis runs scripts on a key one at a time, so a single very busy client tops out around 19,700 decisions a second on this machine. I didn't shard keys in v1. Instead, every bucket key comes from a single
keyFor()function, so splitting a hot key into sub-buckets later means changing one function. - Outage enforcement is approximate. If the load balancer sends one client's traffic unevenly, that client can go somewhat over or under its limit while Redis is down.
- The instance count is set by hand. The local bucket size depends on
RG_INSTANCE_COUNT. If the deployment scales and nobody updates it, outage limits drift.
What I learned
- "Shared state" isn't the same as "correct state." Moving the counter into Redis fixed nothing until the read and the write happened as one step.
- Write the failing test first. The 1,200-of-1,200 result made the race real in a way reading about it never did, and it gave me a test to prove the fix.
- Think about time explicitly. As soon as more than one machine is involved, "now" is a design decision.
- Retries aren't free. Retrying something that isn't safe to repeat can turn a network blip into a wrong answer.
- Decide how you fail before you fail. Picking "degrade" over "open" or "closed" was a product decision as much as a technical one, and writing it down early made the circuit breaker code straightforward.
Every design decision in RateGuard is written up as a short decision record in the repo, if you want to go deeper into any of these.



