Lua Scripting
EVAL, EVALSHA, and atomic multi-command operations
Skills taught: redis.lua
Why Atomicity Matters
Consider a rate limiter: GET counter, increment it, check the limit, SET it back. Between the GET and SET, another request could increment the counter too — causing a race condition. Lua scripts execute as a single atomic unit, eliminating this problem.
# EVAL script numkeys [key ...] [arg ...]
# KEYS[1] = 'counter:page1', ARGV[1] = '1'
EVAL "
local val = redis.call('GET', KEYS[1])
if not val then val = 0 end
local newval = tonumber(val) + tonumber(ARGV[1])
redis.call('SET', KEYS[1], newval)
return newval
" 1 counter:page1 1
# Returns the new value: (integer) 1
KEYS and ARGV
Scripts receive two arrays: KEYS for Redis key names, and ARGV for other arguments. Always pass key names through KEYS — this is required for Redis Cluster to route correctly.
import Redis from 'ioredis';
const redis = new Redis();
// Script: get a value and multiply it
const script = `
local val = redis.call('GET', KEYS[1])
if not val then return 0 end
return tonumber(val) * tonumber(ARGV[1])
`;
// EVAL: numkeys=1, key='counter:hits', argv='10'
const result = await redis.eval(script, 1, 'counter:hits', '10');
console.log(result); // current value * 10
// Cache script by SHA for efficiency
const sha = await redis.script('LOAD', script);
// Use EVALSHA on subsequent calls (no retransmit of script text)
const result2 = await redis.evalsha(sha, 1, 'counter:hits', '10');
Real-World: Atomic Rate Limiter
// Atomic rate limiter: increment counter, set expiry if first request
const rateLimitScript = `
local current = redis.call('INCR', KEYS[1])
if current == 1 then
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
end
return current
`;
async function checkRateLimit(userId, limit = 100, windowSecs = 60) {
const key = `rate:${userId}:${Math.floor(Date.now() / (windowSecs * 1000))}`;
const count = await redis.eval(rateLimitScript, 1, key, windowSecs);
return count > limit; // true = rate limited
}
Real-World: Distributed Lock
// Acquire lock: SET NX EX (native command, no Lua needed for acquire)
async function acquireLock(resource, ttlSecs = 30) {
const token = crypto.randomUUID();
const acquired = await redis.set(
`lock:${resource}`, token,
'NX', 'EX', ttlSecs
);
return acquired ? token : null;
}
// Release lock: MUST check token matches before deleting (Lua!)
const releaseLockScript = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
end
`;
async function releaseLock(resource, token) {
// Atomic check-and-delete: only delete if token matches
// Without Lua, another process could acquire the lock between our GET and DEL
return redis.eval(releaseLockScript, 1, `lock:${resource}`, token);
}
Redis Functions (Modern Alternative)
Redis 7.0 introduced Redis Functions as a named, persistent alternative to EVAL scripts. Functions survive restarts and are stored in RDB/AOF.
# Load a named function library
FUNCTION LOAD "#!lua name=mylib\nredis.register_function('myfunc', function(keys, args) return redis.call('GET', keys[1]) end)"
# Call the function
FCALL myfunc 1 mykey
# List functions
FUNCTION LIST
# Delete a library
FUNCTION DELETE mylib
Tip: Scripts run atomically and block the entire Redis server. Keep Lua scripts short — aim for microseconds, not milliseconds. Any Lua that takes >5 seconds triggers a warning and can be killed with SCRIPT KILL.
Warning: Always declare all Redis key names in the KEYS argument. Hardcoding keys inside the script breaks Redis Cluster routing — the cluster can't determine which shard to route to.
Frequently Asked Questions
What is EVALSHA?
EVALSHA runs a previously loaded script by its SHA1 hash, avoiding resending the script text on every call. Use SCRIPT LOAD to cache the script first.
How do I handle errors in Lua scripts?
Use redis.pcall() instead of redis.call() to catch errors — it returns a Lua table with an 'err' field instead of raising. redis.call() propagates errors to the caller.
What is the time limit for Lua scripts?
5 seconds by default (lua-time-limit in redis.conf). After that, Redis logs a warning but lets the script continue. Use SCRIPT KILL to terminate a running script (only works if no writes have been done yet).