Back to results for “Commands”
Redis › Rate Limiting with Redis

How do you implement a basic fixed window rate limiter using Redis's INCR and EXPIRE commands?

Beginner

Answer

You increment a counter key representing the current time window each time a request comes in, and set an expiration on that key only the first time it is created, so the counter automatically resets once the time window passes, letting you reject any request once the counter exceeds your configured limit within that window.
local count = redis.call('incr', KEYS[1])
if count == 1 then
  redis.call('expire', KEYS[1], 60)
end
return count <= 100
Real-world example A login endpoint limits attempts to five per minute per IP address using a simple fixed window counter, automatically resetting the count once each minute passes.

Common follow-ups: What is a known weakness of the fixed window approach near the boundary between two windows?;How do you handle a burst of requests right at the start of a new window?