Redis Lua scripts
How lazy-layers-cache batches Redis reads, writes and deletes into Lua scripts, and how to run Lua scripts of your own on cache keys with cache.runScript.
lazy-layers-cache talks to Redis through Lua scripts. A script runs on the Redis server as one step, so a read and its TTL, or a write and the fence that stops an older load from overwriting it, cannot be split by another client. Since 9.0, calls made together share one script, and you can run Lua scripts of your own on cache keys.
Batch scripts: one script per 64 keys
When many reads, writes or deletes are issued in the same tick (the keys of a getMany, a setMany, or a burst of requests for different keys), RedisStore queues them and sends one Lua script per 64 keys or 1 MiB of payload, instead of one script per key. A lone call still runs its own single-key script, so nothing changes for a quiet server.
Measured with benchmarks/redis-batch.mjs against a local Redis (BENCHMARKS.md), median of five rounds:
| 500 keys | Script calls, off → on | Redis CPU ms, off → on | Wall ms, off → on |
|---|---|---|---|
setMany | 500 → 8 | 1.0 → 0.8 | 6.5 → 4.0 |
getMany, values in Redis | 500 → 8 | 0.9 → 0.6 | 4.9 → 3.0 |
deleteMany | 500 → 8 | 0.6 → 0.4 | 4.0 → 3.0 |
invalidateByPattern | 500 → 8 | 1.3 → 0.5 | 36.3 → 1.9 |
The call count is what Redis saw and does not depend on the machine. Batched calls were already pipelined on one connection, so most wall times move less than the count; a pattern delete moves most, because it used to wait for each key's script before sending the next.
What stays the same:
- Order. Writes and deletes of one key land in the order they were made, and writes queued in a tick are sent before reads queued in it.
- Fencing. A batched write deletes the key's lease, exactly as a single write does, so a load still in flight cannot overwrite it.
- Reply size. One batched read returns at most about 8 MiB; keys past that are read on their own.
- Blocking. Redis runs one script at a time, so
maxKeysalso bounds how long one script holds Redis. 64 small keys take well under a millisecond.
const cache = await setupCache({
redis: {
store: {
batchScripts: { maxKeys: 64, maxBytes: 1024 * 1024 }, // the defaults
// batchScripts: false, // one script per call
},
},
})Batching applies to the v2 key layout on standalone Redis and Sentinel. On Redis Cluster each cache key has its own hash slot and a script can only touch one slot, so every call runs its own script there.
Run Lua scripts of your own
Register scripts by name in RedisStore's scripts option, then run them with cache.runScript(name, keys, args). The cache maps your keys to their Redis keys, so a script never has to know the prefix, the namespace or the hash tags.
Inside the script:
| Name | Holds |
|---|---|
KEYS[1] to KEYS[n] | The Redis keys of the n cache keys you passed, in order |
KEYS[n + 1] to KEYS[2n] | Their lease keys, in the same order |
ARGV | Your arguments, as strings |
Values are stored in the cache's own encoding (MessagePack, possibly compressed), so a script is the right tool for TTLs, existence checks and whole-record moves, not for editing a value in place. Read and write values through the cache.
Extend the TTL of keys that exist
const cache = await setupCache({
namespace: 'shop',
redis: {
store: {
scripts: {
touch: {
lua: `
local out = {}
for i = 1, #KEYS / 2 do
out[i] = redis.call("pexpire", KEYS[i], ARGV[1])
end
return out
`,
},
},
},
},
})
const touched = await cache.runScript('touch', ['cart:1', 'cart:2'], [600_000])
// [1, 0]: cart:1 had 10 more minutes added, cart:2 was not in RedisPEXPIRE changes Redis, so this script is not readOnly. Mark a script readOnly: true only when it calls nothing but read commands; ioredis may then send it to a replica.
Change keys, and keep every server in step
A script that changes the cache's keys must say so with writes: true. The cache then:
- stops loads already in flight, on this server and on others, from writing over the change (the script deletes the keys' leases after it runs);
- drops the keys from this server's memory once the script returns, even if it failed;
- tells peers over the event bus to drop their copies, so their next read sees what the script left in Redis.
scripts: {
// Remove a key only if it expires within ARGV[1] ms.
dropIfExpiring: {
writes: true,
lua: `
local ttl = redis.call("pttl", KEYS[1])
if ttl >= 0 and ttl < tonumber(ARGV[1]) then
redis.call("del", KEYS[1])
return 1
end
return 0
`,
},
}
await cache.runScript('dropIfExpiring', ['report:daily'], [5_000])Rules
- A script name starts with a letter and holds only letters, digits and
_. It is registered with ioredis under a prefixed name, so it cannot collide with the cache's own scripts. - Errors reach the caller;
runScriptnever fails open. runScriptneeds an L2 that runs scripts, such asRedisStore; with any other L2 it throws aTypeError.- On Redis Cluster, pass one cache key per call: each key and its lease share a slot, but two cache keys usually do not.
Where to next
- Configuration: RedisStore options lists
batchScriptsandscripts. - Batches, namespaces and freshness covers
getMany,setManyandgetOrSetMany. - Stampede protection explains the leases a writing script fences.
Questions
Why does a cache use Lua scripts at all?
Some steps must happen together on the Redis server. Reading a value with its remaining TTL, writing a value while fencing a load still in flight, and taking or releasing a lease are each one Lua script, so no other client can run a command between their parts. lazy-layers-cache calls every script by its hash (EVALSHA) and sends the source only when Redis has not seen it yet.
What are batch scripts?
Calls made in the same tick, such as the 500 reads of a getMany or a burst of requests, are handed to one Lua script per 64 keys instead of one script each. In a recorded run, 500 reads, writes or deletes made 8 script calls instead of 500 and used up to 2.6 times less Redis CPU, and a 500-key pattern delete went from 36 ms to 1.9 ms.
Can I run my own Lua script on cached keys?
Yes. Give it a name in RedisStore's scripts option and call cache.runScript(name, keys, args). The script receives the Redis keys of the cache keys you pass, then their lease keys. Mark it writes: true if it changes those keys, and the cache fences loads in flight and drops the keys from every server's memory afterwards.
Do batch scripts work with Redis Cluster?
Batching is off on Redis Cluster, because every cache key has its own hash slot and a script can only touch keys in one slot. Each call there runs its own script, as before. On standalone Redis and Sentinel, batching is on by default.