// Without Lua
App → Redis → App → Redis (multiple network calls)
// With Lua:
App → Redis (script runs fully inside Redis)
Use case: API rate limiting
You want max N requests per minute.
Flow:
INCR ip:1.2.3.4
EXPIRE ip:1.2.3.4 60
INCR returns 1 → set EXPIRE to 60sINCR increments → you check <= MAXAtomicity concern:
INCR → network lag → EXPIRE missed → key may never expireSolution:
INCR + EXPIRE atomically in one stepExample Lua script:
local current = redis.call("INCR", KEYS[1])
if current ==1 then
redis.call("EXPIRE", KEYS[1], ARGV[1])
end
return current