Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 42 ยท Working with Redis

Lua Scripting and Functions

Learn Redis Lua scripting: EVAL and EVALSHA, KEYS versus ARGV, atomic execution, SCRIPT LOAD, Redis Functions with FCALL, and common script pitfalls.

A transaction runs a fixed list of commands, and WATCH lets you retry when the data changed under you. Sometimes neither is enough: you want to read a value, make a decision and write the result, as one indivisible step, with no retries and no extra round trips. Redis lets you do that by running a small program on the server. The language is Lua, and the program executes inside the Redis process.

Because Redis runs one command at a time, a script is executed atomically: while it runs, no other client's command can run. Every read and write in the script sees a consistent state, and nobody can interleave. Redis 7 added a second way to ship server-side logic called Functions, which are stored libraries of named routines that are part of the dataset.

Real Lua and real commands are read-only blocks in this lesson, since the site cannot run a Redis server or a Lua interpreter against one. The runnable examples are JavaScript models that show the same atomicity, caching and calling rules.

Your first script

EVAL takes the script text, the number of key names, then the key names, then the extra arguments:

TEXT
EVAL "return redis.call('GET', KEYS[1])" 1 greeting
  • 1 is numkeys: how many of the following arguments are key names.
  • The key names are available inside the script as the Lua table KEYS (indexed from 1, as Lua tables are).
  • Everything after the keys is available as ARGV.
  • redis.call(command, ...) runs a Redis command from the script. If the command fails, the script stops with that error. redis.pcall returns the error as a value so you can handle it.

A more useful script reserves stock only if enough is left:

LUA
local stock = tonumber(redis.call('GET', KEYS[1]) or '0')
local wanted = tonumber(ARGV[1])
if stock < wanted then
  return 0
end
redis.call('DECRBY', KEYS[1], wanted)
return 1

Called as EVAL "<the script>" 1 stock:sku42 3, it returns 1 and lowers the stock by 3, or returns 0 and changes nothing. Notice what makes it correct: the GET, the comparison and the DECRBY happen with no other client in between. The client-side version of the same logic needs WATCH and a retry loop (see Transactions).

A script, step by step

EVAL Send the Lua text with keys and arguments.
KEYS The keys the script touches.
ARGV Plain values such as amounts.
Return value Converted to a Redis reply.

One script runs start to finish before any other command.

1 / 2

KEYS versus ARGV

It is tempting to build the key name inside the script ('stock:' .. ARGV[1]) and skip KEYS. Do not. Every key a script touches should be passed in KEYS. Redis Cluster uses the declared keys to find the shard that must run the script, and all of them must live in the same hash slot. Scripts that touch undeclared keys may work on a single server but fail or misbehave in Cluster, and they bypass key-based access checks. Put identifiers of data in KEYS, and everything else (amounts, limits, timestamps) in ARGV.

Scripts also return values to the client with a fixed conversion from Lua to Redis replies. The rules you will meet most often:

Lua value Reply the client sees
number integer (the fractional part is dropped)
string bulk string
table (array style) array (stops at the first nil)
true integer 1
false or nil nil
redis.status_reply("OK") simple string OK

The reverse conversion matters as well: a GET on a missing key returns false in Lua, not nil, which is why scripts write redis.call('GET', k) or '0'.

Atomic by construction

The next example shows why this matters. Two clients each try to buy 3 of 5 items. In the client-side version the clients run GET, decide, then DECRBY as separate steps, and each step is a network trip where the other client may run. In the script version the whole routine is one step. The scheduler gives each client one turn at a time, in round-robin order, which is a model of interleaved network traffic.

JS Race without a script, safe with one

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first run both clients read a stock of 5 before either writes, so both buy 3 and the stock goes to -1: the shop oversold. In the second run alice's script finishes before bob's starts, bob sees 2 left and is refused. The emulator's eval runs the function with no interleaving, which models Redis's single-threaded execution of a script; real Redis runs Lua, not JavaScript.

EVALSHA and SCRIPT LOAD

Sending the whole script text on every call wastes bandwidth. Redis caches each script it runs, keyed by the SHA1 digest of its text. SCRIPT LOAD caches a script and returns the digest without running it, and EVALSHA runs a cached script by digest, with the same numkeys / keys / arguments layout:

TEXT
127.0.0.1:6379> SCRIPT LOAD "return redis.call('GET', KEYS[1])"
"d3c21d0c2b9ca22f82737626a27bcaf5d288f99f"
127.0.0.1:6379> EVALSHA d3c21d0c2b9ca22f82737626a27bcaf5d288f99f 1 greeting
"hello"

The script cache lives in memory and is not guaranteed to survive a restart, a failover to a replica or SCRIPT FLUSH. If it is missing, EVALSHA replies NOSCRIPT. Every client library therefore follows the same pattern: try EVALSHA, and on NOSCRIPT load the script (or send EVAL) and retry. Many libraries do this for you.

Redis Functions

Redis 7 introduced Functions to fix two annoyances of scripts: the cache is not part of the dataset, and every client has to carry the script text. A function library is loaded once with FUNCTION LOAD, is stored with the data, persisted and replicated, and is then called by name with FCALL.

LUA
#!lua name=stocklib

local function reserve(keys, args)
  local stock = tonumber(redis.call('GET', keys[1]) or '0')
  local wanted = tonumber(args[1])
  if stock < wanted then
    return 0
  end
  redis.call('DECRBY', keys[1], wanted)
  return 1
end

redis.register_function('reserve', reserve)
TEXT
redis-cli -x FUNCTION LOAD REPLACE < stocklib.lua
127.0.0.1:6379> FCALL reserve 1 stock:sku42 3
(integer) 1
127.0.0.1:6379> FUNCTION LIST
127.0.0.1:6379> FCALL_RO peek 1 stock:sku42

The first line (#!lua name=...) declares the library name and engine. A function receives keys and args as parameters instead of globals. A function that only reads can be registered with the no-writes flag and called with FCALL_RO, which makes it safe to run on replicas. Scripts can use a similar shebang header with flags in Redis 7 and later.

The next model shows both calling styles side by side: a script cache that can lose its contents and answers NOSCRIPT, and a function registry that survives. The digest here is a simple stand-in hash, not SHA1, because the point is the protocol around it.

JS Script cache with NOSCRIPT vs a function library

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows the difference in one line: after the simulated restart the script cache is empty and the digest no longer works, while the function is still registered. In real Redis a function library is stored with the dataset (persisted and replicated), which is why it also lands on replicas.

Pitfalls

  • Scripts block everyone. While a script runs, no other command runs. A loop over a million keys freezes the server. Keep scripts short. After the busy-reply-threshold setting (5 seconds by default) other clients start receiving BUSY errors, and an administrator can stop a read-only script with SCRIPT KILL.
  • Declare every key in KEYS, and keep them in one slot in Cluster.
  • No new global variables. Declare variables with local. Redis rejects scripts that create globals so scripts cannot leak state between calls.
  • Mind the types. Lua numbers are floating point, so tonumber on counters beyond about 2^53 loses precision, and returning a number drops the fraction. Return strings if you need exact decimals.
  • Do not depend on time or randomness. Modern Redis (7.0+) replicates the effects of a script, so random and time-based commands work, but keep scripts deterministic anyway so they are easy to test.
  • Keep scripts small and tested. A bug in a script is a bug that runs inside the server. Test with a throwaway instance before production.
  • Prefer one command when one exists. INCR, SET NX and HINCRBY need no script at all.

Scripts shine for patterns such as rate limiters, safe lock release and conditional updates (see Sessions and Rate Limiting and Queues, Distributed Locks and Leaderboards).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a Lua script atomic in Redis?

    Redis executes commands on a single thread, and a script counts as one uninterrupted unit of work on that thread.
  2. 2. In EVAL "..." 2 stock:1 stock:2 5, what is ARGV[1]?

    The 2 is numkeys, so stock:1 and stock:2 are KEYS[1] and KEYS[2]. Everything after them, here 5, goes into ARGV.
  3. 3. EVALSHA replies NOSCRIPT. What should the client do?

    The script cache can be empty after a restart, failover or SCRIPT FLUSH. Loading the script again fixes it.
  4. 4. What is the main advantage of Redis Functions over cached scripts?

    FUNCTION LOAD stores a named library as part of the data, so no client needs to carry the script text and replicas have it too.
  5. 5. Why is a long loop inside a script dangerous?

    Script execution blocks the single command thread. Keep scripts short and avoid unbounded loops.

Summary

  • EVAL script numkeys key... arg... runs Lua on the server; KEYS holds declared key names and ARGV the other arguments (both indexed from 1).
  • A script runs atomically: no other command interleaves, so read-decide-write logic needs no WATCH or retries.
  • Pass every key in KEYS, return values follow fixed Lua-to-reply conversions, and a missing key reads as false in Lua.
  • SCRIPT LOAD and EVALSHA save bandwidth; handle NOSCRIPT by loading the script and retrying.
  • Redis 7 Functions (FUNCTION LOAD, FCALL, FCALL_RO) store named libraries with the data, persisted and replicated.
  • Keep scripts short: a slow script blocks every client.

Next, see how applications talk to Redis in Using Redis from Node.js, Python, PHP and Java.