Video in progress
How do you write a sliding window log rate limiter in Redis, and why should it be done with a Lua script?
-- KEYS[1] = rl:{userId}, ARGV: now_ms, window_ms, limit, request_id
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count >= limit then
return 0
end
redis.call('ZADD', key, now, ARGV[4])
redis.call('PEXPIRE', key, window)
return 1
For each user, the request times are stored in a sorted set: entries older than the window are removed, the rest are counted, and if the count is below the limit the new time is added. These steps must be atomic, otherwise parallel requests slip past the limit.
📖 Answer
The script runs in Redis as one atomic step — other commands can't get in between. If you did the same thing from Java with four separate commands, two instances could ZCARD at the same moment, both see "99, limit is 100", and both add — making 101.
Calling it from Java:
private final RedisScript<Long> script =
RedisScript.of(new ClassPathResource("ratelimit.lua"), Long.class);
boolean allow(String userId) {
long now = System.currentTimeMillis();
Long r = redis.execute(script, List.of("rl:{" + userId + "}"),
String.valueOf(now), "60000", "100", UUID.randomUUID().toString());
return r != null && r == 1L;
}
A few subtle points:
ARGV[4]must be unique — otherwise two requests in the same millisecond become a single element in the sorted set;- each instance supplies the time from its own clock; if the clock skew is large, using
redis.call('TIME')inside the Lua script is more accurate; {userId}is a hash tag — in Redis Cluster, all keys the script touches must be in a single slot.
The cost: one element is stored per request. For a user allowed 10,000 per minute, that's a set of 10,000 elements — expensive in memory and CPU. For large limits, a sliding window counter (a weighted sum of the current and previous window counters) or a token bucket is much cheaper, and the accuracy is good enough in practice.
Sign up to mark studied questions and save your progress.