Redis Lua cheatsheet.

Basic EVAL

EVAL "return redis.call('GET', KEYS[1])" 1 mykey

In Python

script = """
local v = redis.call('GET', KEYS[1])
if not v then
    redis.call('SET', KEYS[1], ARGV[1])
    return 1
end
return 0
"""

r = redis.eval(script, 1, "key", "value")

# Cache via SCRIPT LOAD
sha = redis.script_load(script)
r = redis.evalsha(sha, 1, "key", "value")

Atomic operations

All Lua scripts run atomically. Use for compare-and-swap, multi-key ops, complex updates.

# Atomic compare-and-set
cas = """
if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('SET', KEYS[1], ARGV[2])
end
return nil
"""

Multiple returns

script = """
return {redis.call('GET', KEYS[1]), redis.call('GET', KEYS[2])}
"""

Cluster: same hash slot

All KEYS in a Lua call must hash to same slot. Use {tag}:

EVAL "..." 2 {user:1}:profile {user:1}:sessions

Type conversions

LuaRedis
numberint
stringbulk
tablearray
true1
falsenil
nilnil

Helpers

local val = redis.call('GET', KEYS[1])
local exists = (val ~= false)

-- Status reply
return redis.status_reply("OK")

-- Error reply
return redis.error_reply("custom error")

Avoid

  • math.random() without seed → may differ across replicas.
  • time() calls → for replication compat, prefer ARGV time.
  • Long-running scripts → block server.

Script timeout

lua-time-limit 5000   # ms; default 5s

If exceeded: SCRIPT KILL (if no writes) or shutdown.

Functions (Redis 7+)

Persistent server-side functions:

FUNCTION LOAD "#!lua name=mylib
redis.register_function('myfunc', function(keys, args)
    return redis.call('GET', keys[1])
end)
"

FCALL myfunc 1 mykey

Auto-persisted, replicated, faster than EVAL.

Common mistakes

  • Using KEYS in script (must pass via KEYS table, not hard-code).
  • Long-running script → blocks all clients.
  • Random / time non-deterministic on replicas.
  • Returning wrong types.
  • Forgetting cluster hash slot requirement.

Read this next

If you want my Lua scripts library, it’s at rajpoot.dev .


Building something AI-, backend-, or data-heavy and want a second pair of eyes? I do consulting and freelance work — see my projects and ways to reach me at rajpoot.dev .