TExcelTAD
Home › Redis › Redis Lua Scripting

Redis Lua Scripting

Sometimes you need logic that reads data, makes a decision and writes, all atomically. WATCH can do it with retries, but there is a simpler tool: send a small Lua program to Redis. The server runs the whole script as one atomic step, exactly like a single command, and nothing else runs while it executes.

EVAL basics

EVAL script numkeys key [key ...] arg [arg ...] runs a script. Inside the script, the keys are available in the table KEYS and the other arguments in ARGV (Lua tables start at index 1). redis.call runs a Redis command and returns its reply.

redis · try it yourself
EVAL "return 'Hello from Lua'" 0
EVAL "return 6 * 7" 0
EVAL "return {KEYS[1], ARGV[1], ARGV[2]}" 1 user:1 first second
SET greeting Hi
EVAL "return redis.call('GET', KEYS[1])" 1 greeting
redis> EVAL "return 'Hello from Lua'" 0
"Hello from Lua"
redis> EVAL "return 6 * 7" 0
(integer) 42
redis> EVAL "return {KEYS[1], ARGV[1], ARGV[2]}" 1 user:1 first second
1) "user:1"
2) "first"
3) "second"
redis> SET greeting Hi
OK
redis> EVAL "return redis.call('GET', KEYS[1])" 1 greeting
"Hi"

Tip: Always pass key names through KEYS rather than writing them inside the script. Redis Cluster uses the declared keys to route the script to the right node, and the same script can then be reused for any key.

Lua and Redis types

Values are converted between Redis replies and Lua types:

Redis reply Lua value Back to Redis
integer number integer (decimals are truncated)
bulk string string bulk string
array table array
nil false nil
status (OK) table {ok = "OK"} status
redis · try it yourself
EVAL "return 3.99" 0
EVAL "return tostring(3.99)" 0
EVAL "return redis.call('GET', 'missing')" 0
EVAL "return {1, 2, 'three'}" 0
redis> EVAL "return 3.99" 0
(integer) 3
redis> EVAL "return tostring(3.99)" 0
"3.99"
redis> EVAL "return redis.call('GET', 'missing')" 0
(nil)
redis> EVAL "return {1, 2, 'three'}" 0
1) (integer) 1
2) (integer) 2
3) "three"

The truncation catches people out: return numbers as strings if you need decimals.

A real example: transfer only if the balance is enough

Here is "move money only when the sender has enough", which needed WATCH and a retry loop in the previous lesson. As a script it is one call:

redis · try it yourself
SET balance:ada 100
SET balance:linus 20
EVAL "local b = tonumber(redis.call('GET', KEYS[1]) or '0') local amount = tonumber(ARGV[1]) if b < amount then return redis.error_reply('insufficient funds') end redis.call('DECRBY', KEYS[1], amount) redis.call('INCRBY', KEYS[2], amount) return b - amount" 2 balance:ada balance:linus 30
EVAL "local b = tonumber(redis.call('GET', KEYS[1]) or '0') local amount = tonumber(ARGV[1]) if b < amount then return redis.error_reply('insufficient funds') end redis.call('DECRBY', KEYS[1], amount) redis.call('INCRBY', KEYS[2], amount) return b - amount" 2 balance:ada balance:linus 500
MGET balance:ada balance:linus
redis> SET balance:ada 100
OK
redis> SET balance:linus 20
OK
redis> EVAL "local b = tonumber(redis.call('GET', KEYS[1]) or '0') local amount = tonumber(ARGV[1]) if b < amount then return redis.error_reply('insufficient funds') end redis.call('DECRBY', KEYS[1], amount) redis.call('INCRBY', KEYS[2], amount) return b - amount" 2 balance:ada balance:linus 30
(integer) 70
redis> EVAL "local b = tonumber(redis.call('GET', KEYS[1]) or '0') local amount = tonumber(ARGV[1]) if b < amount then return redis.error_reply('insufficient funds') end redis.call('DECRBY', KEYS[1], amount) redis.call('INCRBY', KEYS[2], amount) return b - amount" 2 balance:ada balance:linus 500
(error) insufficient funds
redis> MGET balance:ada balance:linus
1) "70"
2) "50"

Written over several lines, the script is easier to read:

lua
local balance = tonumber(redis.call('GET', KEYS[1]) or '0')
local amount = tonumber(ARGV[1])
if balance < amount then
  return redis.error_reply('insufficient funds')
end
redis.call('DECRBY', KEYS[1], amount)
redis.call('INCRBY', KEYS[2], amount)
return balance - amount

redis.error_reply returns an error to the client. Note or '0': GET on a missing key gives false in Lua.

Loops and logic

Scripts can loop and build results. This one increments several counters and returns their new values, and the second one sorts the matching key names (remember that KEYS returns them in no particular order):

redis · try it yourself
EVAL "local out = {} for i, k in ipairs(KEYS) do out[i] = redis.call('INCRBY', k, ARGV[1]) end return out" 3 hits:a hits:b hits:c 5
EVAL "local names = redis.call('KEYS', ARGV[1]) table.sort(names) return names" 0 hits:*
redis> EVAL "local out = {} for i, k in ipairs(KEYS) do out[i] = redis.call('INCRBY', k, ARGV[1]) end return out" 3 hits:a hits:b hits:c 5
1) (integer) 5
2) (integer) 5
3) (integer) 5
redis> EVAL "local names = redis.call('KEYS', ARGV[1]) table.sort(names) return names" 0 hits:*
1) "hits:a"
2) "hits:b"
3) "hits:c"

Errors: redis.call versus redis.pcall

If a command inside redis.call fails, the script stops and the error is returned to the client. Commands that already ran are not undone, so validate first and write last. redis.pcall catches the error and returns it as a table instead, so the script can continue:

redis · try it yourself
SET word hello
EVAL "redis.call('SET', KEYS[2], 'one') redis.call('INCR', KEYS[1]) redis.call('SET', KEYS[2], 'two')" 2 word step
GET step
EVAL "local r = redis.pcall('INCR', KEYS[1]) if type(r) == 'table' and r.err then return 'caught: ' .. r.err end return r" 1 word
redis> SET word hello
OK
redis> EVAL "redis.call('SET', KEYS[2], 'one') redis.call('INCR', KEYS[1]) redis.call('SET', KEYS[2], 'two')" 2 word step
(error) ERR value is not an integer or out of range script: 04a507bb1c7649b88bf81f5e72a5e4afe23bd511, on @user_script:1.
redis> GET step
"one"
redis> EVAL "local r = redis.pcall('INCR', KEYS[1]) if type(r) == 'table' and r.err then return 'caught: ' .. r.err end return r" 1 word
"caught: ERR value is not an integer or out of range"

The first script stopped at the failing INCR, but its first SET had already happened, so step is "one". The error message names the script by its SHA1 hash. The second script caught the error with redis.pcall and returned its own reply.

Caching scripts: SCRIPT LOAD and EVALSHA

Sending a long script on every call wastes bandwidth. SCRIPT LOAD stores a script on the server and returns its SHA1 hash; EVALSHA then runs it by hash:

redis · try it yourself
SCRIPT LOAD "return redis.call('INCRBY', KEYS[1], ARGV[1])"
EVALSHA 8cd00688c05c46bde4a2e60658ef20a2e5c0b248 1 counter 10
EVALSHA 8cd00688c05c46bde4a2e60658ef20a2e5c0b248 1 counter 5
SCRIPT EXISTS 8cd00688c05c46bde4a2e60658ef20a2e5c0b248 ffffffffffffffffffffffffffffffffffffffff
redis> SCRIPT LOAD "return redis.call('INCRBY', KEYS[1], ARGV[1])"
"8cd00688c05c46bde4a2e60658ef20a2e5c0b248"
redis> EVALSHA 8cd00688c05c46bde4a2e60658ef20a2e5c0b248 1 counter 10
(integer) 10
redis> EVALSHA 8cd00688c05c46bde4a2e60658ef20a2e5c0b248 1 counter 5
(integer) 15
redis> SCRIPT EXISTS 8cd00688c05c46bde4a2e60658ef20a2e5c0b248 ffffffffffffffffffffffffffffffffffffffff
1) (integer) 1
2) (integer) 0

The hash depends only on the script text, so it is the same on every server. If the cache was cleared (after a restart, for example), EVALSHA fails with NOSCRIPT and the client falls back to EVAL. Client libraries do this for you (r.register_script(...) in redis-py).

Functions (Redis 7+)

Scripts loaded with SCRIPT LOAD are a cache and can vanish. Functions are the persistent alternative: a named library of Lua functions that is saved with the data and replicated. You load a library with FUNCTION LOAD and call it with FCALL:

redis · try it yourself
FUNCTION LOAD "#!lua name=shop\nredis.register_function('add_to_cart', function(keys, args) return redis.call('HINCRBY', keys[1], args[1], args[2]) end)"
FCALL add_to_cart 1 cart:7 product:42 2
FCALL add_to_cart 1 cart:7 product:42 1
HGETALL cart:7
redis> FUNCTION LOAD "#!lua name=shop\nredis.register_function('add_to_cart', function(keys, args) return redis.call('HINCRBY', keys[1], args[1], args[2]) end)"
"shop"
redis> FCALL add_to_cart 1 cart:7 product:42 2
(integer) 2
redis> FCALL add_to_cart 1 cart:7 product:42 1
(integer) 3
redis> HGETALL cart:7
1) "product:42"
2) "3"

Rules for good scripts

  • Keep them short: while a script runs, the whole server waits. A loop over a million keys blocks everyone.
  • Declare every key you touch in KEYS (required for Cluster).
  • Do not rely on time or randomness inside scripts if you need reproducible results.
  • Validate inputs before the first write, since there is no rollback.

Test yourself

Inside EVAL "..." 2 a b c, what is ARGV[1]?

  1. a
  2. b
  3. c
  4. 2

What does EVAL "return 2.75" 0 return?

  1. "2.75"
  2. (integer) 2
  3. (integer) 3
  4. (error)

Why are Lua scripts useful compared with MULTI/EXEC?

  1. They are stored on disk automatically
  2. They can read values and decide what to write, atomically, without retries
  3. They run on the client
  4. They support rollback