Lua scripts in Redis run all commands together without interruption. This means they act like one single step, so no other commands can run in the middle.
0
0
Why Lua scripts enable atomicity in Redis
Introduction
When you want to update multiple keys in Redis and ensure no other changes happen between those updates.
When you need to check a value and then change it only if it meets a condition, all at once.
When you want to avoid race conditions where two clients try to change data at the same time.
When you want to perform a complex operation that must not be split into parts.
When you want to keep your data consistent without using locks.
Syntax
Redis
EVAL script numkeys key [key ...] arg [arg ...]
The entire Lua script runs as one atomic operation in Redis.
numkeys tells Redis how many keys the script will access.
Examples
This script sets the value of 'mykey' to 'myvalue' atomically.
Redis
EVAL "return redis.call('set', KEYS[1], ARGV[1])" 1 mykey myvalue
This script changes 'mykey' from 'oldval' to 'newval' only if the current value is 'oldval'.
Redis
EVAL "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('set', KEYS[1], ARGV[2]) else return 0 end" 1 mykey oldval newval
Sample Program
This script checks if the key 'counter' has the value '10'. If yes, it sets it to '20'. Otherwise, it does nothing. The whole check and set happen together without interruption.
Redis
EVAL "local current = redis.call('get', KEYS[1]); if current == ARGV[1] then redis.call('set', KEYS[1], ARGV[2]); return 'Updated' else return 'Not updated' end" 1 counter 10 20
OutputSuccess
Important Notes
Lua scripts run atomically, so no other Redis command can run while the script is executing.
This atomicity helps prevent data conflicts in multi-client environments.
Keep Lua scripts short and fast to avoid blocking Redis for too long.
Summary
Lua scripts in Redis run as one single, uninterruptible operation.
This ensures data stays consistent and safe from race conditions.
Use Lua scripts when you need to do multiple related commands together safely.