Atomic Operations with Lua Scripts
Advanced15 minTrending
Execute complex multi-step operations atomically in Redis using server-side Lua scripting to eliminate race conditions.
Prerequisites
- -Redis installed and running
- -Basic understanding of Lua syntax
Steps
1
Run an inline Lua script
Execute a simple Lua script that sets and returns a value atomically.
$ redis-cli EVAL "redis.call('SET', KEYS[1], ARGV[1]) return redis.call('GET', KEYS[1])" 1 mykey hello
KEYS[1] is the first key argument, ARGV[1] is the first non-key argument. Always pass keys via KEYS for cluster compatibility.
2
Atomic compare-and-swap
Implement a compare-and-swap operation that only updates a key if it matches an expected value.
$ redis-cli EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('SET', KEYS[1], ARGV[2]) return 1 else return 0 end" 1 mykey hello world
3
Load a script for reuse
Load a Lua script into Redis and get its SHA hash for repeated execution without resending the script body.
$ redis-cli SCRIPT LOAD "redis.call('SET', KEYS[1], ARGV[1]) redis.call('EXPIRE', KEYS[1], ARGV[2]) return 1"
Save the returned SHA hash and use EVALSHA to call the script by hash, reducing bandwidth.
4
Execute a loaded script by SHA
Run a previously loaded script using its SHA hash.
$ redis-cli EVALSHA <sha-hash> 1 cached:item '{"data":"value"}' 3600
5
Atomic rate limiter in Lua
Implement a precise rate limiter as a single atomic Lua script.
$ redis-cli EVAL "local count = redis.call('INCR', KEYS[1]) if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[2]) end if count > tonumber(ARGV[1]) then return 0 else return 1 end" 1 ratelimit:user1001 10 60
Full Script
FAQ
Discussion
Loading comments...