Learn Labs
Transactions & Scripting

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 uses KEYS to route the script to the right node, and ACLs check them.
  • ARGV[] holds everything else.
  • redis.call raises an error on failure (aborting the script); redis.pcall returns 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:greeting

Client 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 applib
EVAL scriptsFunctions
Lives inThe client's codeThe server, named
Survives restartNo (cache only)Yes (RDB/AOF)
ReplicatedEffects areThe library itself is
DeploymentWith the appSeparately: 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 *.

CONFIG GET busy-reply-threshold5000 msafter 5s, other clients start getting: BUSY Redis is busy running a scriptSCRIPT KILLstop a read-only script that's running too longFUNCTION KILLsame for functionsSHUTDOWN NOSAVEthe only way out of a script that has already written

Rules for scripts

  1. Pass every key in KEYS; never compute key names inside the script.
  2. In Cluster, all of a script's keys must hash to the same slot (use hash tags).
  3. Keep them short. Microseconds, not milliseconds.
  4. Make them deterministic: Redis 7+ replicates the effects of scripts, but non-determinism still makes them hard to reason about.
  5. 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

  1. Load the applib function and call debit until it fails.
  2. Restart Redis (docker restart redis) and run FUNCTION LIST. The function survived. Try EVALSHA with an earlier script's SHA: it didn't (NOSCRIPT).
  3. Run a deliberately slow script in one terminal, EVAL "local i=0 while i < 3e8 do i=i+1 end return i" 0, and a PING in another. Watch the BUSY error, then SCRIPT KILL.

On this page