Lua Scripting & Functions
Server-side atomic logic with EVAL and FUNCTION, and its dangers
Lua scripts run inside Redis, atomically: while a script runs, no other command does. That lets you read, decide, and write in one step, with no round trips and no retry loops. It's how the token bucket and the lock release in this module work.
EVAL
EVAL "return redis.call('INCRBY', KEYS[1], ARGV[1])" 1 app:counter 5
# script numkeys keys... args...KEYS[]holds the key names the script touches. Always pass keys this way, never build key names inside the script: Redis Cluster usesKEYSto route the script to the right node, and ACLs check them.ARGV[]holds everything else.redis.callraises an error on failure (aborting the script);redis.pcallreturns the error so the script can handle it.
EVALSHA and script caching
Sending the full script text every time wastes bandwidth. Load it once, then call it by its SHA1:
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
"d3c21d0c2b9ca22f82737626a27bcaf5d288f99f"
EVALSHA d3c21d0c2b9ca22f82737626a27bcaf5d288f99f 1 app:greetingClient libraries do this automatically: redis-py's register_script
(used in the labs) tries EVALSHA and falls back to EVAL if the
server returns NOSCRIPT, which happens after a restart or failover
because the script cache isn't persisted.
Example: check balance and debit
The thing MULTI alone can't do, in one atomic step:
local bal = tonumber(redis.call('GET', KEYS[1]) or '0')
local amt = tonumber(ARGV[1])
if bal < amt then
return redis.error_reply('INSUFFICIENT_FUNDS')
end
return redis.call('DECRBY', KEYS[1], amt)No WATCH, no retries, no race, no matter how many clients call it at
once.
Functions
Since Redis 7, Functions are the managed way to keep server-side
code. A library of functions is loaded once, gets a name, is
persisted in RDB/AOF, and is replicated, unlike EVAL scripts:
FUNCTION LOAD "#!lua name=applib
redis.register_function('debit', function(keys, args)
local bal = tonumber(redis.call('GET', keys[1]) or '0')
local amt = tonumber(args[1])
if bal < amt then return redis.error_reply('INSUFFICIENT_FUNDS') end
return redis.call('DECRBY', keys[1], amt)
end)"
SET app:balance 100
FCALL debit 1 app:balance 30 # 70
FCALL debit 1 app:balance 500 # (error) INSUFFICIENT_FUNDS
FUNCTION LIST
FUNCTION DELETE applibEVAL scripts | Functions | |
|---|---|---|
| Lives in | The client's code | The server, named |
| Survives restart | No (cache only) | Yes (RDB/AOF) |
| Replicated | Effects are | The library itself is |
| Deployment | With the app | Separately: FUNCTION LOAD REPLACE |
Use Functions for shared logic many services call; EVAL with
register_script is fine for logic owned by one app.
The danger: blocking the server
A script is atomic because it blocks everything while it runs. A
script that loops over a million keys freezes Redis just like KEYS *.
A script that has already performed a write can't be killed, because
stopping it halfway would break atomicity. Your options are to wait or
to SHUTDOWN NOSAVE, losing every write since the last save. Keep
scripts short and bounded: O(1) or O(log N) work, a handful of keys,
no loops over unbounded data.
Rules for scripts
- Pass every key in
KEYS; never compute key names inside the script. - In Cluster, all of a script's keys must hash to the same slot (use hash tags).
- Keep them short. Microseconds, not milliseconds.
- Make them deterministic: Redis 7+ replicates the effects of scripts, but non-determinism still makes them hard to reason about.
- Don't use them to work around a bad data model. If you need a 200-line script, the data probably belongs in a different shape or a different database.
Lab
- Load the
applibfunction and calldebituntil it fails. - Restart Redis (
docker restart redis) and runFUNCTION LIST. The function survived. TryEVALSHAwith an earlier script's SHA: it didn't (NOSCRIPT). - Run a deliberately slow script in one terminal,
EVAL "local i=0 while i < 3e8 do i=i+1 end return i" 0, and aPINGin another. Watch theBUSYerror, thenSCRIPT KILL.