Redis › Lua Scripting
How would you write a Lua script to implement an atomic rate limiter that checks and increments a request counter in a single operation?
AdvancedAnswer
You write a script that increments a counter for the specific rate limited key, sets an expiration on it only if this is the very first request within the current time window, checks if the incremented count exceeds your configured limit, and returns whether the current request should be allowed or rejected, all as a single atomic operation that avoids race conditions between the check and the increment.
local current = redis.call('incr', KEYS[1])
if current == 1 then
redis.call('expire', KEYS[1], ARGV[1])
end
if current > tonumber(ARGV[2]) then
return 0
end
return 1Real-world example An API gateway uses this kind of atomic Lua script to enforce a rate limit of one hundred requests per minute per customer, guaranteeing accurate enforcement even under extremely high concurrent request volume.