Redis Rate Limiting
A rate limiter caps how often a client may do something: 100 API requests per minute per key, 5 login attempts per 15 minutes per account, 1 password-reset email per minute. Redis is the standard place to keep these counters, because every web server must see the same numbers and the atomic commands make counting race-free.
Fixed window counter
The simplest limiter counts requests in fixed time windows. The key contains the window number, for example the current minute, and expires when the window is over:
key = ratelimit:{user}:{unix_time // 60}
INCR key -> number of requests in this minute
EXPIRE key 60 NX -> set the expiry only on the first request
allow if the count <= limitHere user 7 sends four requests in minute 29346000 with a limit of 3:
INCR ratelimit:user:7:29346000
EXPIRE ratelimit:user:7:29346000 60 NX
INCR ratelimit:user:7:29346000
EXPIRE ratelimit:user:7:29346000 60 NX
INCR ratelimit:user:7:29346000
INCR ratelimit:user:7:29346000
TTL ratelimit:user:7:29346000redis> INCR ratelimit:user:7:29346000
(integer) 1
redis> EXPIRE ratelimit:user:7:29346000 60 NX
(integer) 1
redis> INCR ratelimit:user:7:29346000
(integer) 2
redis> EXPIRE ratelimit:user:7:29346000 60 NX
(integer) 0
redis> INCR ratelimit:user:7:29346000
(integer) 3
redis> INCR ratelimit:user:7:29346000
(integer) 4
redis> TTL ratelimit:user:7:29346000
(integer) 60
The fourth request saw a count of 4 and would be rejected with HTTP 429 Too Many Requests. Note that EXPIRE ... NX returned 0 the second time, so later requests do not keep pushing the expiry back.
To make "increment and set the expiry" a single round trip, send both in a transaction or a script:
EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rl:ip:10.0.0.1:29346000 60
EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rl:ip:10.0.0.1:29346000 60
TTL rl:ip:10.0.0.1:29346000redis> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rl:ip:10.0.0.1:29346000 60
(integer) 1
redis> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rl:ip:10.0.0.1:29346000 60
(integer) 2
redis> TTL rl:ip:10.0.0.1:29346000
(integer) 60
Weakness: a client can send limit requests at the end of one window and limit more at the start of the next, so twice the limit within a few seconds.
Sliding window log
A sorted set stores one member per request, scored by its timestamp. For each new request:
- Remove entries older than the window (
ZREMRANGEBYSCORE). - Count the remaining entries (
ZCARD). - If under the limit, add the request (
ZADD).
With a 60-second window and a limit of 3, requests arrive at t = 100, 110, 120, 130 and 165 seconds. (To keep the transcript short, the clean-up and count before requests 2 and 3 are left out; they would find 1 and 2 entries.)
ZREMRANGEBYSCORE rl:log:user:7 -inf 40
ZCARD rl:log:user:7
ZADD rl:log:user:7 100 req:1
ZADD rl:log:user:7 110 req:2
ZADD rl:log:user:7 120 req:3
ZREMRANGEBYSCORE rl:log:user:7 -inf 70
ZCARD rl:log:user:7
ZREMRANGEBYSCORE rl:log:user:7 -inf 105
ZCARD rl:log:user:7
ZADD rl:log:user:7 165 req:5
ZRANGE rl:log:user:7 0 -1 WITHSCORESredis> ZREMRANGEBYSCORE rl:log:user:7 -inf 40
(integer) 0
redis> ZCARD rl:log:user:7
(integer) 0
redis> ZADD rl:log:user:7 100 req:1
(integer) 1
redis> ZADD rl:log:user:7 110 req:2
(integer) 1
redis> ZADD rl:log:user:7 120 req:3
(integer) 1
redis> ZREMRANGEBYSCORE rl:log:user:7 -inf 70
(integer) 0
redis> ZCARD rl:log:user:7
(integer) 3
redis> ZREMRANGEBYSCORE rl:log:user:7 -inf 105
(integer) 1
redis> ZCARD rl:log:user:7
(integer) 2
redis> ZADD rl:log:user:7 165 req:5
(integer) 1
redis> ZRANGE rl:log:user:7 0 -1 WITHSCORES
1) "req:2"
2) "110"
3) "req:3"
4) "120"
5) "req:5"
6) "165"
At t = 130 the window (70, 130] already contains 3 requests, so request 4 is rejected and not added. At t = 165 the window starts at 105, req:1 is removed, the count is 2, and request 5 is allowed. This is exact, but it stores one entry per request; in practice the three steps run in a Lua script so that they are atomic.
Token bucket
A token bucket allows short bursts while enforcing an average rate. The bucket holds up to capacity tokens and refills at rate tokens per second; each request takes one token. Only two numbers per client are stored (tokens and the last refill time), typically in a hash, and the logic runs in a Lua script. Here is the same algorithm in Python with explicit timestamps, so you can see its behaviour:
def make_bucket(capacity, rate):
return {"tokens": float(capacity), "ts": 0.0, "capacity": capacity, "rate": rate}
def allow(bucket, now):
elapsed = now - bucket["ts"]
bucket["tokens"] = min(bucket["capacity"], bucket["tokens"] + elapsed * bucket["rate"])
bucket["ts"] = now
if bucket["tokens"] >= 1:
bucket["tokens"] -= 1
return True
return False
bucket = make_bucket(capacity=3, rate=0.5) # bursts of 3, then 1 request every 2 s
for now in [0, 0.1, 0.2, 0.3, 1.0, 2.5, 3.0, 9.0, 9.1, 9.2, 9.3]:
ok = allow(bucket, now)
print(f"t={now:>4}s {'allowed' if ok else 'REJECTED':<8} tokens left {bucket['tokens']:.2f}")t= 0s allowed tokens left 2.00
t= 0.1s allowed tokens left 1.05
t= 0.2s allowed tokens left 0.10
t= 0.3s REJECTED tokens left 0.15
t= 1.0s REJECTED tokens left 0.50
t= 2.5s allowed tokens left 0.25
t= 3.0s REJECTED tokens left 0.50
t= 9.0s allowed tokens left 2.00
t= 9.1s allowed tokens left 1.05
t= 9.2s allowed tokens left 0.10
t= 9.3s REJECTED tokens left 0.15
The first three requests use the burst, the fourth is rejected, and afterwards tokens come back at one every two seconds. After a long pause (t = 9) the bucket is full again, but never fuller than its capacity.
The Redis version stores the bucket in a hash and runs the same arithmetic in Lua:
-- KEYS[1] = bucket key, ARGV = capacity, rate (tokens/s), now (seconds)
local capacity, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = 0
if tokens >= 1 then tokens = tokens - 1; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'ts', tostring(now))
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
return allowedChoosing an algorithm
| Algorithm | Memory per client | Accuracy | Bursts |
|---|---|---|---|
| Fixed window | 1 counter | up to 2× at window edges | yes, at edges |
| Sliding window log | 1 entry per request | exact | no |
| Sliding window counter (two fixed windows, weighted) | 2 counters | close | small |
| Token bucket | 2 numbers | exact average rate | yes, up to capacity |
Whatever you choose, send the client useful headers (Retry-After, X-RateLimit-Remaining) and limit by the right identity: API key or user ID, with IP address only as a fallback.
Test yourself
Why does a fixed-window limiter use EXPIRE key 60 NX instead of a plain EXPIRE on every request?
- NX is faster
- So that later requests do not push the expiry back and the window really ends
- NX deletes the key
- EXPIRE without NX is not allowed
Which Redis type stores the request timestamps in a sliding-window log?
- List
- Sorted set
- Bitmap
- HyperLogLog
A token bucket has capacity 10 and refills 1 token per second. A client was idle for an hour. How many requests can it make instantly?
- 1
- 10
- 3600
- Unlimited