MULTI/EXEC versus Lua scripts
A Redis transaction batches commands; a Lua script is the only way to branch on a value atomically.
Open this lesson in the learning hubKey points
MULTIqueues commands andEXECruns them with no other client interleaved between them.- There is no rollback: if one queued command fails at runtime, the others still applied and
EXECreports per-command errors. - A command rejected at queue time, such as a wrong arity, aborts the whole transaction at
EXECsince Redis 2.6.5. - You cannot read a reply mid transaction, so any if-then-else must be done with
WATCHand a retry loop. WATCHgives optimistic locking: if a watched key changed,EXECreturns nil and you retry from the top.EVALruns a Lua script atomically and can branch on values, which is why compare-and-delete is always a script.
Example
EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
end" 1 lock:order:991 my-token-4f2a
SCRIPT LOAD "return redis.call('INCRBY', KEYS[1], ARGV[1])"
# -> "a1b2c3..." then call it cheaply with EVALSHA a1b2c3... 1 counter 5
MULTI groups commands, WATCH detects interference, and Lua is the only way to decide atomically.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Redis Course course, and every lesson in it is listed on the Redis Course contents page.