Designing a distributed rate limiter with Redis
A rate limiter that lives inside one process breaks the moment you run three copies of the API. Here is a token bucket shared through Redis, made atomic with a Lua script, with a Go middleware and a plan for when Redis is down.
An in-memory rate limiter works fine until you run a second copy of the service. With three instances behind a load balancer, a "100 requests per minute" limit quietly becomes 300, because each instance keeps its own count. The fix is to keep the count in one shared place, and Redis is the usual choice.
This is an intermediate post. You should know a bit of Go and have Docker on your machine. If you haven't read it yet, the token bucket rate limiter in golang without Redis covers the single process version, and this one picks up where that stops. I used Go 1.27.3, Redis 8.10.3 (the redis:8-alpine image) and go-redis v9.23.0.
We will go the usual way for this series: requirements, estimates, a diagram, then a deep dive and the trade-offs.
Requirements
I wrote them down the way I would for a real public API.
- Limit per API key (or per user). Per IP only for anonymous calls.
- Allow short bursts, then a steady rate. For example 100 requests at once, then 10 per second.
- The limit must hold across all app instances.
- Tell the client when to come back: a
429with aRetry-Afterheader. - Adding the limiter must not add much latency. A millisecond or two is fine.
- If Redis goes down, the API stays up.
Actually the last one is the one people forget. We will spend a whole section on it.
Estimates
The method is the same as in system design basics: latency, throughput and back-of-the-envelope estimates. Say the API has 10,000 active API keys and peaks at 2,000 requests per second across all instances. Every request makes one Redis call, so Redis sees 2,000 script calls a second. A single Redis instance handles far more than that on one core, the script is a handful of commands on one small hash.
Memory is tiny. I checked the real size of one bucket with MEMORY USAGE after running the code below and it said 90 bytes. 10,000 keys is under a megabyte. Even a million keys is about 90 MB, and idle keys expire by themselves.
Latency is one network round trip to Redis. In the same availability zone that's well under a millisecond. On my laptop, through OrbStack's port forwarding, it was a lot slower, which bit me later.
High-level design
+-----------+
client -------> | LB |
+-----+-----+
+------------+------------+
v v v
+---------+ +---------+ +---------+
| api #1 | | api #2 | | api #3 | middleware: Allow(key)
+----+----+ +----+----+ +----+----+
| | |
+------------+------------+
v
+-----------------+
| Redis | one hash per key:
| rl:{key:abc} | tokens, last refill time
+-----------------+
Each instance asks Redis "can key X spend one token?" before running the handler. Redis keeps the only copy of the bucket.
Picking the algorithm
There are three common ones.
A fixed window counter is INCR plus EXPIRE on a key like rl:abc:202611191205. It's the simplest. The problem is the edge of the window: a client can send the full limit at 12:05:59 and again at 12:06:00, so twice the limit in two seconds.
A sliding window log keeps one sorted set entry per request and counts entries in the last N seconds. It's exact. But memory grows with the limit. A limit of 1,000 per minute means up to 1,000 entries per key.
A token bucket keeps two numbers per key: tokens left and when we last refilled. It allows bursts up to the bucket size and a steady rate after that, which matches the requirements. I went with token bucket. I still wrote the sliding log too, it's in the code folder, for when someone needs an exact "N per window" rule.
Why not just GET and SET from Go
My first instinct was to read the counter in Go, check it and write it back. So I wrote that version as test, to see how bad it gets. 300 goroutines, limit of 100.
n, err := rdb.Get(ctx, key).Int()
if err != nil && err != redis.Nil {
return err
}
if n < limit {
rdb.Set(ctx, key, n+1, time.Minute)
allowed.Add(1)
}
ratelimit_test.go:99: naive limiter allowed 300 of 300 with limit 100
Every single request got through. All the goroutines read the old value before any of them wrote, so the limit did nothing at all. I ran it five times and it was 300 of 300 every time. Multiple app instances make this worse, not better.
The read, the refill and the write have to happen as one step. In Redis that means a Lua script (or a function), because Redis runs a script start to end without running any other command in between.
The Lua script
-- Token bucket. One hash per key: tokens left and the last refill time.
-- KEYS[1] = bucket key
-- ARGV[1] = capacity (max burst)
-- ARGV[2] = refill rate, tokens per second
-- ARGV[3] = cost of this request (usually 1)
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
-- Use the Redis clock, not the app server clock.
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1])
local ts = tonumber(b[2])
if tokens == nil then
tokens = capacity
ts = now
end
local elapsed = math.max(0, now - ts)
tokens = math.min(capacity, tokens + elapsed * rate / 1000)
local allowed = 0
local retry_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_ms = math.ceil((cost - tokens) * 1000 / rate)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
-- An idle bucket refills completely after capacity/rate seconds,
-- so after that the key carries no information. Let it expire.
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity * 1000 / rate) + 1000)
return {allowed, math.floor(tokens), retry_ms}
A few choices in there are deliberate.
The time comes from redis.call('TIME'). If each app server passed its own clock, two servers that are 300 ms apart would refill the same bucket differently. With the Redis clock there is only one clock. Since Redis 7 scripts are replicated by their effects, so calling TIME in a script that writes is fine.
Basically, the refill is lazy. Nothing runs in the background. Each call works out how many tokens dripped in since the last call.
The key expires once a full refill has happened, so idle keys clean themselves up. A bucket that would be full anyway carries no information.
The Go side
redis.NewScript sends EVALSHA and falls back to EVAL when Redis says it hasn't seen the script yet. The key goes inside {} braces. On Redis Cluster that's a hash tag, it decides which slot the key lands on, and it keeps any other keys you add for the same client on the same node.
//go:embed token_bucket.lua
var tokenBucketLua string
var tokenBucket = redis.NewScript(tokenBucketLua)
func (l *Limiter) Allow(ctx context.Context, key string) (Result, error) {
if time.Now().UnixNano() < l.downUntil.Load() {
return l.allowLocal(key), nil
}
ctx, cancel := context.WithTimeout(ctx, l.Timeout)
defer cancel()
res, err := tokenBucket.Run(ctx, l.rdb, []string{"rl:{" + key + "}"},
l.capacity, l.perSec, 1).Int64Slice()
if err != nil {
if errors.Is(err, context.Canceled) {
return Result{}, err
}
slog.Warn("rate limiter: redis failed, using local fallback", "err", err)
l.downUntil.Store(time.Now().Add(time.Second).UnixNano())
return l.allowLocal(key), nil
}
if len(res) != 3 {
return Result{}, fmt.Errorf("unexpected script reply %v", res)
}
return Result{
Allowed: res[0] == 1,
Remaining: res[1],
RetryAfter: time.Duration(res[2]) * time.Millisecond,
}, nil
}
The middleware turns that into HTTP.
func (l *Limiter) Middleware(keyFn func(*http.Request) string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
res, err := l.Allow(r.Context(), keyFn(r))
if err != nil {
http.Error(w, "request cancelled", http.StatusServiceUnavailable)
return
}
if !res.Degraded {
w.Header().Set("RateLimit-Remaining", strconv.FormatInt(res.Remaining, 10))
}
if !res.Allowed {
secs := int(math.Ceil(res.RetryAfter.Seconds()))
w.Header().Set("Retry-After", strconv.Itoa(max(1, secs)))
http.Error(w, "too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
Retry-After is standard HTTP. The RateLimit-* headers come from an IETF draft that changed shape a few times, so if your clients will parse them, check the current draft first. I kept it to one simple header.
Running it
Start a throwaway Redis, then the demo API from the code folder. It allows a burst of 10 and then 2 per second per API key.
docker run -d --name rl-redis -p 127.0.0.1:6379:6379 redis:8-alpine
REDIS_ADDR=127.0.0.1:6379 go run ./cmd/api
In another terminal, fire 12 requests.
for i in $(seq 1 12); do
curl -s -o /dev/null \
-w "%{http_code} remaining=%header{ratelimit-remaining} retry-after=%header{retry-after}\n" \
-H "X-API-Key: demo" localhost:8080/
done
200 remaining=9 retry-after=
200 remaining=8 retry-after=
...
200 remaining=0 retry-after=
429 remaining=0 retry-after=1
429 remaining=0 retry-after=1
The bucket itself is a plain hash, you can look at it.
docker exec rl-redis redis-cli HGETALL "rl:{key:demo}"
tokens
0.13999999999999946
ts
1795070239417
The fraction is the refill that dripped in between the last two calls. Floats, fine for this.
The real test is the shared one: three separate Redis clients (three "instances") and 300 concurrent calls against a bucket of 100 refilling at 10 per second.
ratelimit_test.go:64: allowed=102 denied=198 took=222.434583ms
100 from the burst plus two that refilled during the 222 ms run. Compare that with the 300 of 300 from the naive version.
When Redis is down
This is the same thinking as in designing for failure: the limiter is a dependency, so it needs a timeout and a plan. See, you have three options. Fail closed means every request gets rejected, so a Redis blip becomes a full API outage. I don't like that for most APIs. Fail open means no limit at all while Redis is away, which is exactly the moment a misbehaving client can do the most harm. The middle option is a local fallback: each instance keeps an in-memory bucket with its share of the limit, so with 3 instances each one allows a third.
That's what allowLocal does, with golang.org/x/time/rate. My test points the client at a closed port and checks it.
ratelimit_test.go:138: fallback allowed 10 of 50 in 51.159541ms
A third of the burst of 30, as expected. The downUntil field matters here. My first version had no cooldown, so every request tried Redis, waited for the dial to fail, then fell back. That run took 2.54 seconds for 50 calls and let 12 through instead of 10, because the bucket refilled while it waited around. Now one failure skips Redis for a second and the 50 calls take 51 ms.
And the timeout bit me from the other side too. I started with 50 ms per call. On my laptop, the very first shared test sometimes fell back on a few dozen calls with context deadline exceeded, because 300 brand new connections through Docker's port forwarding are slow to open. One of those runs allowed 123 instead of 100, the fallback buckets are looser than the real one. In production next to Redis, 50 ms is plenty. In the test I raised the timeout and loaded the script at startup with Warm, so the first requests don't pay for the extra EVALSHA, NOSCRIPT, EVAL round trip.
Trade-offs
Every request now pays a Redis round trip. If that hurts, you can let each instance take tokens in small batches (say 10 at a time) and spend them locally. Less calls, slightly less exact.
Redis becomes part of your request path. Put it in the same zone as the app, watch its latency, and decide the failure mode up front, as above.
With a primary and replica, a failover can lose the last few writes, so some buckets reset to full (replication is asynchronous, more on that in consistency explained with examples). For rate limiting I'm fine with that. For billing quotas I'd keep the count in the database instead.
The local fallback map grows with every key it sees while Redis is down. For a short outage that's ok; for a long one you would want an LRU there.
The whole thing including tests, the sliding window log script and the demo API is about 250 lines. If the API is a single instance only, use the in-process version and skip Redis.