17. Lua Scripting: Atomic Operations
Lua Scripting: Atomic Operations in Redis
Lua scripting enables atomic operations in Redis. Scripts run on the server, guaranteeing atomicity. They're ideal for complex operations that need to be atomic and efficient. This module covers Lua scripting, use cases, and best practices.
Lua scripts are executed atomically on the Redis server. They can access multiple keys and perform complex logic. Scripts are cached and efficient. Use Lua scripts for any multi-key operation that needs atomicity. Understanding Lua scripting unlocks advanced Redis capabilities and enables complex data patterns.
This module covers Lua script syntax, EVAL/EVALSHA commands, use cases, and best practices with comprehensive examples.
Writing Lua Scripts
Lua scripts are written in Lua and executed with EVAL or EVALSHA. Scripts have access to Redis commands via redis.call(). They can handle errors and complex logic. Scripts are cached and can be reused.
Lua scripts support variables, conditionals, loops, and error handling. Use redis.call() for Redis commands, redis.pcall() for non-failing calls. Use redis.error_reply() for error responses. Scripts are ideal for multi-key operations that need atomicity.
-- Atomic transfer script
-- KEYS[1]: from account, KEYS[2]: to account
-- ARGV[1]: amount
local from = redis.call('GET', KEYS[1])
if not from or tonumber(from) < tonumber(ARGV[1]) then
return redis.error_reply('Insufficient funds')
end
local amount = tonumber(ARGV[1])
redis.call('DECRBY', KEYS[1], amount)
redis.call('INCRBY', KEYS[2], amount)
return redis.call('GET', KEYS[1]) -- Return new balance
-- Atomic check-and-set
local key = KEYS[1]
local expected = ARGV[1]
local new_value = ARGV[2]
local current = redis.call('GET', key)
if current == expected then
redis.call('SET', key, new_value)
return 1
end
return 0
Using EVAL and EVALSHA
EVAL executes scripts. EVALSHA executes cached scripts. Scripts are cached after first execution. Use EVALSHA for performance. Redis caches scripts by SHA hash.
EVALSHA is the preferred way to execute scripts in production. The script is loaded once with SCRIPT LOAD, then executed with EVALSHA. This reduces network overhead. Redis caches scripts globally and persists them across connections.
// Execute Lua script with EVAL const script = ` local from = redis.call('GET', KEYS[1]) if not from or tonumber(from) < tonumber(ARGV[1]) then return redis.error_reply('Insufficient funds') end redis.call('DECRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[2], ARGV[1]) return redis.call('GET', KEYS[1]) `; // EVAL - execute script directly const result = await client.eval(script, { keys: ['account:1', 'account:2'], arguments: ['100'] }); // EVALSHA - execute cached script const sha = await client.scriptLoad(script); const resultCached = await client.evalSha(sha, { keys: ['account:1', 'account:2'], arguments: ['100'] });
Best Practices
Lua scripting best practices include using EVALSHA for performance, handling errors, keeping scripts short, and testing thoroughly. Use scripts for atomic operations. Keep scripts simple and focused. Test scripts with the --ldb flag. These practices ensure reliable scripts.
Scripts should be short and focused on one operation. Avoid complex logic that could take time — Redis is single-threaded, so scripts block other operations. Use pcall for error handling. Test scripts extensively before production. Document script behavior.
- Use EVALSHA: Cache scripts for better performance with SCRIPT LOAD.
- Error Handling: Handle errors with redis.error_reply and pcall.
- Short Scripts: Keep scripts focused on one operation.
- Testing: Test scripts with redis-cli --ldb for debugging.
- Atomicity: Use scripts for operations that need atomicity.
- Documentation: Document script behavior and requirements.
Knowledge Check
Ready to test your understanding of 17. Lua Scripting: Atomic Operations?