Video in progress

How do you build an API rate limiter with Redis?

The simplest is a fixed window: INCR rl:{user}:{minute}, set EXPIRE on the first INCR, and return 429 when the count goes over the limit. For more accuracy, use a sliding window with a Sorted Set, or a token bucket in Lua.

📖 Answer

A fixed window, made atomic with Lua:

local n = redis.call('INCR', KEYS[1])
if n == 1 then
  redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return n
long minute = Instant.now().getEpochSecond() / 60;
Long n = redis.execute(RATE_SCRIPT, List.of("rl:" + userId + ":" + minute), "60");
if (n > 100) throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);

If you call INCR and EXPIRE separately and the application crashes in between, the key has no expiry and the user is blocked forever. That's why it's a script.

The weakness of a fixed window is the boundary: 100 requests go through at 12:00:59 and another 100 at 12:01:00, so 200 in two seconds.

A sliding window log keeps each request in a Sorted Set with its timestamp: you clean out old entries with ZREMRANGEBYSCORE and check ZCARD. It's accurate, but costs memory per user proportional to the number of requests.

A token bucket stores "tokens left" and "last refill time" in the key; it's gentler on bursts. Ready-made options: Bucket4j's Redis backend, and RedisRateLimiter in Spring Cloud Gateway.

Decide in advance what to do when Redis is down: let requests through or block them.