Script Valley
Redis: Complete Course
Transactions, Scripting, and PipelinesLesson 5.4

Lua scripting in Redis: run server-side logic atomically with EVAL

EVAL command, KEYS and ARGV, atomicity of Lua scripts, no interleaving, redis.call vs redis.pcall, SCRIPT LOAD EVALSHA, when to use Lua

Server-side scripts with Lua

Lua scripts run inside Redis atomically. The entire script executes without interruption — no other command runs on the server until it completes.

Basic EVAL syntax

-- EVAL script numkeys key1 key2 ... arg1 arg2 ...
EVAL "return redis.call('get', KEYS[1])" 1 mykey

-- Multi-step atomic operation: conditional set
EVAL "
  local current = redis.call('get', KEYS[1])
  if current == ARGV[1] then
    redis.call('set', KEYS[1], ARGV[2])
    return 1
  end
  return 0
" 1 mykey expected_value new_value

Caching scripts with EVALSHA

-- Load script once, call by SHA1 hash
SCRIPT LOAD "return redis.call('get', KEYS[1])"
# → "e0e1f9fabfa9d353e01a1ec85..."

EVALSHA e0e1f9... 1 mykey

redis.call vs redis.pcall

redis.call raises a Lua error on Redis error, aborting the script. redis.pcall catches the error and returns it as a table, letting you handle it in Lua. Use pcall when a command may fail and you want to continue execution.

Lua scripts replace WATCH+MULTI/EXEC patterns when logic is complex or contention is high. All reads and writes happen server-side in a single round trip.

Up next

Rate limiting with Redis: sliding window and token bucket patterns

Sign in to track progress