Rate Limiting with Lua
Implement sliding window rate limiters atomically in Redis Lua.
Why Redis for Rate Limiting?
Redis provides atomic operations, in-memory speed, and shared state across multiple application servers — making it ideal for distributed rate limiting.
Simple Fixed Window Counter
Count requests per time window using INCR and EXPIRE.
EVAL "
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local count = redis.call('INCR', key)
if count == 1 then
redis.call('EXPIRE', key, window)
end
if count > limit then
return 0 -- rejected
end
return 1 -- allowed
" 1 rate:user:123 100 60All lessons in this course
- EVAL and Redis Lua Environment
- Atomic Operations and Transactions
- Rate Limiting with Lua
- SCRIPT LOAD and EVALSHA