Redis Lua scripting lets you run a sequence of commands on the server atomically — no other command runs in between, no race conditions, and the network round trips collapse to one. It is the primitive behind reliable rate limiters, distributed locks (Redlock building blocks), atomic counters with side effects, and any operation that needs read-then-write semantics on more than one key. This article covers EVAL, EVALSHA, the KEYS and ARGV contract, the replication implications, and the patterns that hold up under production load.
How to verify
# A trivial script
redis-cli EVAL "return 'hello'" 0
# Pass KEYS and ARGV
redis-cli EVAL "return redis.call('GET', KEYS[1])" 1 mykey
# Cache a script and execute by hash
SHA=$(redis-cli SCRIPT LOAD "return redis.call('GET', KEYS[1])")
echo "$SHA"
redis-cli EVALSHA "$SHA" 1 mykey
# Inspect cached scripts
redis-cli SCRIPT EXISTS "$SHA"
What’s happening
EVAL <script> <numkeys> <key1> <key2> ... <arg1> <arg2> ... sends a Lua script to the server. The script executes atomically — the Redis main thread runs it from start to finish without interleaving any other command. Inside the script, redis.call('GET', KEYS[1]) performs a Redis command, and the result is a Lua value that you can branch on, transform, and return.
Two argument arrays are passed:
KEYS— the keys the script will touch. Crucial for cluster routing: in a Redis Cluster, every key inKEYSmust hash to the same slot, and the script is sent to the node that owns that slot. Lying about which keys you touch (usingredis.call('GET', 'someotherkey')without listing it inKEYS) breaks cluster routing.ARGV— opaque arguments, treated as strings. Use these for non-key inputs: timestamps, TTLs, comparison values.
To avoid sending the script body on every call, SCRIPT LOAD returns a SHA1 of the script. EVALSHA <sha1> <numkeys> ... runs the cached script. If the cache has been cleared (e.g., after SCRIPT FLUSH or a server restart), EVALSHA returns NOSCRIPT and the client should fall back to EVAL and reload.
Replication: scripts replicate by sending the script and arguments to replicas, who re-execute. Redis 5+ supports redis.replicate_commands() which replicates the resulting commands instead — useful for scripts that touch non-deterministic state.
The procedure
-
Write a script. Atomic check-and-set with TTL — set a key only if it does not exist and stamp a TTL:
-- setnx-with-ttl.lua local current = redis.call('GET', KEYS[1]) if current == false then redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2]) return 1 else return 0 end -
Execute it inline with EVAL:
redis-cli --eval setnx-with-ttl.lua mylock , my-uuid-1234 30The comma separates
KEYSandARGV.mylockisKEYS[1],my-uuid-1234isARGV[1],30isARGV[2]. -
Cache the script for repeated use:
SHA=$(redis-cli SCRIPT LOAD "$(cat setnx-with-ttl.lua)") redis-cli EVALSHA "$SHA" 1 mylock my-uuid-1234 30 -
Implement a rate limiter (sliding-window counter, 100 requests per 60 seconds per user):
-- rate-limit.lua local key = KEYS[1] local limit = tonumber(ARGV[1]) local window = tonumber(ARGV[2]) local count = redis.call('INCR', key) if count == 1 then redis.call('EXPIRE', key, window) end if count > limit then return 0 end return 1redis-cli --eval rate-limit.lua user:42:rate , 100 60 -
Implement a safe lock release (only delete if the lock value matches the holder’s UUID):
-- release-lock.lua if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end -
Handle NOSCRIPT in the client. Pseudocode for a resilient call:
try: return r.evalsha(sha, 1, key, value, ttl) except redis.exceptions.NoScriptError: sha = r.script_load(script_body) return r.evalsha(sha, 1, key, value, ttl) -
For cluster deployments, ensure all keys hash to the same slot using curly-brace tags:
redis-cli -c --eval transfer.lua "balance:{tx7}:alice" "balance:{tx7}:bob" , 50
Common pitfalls
- A script that blocks the Redis main thread for more than 100 ms freezes every other client. Keep scripts short and bounded; never loop over
SCANinside a script. redis.call('GET', 'hardcoded-key')without listinghardcoded-keyinKEYSbreaks cluster routing — the script lies about what it touches. Always pass keys viaKEYS.- Returning a table from Lua with a
nilin the middle is treated as the end of the array. Convertnilto a sentinel likefalseor an empty string before returning. SCRIPT FLUSHclears the cache on the master but not on replicas in some older versions; checkSCRIPT EXISTSon both after a flush.- A script that uses
redis.replicate_commands()and modifies state viamath.random()produces different results on replicas — Redis 5+ is stricter about this, refusing such scripts unless they explicitly opt out of script replication.
In the engagements we run, every Lua script ships with a unit test that asserts the result of EVAL against a fresh fixture, a Prometheus counter for redis_slowlog entries tagged with the script SHA, and a documented cluster keying contract. We operate that under Managed Operations — and for more powerful server-side logic Redis 7 introduces Redis Functions which deserve a separate look.