Difficulty: Advanced
What are the advantages of running Lua scripts in Redis, and what should you watch out for? Write a script that does something atomically.
Lua scripts let you run multi-step logic inside the Redis server as a single atomic operation. While a script runs, no other command executes, so you get read-modify-write logic without race conditions, plus fewer network round trips because the whole sequence travels in one call. The catch is that a slow script blocks every other client, so scripts must be short and bounded.
INCR, EXPIRE and a comparison becomes one request instead of three. Across a Mumbai to Singapore link at 60 ms RTT, that matters.MULTI/EXEC queues commands but cannot branch on results. Lua can use if, loops and the return values of redis.call.EVAL script numkeys key1 ... arg1 ... sends the script text. Inside it, keys are in KEYS[1..n] and other values in ARGV[1..n].SCRIPT LOAD returns that SHA, and EVALSHA sha ... runs it without resending the body. If the cache was flushed (for example after a restart), you get NOSCRIPT and should fall back to EVAL. Most client libraries do this for you.FUNCTION LOAD, FCALL) are the recommended way to ship server-side logic. Unlike the script cache, functions are persisted and replicated, so they survive restarts.EVAL_RO and FCALL_RO run read-only scripts that can be routed to replicas.KEYS, never build key names inside the script. Redis Cluster uses KEYS to route the call, and all keys must hash to the same slot (use hash tags like {user:42}).redis.call raises an error that aborts the script; redis.pcall returns the error so you can handle it. Writes made before an error are not rolled back.A script that loops over a million elements freezes Redis for everyone. After busy-reply-threshold (formerly lua-time-limit, default 5000 ms) other clients start getting BUSY errors. You can stop a read-only script with SCRIPT KILL, but once a script has written data the only escape is SHUTDOWN NOSAVE, which loses data since the last save. Keep scripts O(1) or O(small N), and never use them for bulk scans.
| MULTI/EXEC | Lua script | |
|---|---|---|
| Atomic execution | Yes | Yes |
| Branch on a read value | No, needs WATCH and retry | Yes, with if/else |
| Round trips | Several commands pipelined | One call |
| Rollback on error | No | No |
| Risk | Optimistic retries under contention | Long script blocks server |
import Redis from 'ioredis';
const redis = new Redis();
// Decrement stock only if enough units remain.
// Returns remaining stock, or -1 if sold out.
redis.defineCommand('reserveStock', {
numberOfKeys: 1,
lua: `
local stock = tonumber(redis.call('GET', KEYS[1]) or '0')
local qty = tonumber(ARGV[1])
if stock < qty then
return -1
end
return redis.call('DECRBY', KEYS[1], qty)
`,
});
await redis.set('stock:sku:7781', 3);
console.log(await redis.reserveStock('stock:sku:7781', 2)); // 1
console.log(await redis.reserveStock('stock:sku:7781', 2)); // -1
ioredis loads the script and calls it with EVALSHA, falling back to EVAL on NOSCRIPT. No other client can change the stock between the GET and the DECRBY.
# Acquire: set only if absent, with a 30s expiry and a unique token
redis-cli SET lock:invoice:55 'tok-8f2a' NX PX 30000
# Release: delete only if the lock still holds our token
redis-cli EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock:invoice:55 tok-8f2a
Without the script, a slow client could delete a lock that already expired and was taken by someone else.
EVAL and EVALSHA, Atomic Scripts, KEYS and ARGV, Redis Functions, Script Blocking