Back to results for “Distributed Locks with Redis”
Redis › Transactions

When would you choose a Lua script over a MULTI and EXEC transaction to achieve atomicity in Redis?

Advanced

Answer

A Lua script is often a better choice when your atomic operation needs conditional logic based on values read partway through, since the entire script runs as a single atomic unit on the server with full access to intermediate results, whereas a plain transaction only queues commands blindly without letting you branch based on values retrieved earlier in the same transaction.
EVAL "local val = redis.call('GET', KEYS[1]) if val == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 mykey expected_value
Real-world example A distributed locking system uses a Lua script instead of a plain transaction to atomically check that a lock's value matches the expected owner before deleting it, something a simple MULTI and EXEC sequence cannot express.

Common follow-ups: What are the performance differences between Lua scripts and transactions for simple use cases?;Can a Lua script call WATCH internally?