Skip to content

Redis Lua scripting with EVAL and EVALSHA

Write atomic Lua scripts for Redis, load with EVAL/SCRIPT LOAD, pass KEYS and ARGV correctly, and avoid the blocking and replication pitfalls in production.

Redis Lua scripting lets you run a sequence of commands on the server atomically — no other command runs in between, no race conditions, and the network round trips collapse to one. It is the primitive behind reliable rate limiters, distributed locks (Redlock building blocks), atomic counters with side effects, and any operation that needs read-then-write semantics on more than one key. This article covers EVAL, EVALSHA, the KEYS and ARGV contract, the replication implications, and the patterns that hold up under production load.

How to verify

# A trivial script
redis-cli EVAL "return 'hello'" 0

# Pass KEYS and ARGV
redis-cli EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# Cache a script and execute by hash
SHA=$(redis-cli SCRIPT LOAD "return redis.call('GET', KEYS[1])")
echo "$SHA"
redis-cli EVALSHA "$SHA" 1 mykey

# Inspect cached scripts
redis-cli SCRIPT EXISTS "$SHA"

What’s happening

EVAL <script> <numkeys> <key1> <key2> ... <arg1> <arg2> ... sends a Lua script to the server. The script executes atomically — the Redis main thread runs it from start to finish without interleaving any other command. Inside the script, redis.call('GET', KEYS[1]) performs a Redis command, and the result is a Lua value that you can branch on, transform, and return.

Two argument arrays are passed:

  • KEYS — the keys the script will touch. Crucial for cluster routing: in a Redis Cluster, every key in KEYS must hash to the same slot, and the script is sent to the node that owns that slot. Lying about which keys you touch (using redis.call('GET', 'someotherkey') without listing it in KEYS) breaks cluster routing.
  • ARGV — opaque arguments, treated as strings. Use these for non-key inputs: timestamps, TTLs, comparison values.

To avoid sending the script body on every call, SCRIPT LOAD returns a SHA1 of the script. EVALSHA <sha1> <numkeys> ... runs the cached script. If the cache has been cleared (e.g., after SCRIPT FLUSH or a server restart), EVALSHA returns NOSCRIPT and the client should fall back to EVAL and reload.

Replication: scripts replicate by sending the script and arguments to replicas, who re-execute. Redis 5+ supports redis.replicate_commands() which replicates the resulting commands instead — useful for scripts that touch non-deterministic state.

The procedure

  1. Write a script. Atomic check-and-set with TTL — set a key only if it does not exist and stamp a TTL:

    -- setnx-with-ttl.lua
    local current = redis.call('GET', KEYS[1])
    if current == false then
      redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
      return 1
    else
      return 0
    end
  2. Execute it inline with EVAL:

    redis-cli --eval setnx-with-ttl.lua mylock , my-uuid-1234 30

    The comma separates KEYS and ARGV. mylock is KEYS[1], my-uuid-1234 is ARGV[1], 30 is ARGV[2].

  3. Cache the script for repeated use:

    SHA=$(redis-cli SCRIPT LOAD "$(cat setnx-with-ttl.lua)")
    redis-cli EVALSHA "$SHA" 1 mylock my-uuid-1234 30
  4. Implement a rate limiter (sliding-window counter, 100 requests per 60 seconds per user):

    -- rate-limit.lua
    local key = KEYS[1]
    local limit = tonumber(ARGV[1])
    local window = tonumber(ARGV[2])
    local count = redis.call('INCR', key)
    if count == 1 then
      redis.call('EXPIRE', key, window)
    end
    if count > limit then
      return 0
    end
    return 1
    redis-cli --eval rate-limit.lua user:42:rate , 100 60
  5. Implement a safe lock release (only delete if the lock value matches the holder’s UUID):

    -- release-lock.lua
    if redis.call('GET', KEYS[1]) == ARGV[1] then
      return redis.call('DEL', KEYS[1])
    else
      return 0
    end
  6. Handle NOSCRIPT in the client. Pseudocode for a resilient call:

    try:
        return r.evalsha(sha, 1, key, value, ttl)
    except redis.exceptions.NoScriptError:
        sha = r.script_load(script_body)
        return r.evalsha(sha, 1, key, value, ttl)
  7. For cluster deployments, ensure all keys hash to the same slot using curly-brace tags:

    redis-cli -c --eval transfer.lua "balance:{tx7}:alice" "balance:{tx7}:bob" , 50

Common pitfalls

  • A script that blocks the Redis main thread for more than 100 ms freezes every other client. Keep scripts short and bounded; never loop over SCAN inside a script.
  • redis.call('GET', 'hardcoded-key') without listing hardcoded-key in KEYS breaks cluster routing — the script lies about what it touches. Always pass keys via KEYS.
  • Returning a table from Lua with a nil in the middle is treated as the end of the array. Convert nil to a sentinel like false or an empty string before returning.
  • SCRIPT FLUSH clears the cache on the master but not on replicas in some older versions; check SCRIPT EXISTS on both after a flush.
  • A script that uses redis.replicate_commands() and modifies state via math.random() produces different results on replicas — Redis 5+ is stricter about this, refusing such scripts unless they explicitly opt out of script replication.

In the engagements we run, every Lua script ships with a unit test that asserts the result of EVAL against a fresh fixture, a Prometheus counter for redis_slowlog entries tagged with the script SHA, and a documented cluster keying contract. We operate that under Managed Operations — and for more powerful server-side logic Redis 7 introduces Redis Functions which deserve a separate look.