Back to results for “Rate Limiting with Redis”
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?

Advanced

Answer

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 1
Real-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.

Common follow-ups: Why would this rate limiting logic be unsafe if implemented as several separate Redis commands instead of one script?;How do you adjust this script to support a sliding window rather than a fixed window?