Writing
Fullstack English

Rate Limiting With Redis: Sliding Windows in 20 Lines

Fixed windows burst, token buckets confuse, sliding window counters hit the sweet spot. A production rate limiter with Lua atomicity.

  • Published
  • 1 min read
On this page3 sections
  1. Why fixed windows leak
  2. Redis implementation
  3. The parts people forget

The day your API gets popular is the day one caller takes down everyone else. Rate limiting is the fence - and where you put the counter matters more than the algorithm’s name.

Why fixed windows leak

“100 requests per minute” counted per calendar minute allows 200 requests in two seconds - 100 at 11:59:59 and 100 at 12:00:00. Sliding window counters fix this by weighting the previous window:

text
count = curr_window + prev_window * overlap_fraction

Redis implementation

Atomic via a tiny Lua script (no read-modify-write race):

lua
local curr = redis.call('INCR', KEYS[1])
if curr == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1] * 2) end
local prev = tonumber(redis.call('GET', KEYS[2]) or '0')
local weighted = curr + prev * tonumber(ARGV[2])
return weighted

Key by user:{id}:{window_ts}. Two keys per user, self-expiring - no cleanup job.

The parts people forget

  • Return 429 with Retry-After - well-behaved clients will actually honor it.
  • Separate limits per route class: login endpoints get strict ones (credential stuffing), read endpoints get generous ones.
  • Fail open if Redis is down for reads-only traffic, fail closed for auth attempts. Availability and security disagree; decide per route, on purpose.