Build the mental model
A Lua script runs multiple commands as one atomic server-side unit. Pass keys through KEYS and values through ARGV; declare every accessed key for cluster routing. Long scripts can block the server, so keep work bounded. Redis Functions package logic into named, persisted libraries.
Connect it to a real scenario
Implement a limited coupon claim that checks remaining stock, decrements it, and records the user in a claim set. Duplicate claims are no-ops and zero stock is rejected. On NOSCRIPT, load and retry, and record business outcome codes in metrics.
Try the working example
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return 2 end
local remaining = tonumber(redis.call('GET', KEYS[1]) or '0')
if remaining <= 0 then return 0 end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
return 1
-- KEYS: coupon:{42}:remaining, coupon:{42}:claimsThe script atomically returns 0 for sold out, 1 for claimed, or 2 for duplicate.5-minute try-it
Add success, blocked, and error outcome codes plus test cases to the rate-limit script.
One important caution
Do not run unbounded scans, loops, or external calls in Lua; the server event loop can be blocked.
Redis — Scripting with Lua — Redis