Module A-2·22 min read

Why Lua scripts execute atomically, KEYS and ARGV conventions, redis.call() vs redis.pcall(), SCRIPT LOAD and EVALSHA for script caching, atomic rate limiters and conditional operations impossible without Lua.

A-2 — Lua Scripting: EVAL, EVALSHA, and Atomic Compound Operations

Who this module is for: You have reached the limits of MULTI/EXEC and WATCH — you need to read a value, make a decision based on it, and write conditionally, all as a single atomic operation. Lua scripts run atomically on the Redis server, executing arbitrary logic without any other client interleaving. This module covers the EVAL model, the KEYS/ARGV convention, script caching, error handling, and the patterns that are impossible to implement correctly without Lua.


Why Lua Scripts Are Atomic

Redis's single-threaded event loop executes commands one at a time. A Lua script is executed as if it were a single command — it runs to completion before any other client's command executes. No other client can see intermediate state or interleave their commands during script execution.

This is stronger than MULTI/EXEC:

  • MULTI/EXEC queues commands and sends them together, but does not provide read-then-decide-then-write atomicity (you cannot use the result of a read to conditionally control what you write)
  • Lua executes arbitrary code server-side — you can read, branch, loop, and write all within the atomic boundary

The price: While a Lua script runs, Redis processes no other commands. Long-running scripts block all clients. Scripts must be fast (< 1ms ideally, < 5ms acceptable).


EVAL: Running a Script

EVAL script numkeys key [key ...] arg [arg ...]
  • script — the Lua script as a string
  • numkeys — the number of key arguments (required for Cluster routing)
  • key [key ...] — key names accessible in the script as KEYS[1], KEYS[2], etc.
  • arg [arg ...] — additional arguments accessible as ARGV[1], ARGV[2], etc.
text

The KEYS and ARGV Convention

KEYS — all Redis key names the script accesses. Required for Redis Cluster: the cluster client routes the command based on KEYS[1]. If your script accesses keys on different slots, it will fail in Cluster.

ARGV — all non-key parameters: values, thresholds, configuration.

The convention is enforced by policy, not the interpreter. You can technically access any key by hardcoding the name in the script, but this breaks Cluster routing. Always pass key names via KEYS.

lua

redis.call vs redis.pcall

lua

redis.call propagates errors — if the Redis command fails (type mismatch, wrong arg count), the script aborts and Redis returns an error to the client.

redis.pcall catches errors and returns them as a Lua table {err = "error message"}. Use when you want to handle errors within the script:

lua

Return Types

Lua → Redis type conversion:

LuaRedis reply
integerInteger reply
stringBulk string reply
table (array)Multi-bulk reply
{ok = "OK"}Simple string reply (+OK)
{err = "ERR msg"}Error reply
false or nilNil bulk reply
lua

Important: Lua numbers are always floats. When returning integers to Redis, use math.floor() or tonumber() for explicit integer conversion. return 3.14(integer) 3 (Redis truncates floats).


SCRIPT LOAD and EVALSHA

Sending the full script text on every call is wasteful for large scripts. SCRIPT LOAD uploads the script to Redis once and returns its SHA1 digest. EVALSHA then calls the script by SHA:

text
typescript

Script cache persistence: The script cache lives in Redis memory and is cleared on restart. Your application must re-load scripts after a Redis restart. Pattern:

typescript

SCRIPT EXISTS sha1 [sha1 ...] — check if scripts are loaded:

text

SCRIPT FLUSH — clear all cached scripts. Run this after code changes that modify Lua scripts.


Production Lua Patterns

Pattern 1: Atomic Rate Limiter

The sliding window rate limiter with Sorted Sets (from P-5) requires multiple commands. In a pipeline, they are not atomic. In Lua, they are:

lua
typescript

Pattern 2: Conditional Set (Set If Less Than)

Update a leaderboard score only if it is higher than the current score — atomically:

lua

Without Lua, this would require WATCH + MULTI/EXEC with a retry loop. With Lua: one atomic call.

Pattern 3: Atomic Inventory Deduction

lua

Pattern 4: Get-or-Set (Single-Flight Cache)

lua

Debugging Lua Scripts

redis.log

lua

Log levels: LOG_DEBUG, LOG_VERBOSE, LOG_NOTICE, LOG_WARNING. Output appears in the Redis log file.

SCRIPT DEBUG

Redis 3.2+ includes a Lua debugger. Start a debugging session:

bash

Commands in debug mode: s (step), n (next), c (continue), b line (breakpoint), p var (print), l (list source).

Test Scripts in Isolation

Before deploying a Lua script, test it with EVAL directly in redis-cli with representative inputs. Verify the return values match your expected Redis response types.


Execution Limits

lua-time-limit 5000 → script cannot run for more than 5 seconds (default)

After lua-time-limit milliseconds, Redis stops accepting most new commands and returns a BUSY error. The script cannot be killed immediately — you can send SCRIPT KILL to terminate a script that has not yet performed any writes. If the script has written data, SCRIPT KILL is refused (to prevent partial writes), and only SHUTDOWN NOSAVE will stop Redis.

This is why Lua scripts must be fast. A script that loops over a large dataset or has an infinite loop can make Redis completely unresponsive.

Design rule: Lua scripts should complete in microseconds to single-digit milliseconds. If you need to process large datasets, do it in application code with SCAN-based iteration — not in a single Lua script.


Summary

  • Lua scripts execute atomically on the Redis server — no other command runs during script execution
  • EVAL script numkeys KEYS... ARGV... — pass key names via KEYS (required for Cluster routing), other params via ARGV
  • redis.call() aborts on error; redis.pcall() catches and returns errors as Lua tables
  • SCRIPT LOAD uploads a script and returns its SHA1; EVALSHA calls by SHA (avoids retransmitting the script body on every call)
  • Handle NOSCRIPT errors after Redis restart by reloading scripts automatically
  • Lua enables atomic operations impossible with MULTI/EXEC: read-then-decide-then-write, conditional updates, get-or-set
  • Scripts must be fastlua-time-limit (default 5s) blocks all clients when exceeded; design for < 1ms execution
  • Debug with redis.log() and redis-cli --ldb

Next: A-3 — Redis Functions: Persistent Stored Procedures — how Redis Functions differ from Lua scripts (functions survive restarts), function libraries, and when to migrate from EVALSHA to Functions.


Knowledge Check

A developer writes a Lua script to conditionally update a user's balance. To avoid passing too many arguments, they hardcode the key name user:1001:balance directly inside the script rather than passing it via the KEYS array. The script works perfectly in their local standalone Redis instance, but fails when deployed to their production Redis Cluster. Why?


An application uses a complex Lua script to analyze and aggregate thousands of keys. During a traffic spike, the script occasionally takes 6 seconds to execute. What is the impact of this 6-second execution time on the Redis instance?


What is the primary operational advantage of using EVALSHA over EVAL in application code?

Test your knowledge with more question sets

Sign in to access a wider variety of questions and get notified when new practice sets are added to this module.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.