MULTI/EXEC versus Lua scripts

Redis Course · lesson 8 of 19 · 5 min read

A Redis transaction batches commands; a Lua script is the only way to branch on a value atomically.

Open this lesson in the learning hub

Key points

  • MULTI queues commands and EXEC runs them with no other client interleaved between them.
  • There is no rollback: if one queued command fails at runtime, the others still applied and EXEC reports per-command errors.
  • A command rejected at queue time, such as a wrong arity, aborts the whole transaction at EXEC since Redis 2.6.5.
  • You cannot read a reply mid transaction, so any if-then-else must be done with WATCH and a retry loop.
  • WATCH gives optimistic locking: if a watched key changed, EXEC returns nil and you retry from the top.
  • EVAL runs 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.