"Allow 100 requests per minute per API key" sounds like a two-line Redis job: INCR a counter and check it. Then you notice bursts of 200 requests getting through at the minute boundary, counters that never expire, and race conditions under load. Here are the common rate-limiting patterns in Redis, what each one gets wrong, and how to implement it correctly.
Pattern 1: fixed window counter
Count requests in the current window (for example the current minute):
key = ratelimit:{apiKey}:{unix_minute}
INCR key
EXPIRE key 60 NX -- set the TTL only on first creation (Redis 7.0+)
-> if the count > 100: reject
Atomic, in one round trip with a pipeline or MULTI:
const key = `rl:${apiKey}:${Math.floor(Date.now() / 60000)}`;
const [count] = await redis.multi().incr(key).expire(key, 60, "NX").exec();
if (count > 100) return reject();
- The
EXPIRE … NXflag (or checkingcount === 1before setting the TTL on older versions) prevents immortal counters. If youINCRwithout ever setting a TTL, the key never expires. - Weakness: a client can send 100 requests at 12:00:59 and 100 more at 12:01:00, which is 200 in two seconds. For many APIs that's acceptable, and it's the cheapest option (one small key per client per window).
Pattern 2: sliding window log
Store a timestamp per request in a sorted set, and count only the last 60 seconds:
ZREMRANGEBYSCORE key 0 (now - 60000)
ZADD key now requestId
ZCARD key
EXPIRE key 60
It's exact, with no boundary bursts. But it stores one entry per request, so memory grows with the limit (a limit of 10,000/min means 10,000 entries per client). Use it for low limits, such as login attempts.
Pattern 3: sliding window counter (a good default)
Keep fixed-window counters, but weight the previous window by how much of it still overlaps the sliding window:
estimate = current_count + previous_count × (1 − elapsed_fraction_of_current_window)
At 15 seconds into a minute, 75% of the previous minute's count still counts. It uses two small keys per client and smooths out the boundary burst, with a small approximation. Cloudflare has described using this approach at very large scale.
Pattern 4: token bucket (allows controlled bursts)
Each client has a bucket of up to N tokens that refills at R tokens per second, and each request takes one token. Implement it in Lua, so reading, refilling and taking tokens is atomic:
-- KEYS[1] = bucket key; ARGV = capacity, refill_per_sec, now_ms, cost
local cap, rate, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000))
return allowed and 1 or 0
Pass the current time from the application, or use redis.call('TIME') inside the script so every client uses Redis's clock. It suits APIs that want to allow short bursts while enforcing an average rate.
Getting the details right
- Atomicity: "read, check, then write" in separate commands races under concurrency. Use
INCR,MULTI/pipelines, or Lua. - Redis Cluster: keys used together in one script must be in the same hash slot. Use hash tags:
rl:{apiKey}:currentandrl:{apiKey}:previous. - Tell the client what happened: return
429 Too Many RequestswithRetry-AfterandRateLimit-*headers. - Decide what happens when Redis is down: allowing requests (fail open) keeps the API up; rejecting them (fail closed) protects the backend. Choose per endpoint, and put a timeout on the Redis call.
- Pick the right key: API key or user ID for authenticated traffic, IP address (or subnet) for anonymous traffic, and separate limits per endpoint class.
- Don't reinvent it if you don't need to: API gateways, reverse proxies and libraries (for example
rate-limiter-flexible,redis-cell) implement these patterns and have been tested.
Checklist
- Fixed window (
INCR+EXPIRE NX) is simple and cheap, but allows boundary bursts. - Sliding log (sorted set) is exact but memory-hungry; the sliding window counter is a good default.
- Token bucket in Lua allows controlled bursts with atomic updates.
- Keep operations atomic, use hash tags in Cluster, return 429 with headers, and choose fail-open or fail-closed deliberately.
Get the weekly commit
New database deep dives every week.
