EVAL, Lua & Function Stats (Server-side Scripting)
Run atomic server-side Lua scripts; load and call functions.
Code
# EVAL: run Lua inline. Keys start at KEYS[1], args at ARGV[1]
127.0.0.1:6379> EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey hello
OK
127.0.0.1:6379> EVAL "return redis.call('GET', KEYS[1])" 1 mykey
"hello"
# Atomic conditional set (only if not exists)
127.0.0.1:6379> EVAL \
"if redis.call('EXISTS', KEYS[1]) == 0 then \
return redis.call('SET', KEYS[1], ARGV[1]) \
else return 0 end" 1 lock:resource token-abc
# Cache the script — call by SHA1 (avoids resending the body)
127.0.0.1:6379> SCRIPT LOAD "return redis.call('GET', KEYS[1])"
"e0e1f9fabfc9d4800c877a703b823ac0578ff833"
127.0.0.1:6379> EVALSHA e0e1f9fabfc9d4800c877a703b823ac0578ff833 1 mykey
"hello"
127.0.0.1:6379> SCRIPT EXISTS e0e1f9fabfc9d4800c877a703b823ac0578ff833
# Functions (Redis 7+) — named, library-style, replaces EVAL for new apps
127.0.0.1:6379> FUNCTION LOAD '#!lua name=mylib \
redis.register_function("myget", function(keys, args) \
return redis.call("GET", keys[1]) end)'
127.0.0.1:6379> FCALL myget 1 mykey
# List / dump functions
127.0.0.1:6379> FUNCTION LIST
127.0.0.1:6379> FUNCTION DUMPExplanation
EVAL runs Lua server-side: scripts execute atomically (no other command interleaves), making them ideal for atomic compare-and-set, rate limiting, or multi-key logic. KEYS[] and ARGV[] separate key names (so cluster can route) from arguments. SCRIPT LOAD caches the body and returns its SHA1; EVALSHA runs by hash — clients use this to avoid resending the script each call. Redis 7+ introduces FUNCTION LOAD with named, versionable libraries (FCALL to invoke) — preferred for new code over anonymous EVAL. Scripts must be fast: a long script blocks the whole server. Don't read non-key state (system time, random) — results must be deterministic for replication.
More Redis CLI Snippets
Connecting: URLs, TLS, AUTH & Select
Connect to standalone, TLS, authenticated, or non-default DB indexes.
Interactive Mode, HELP & Inspecting
Navigate the REPL, discover commands, and introspect the server.
MULTI / EXEC / WATCH (Transactions)
Queue commands atomically and use optimistic locking with WATCH.
Pub/Sub: SUBSCRIBE, PUBLISH & PSUBSCRIBE
Fan-out messaging with channels and pattern subscriptions.
MONITOR, SLOWLOG & Latency Debugging
Watch every command in real time and find slow queries.
RDB / AOF Persistence & Backup
Trigger snapshots, manage AOF rewrite, and capture a safe backup.