Script Caching

Difficulty: Advanced

Question

What are SCRIPT LOAD and EVALSHA for, how do clients handle a missing script, and how do Redis 7 Functions change the picture?

Answer

SCRIPT LOAD sends a Lua script to Redis, stores it in the server's script cache and returns its SHA1 digest. EVALSHA <sha1> numkeys key... arg... then runs the cached script by that digest, so the client sends 40 hex characters instead of the full script on every call. If the script is not in the cache, Redis replies with a NOSCRIPT error and the client must fall back to EVAL or load it again.

Why scripts exist at all

A Lua script runs atomically: while it executes, no other command runs. That lets you do read-modify-write logic (check a value, then update several keys) without WATCH/MULTI retries and in a single network round trip. Rate limiters, compare-and-delete lock release and inventory decrements are common examples.

How the cache behaves

  • EVAL also caches the script it runs, under the SHA1 of its body. SCRIPT LOAD just caches without running.
  • The cache lives in memory only. It is cleared on restart, by SCRIPT FLUSH, and a newly promoted replica or a new cluster node may not have your script.
  • SCRIPT EXISTS sha1 [sha1 ...] checks presence.
  • Because the cache can disappear at any time, every client must handle NOSCRIPT. Libraries do this automatically: ioredis defineCommand, redis-py register_script and Jedis try EVALSHA first and fall back to EVAL on NOSCRIPT.

Rules scripts must follow

  • Pass every key the script touches in KEYS, not built from strings inside the script. Redis Cluster uses KEYS to route the call, and all keys must hash to the same slot.
  • Keep scripts short. A long script blocks every other client. After busy-reply-threshold (formerly lua-time-limit, default 5 seconds) Redis starts replying BUSY to others, and you can stop a read-only script with SCRIPT KILL.
  • Since Redis 5.0 scripts are replicated by their effects (the write commands they produce), so non-deterministic calls like reading the time are allowed.
  • Redis 7.0 added EVAL_RO and EVALSHA_RO for read-only scripts that can run on replicas.

EVAL/EVALSHA vs Redis Functions

AspectEVAL / EVALSHAFunctions (7.0+)
Loaded withSCRIPT LOAD or EVALFUNCTION LOAD
Called withEVALSHA sha1 ...FCALL name numkeys ...
Survives restartNoYes, saved in RDB and AOF
Replicated to replicasNo (cache is local)Yes
Identified bySHA1 of the bodyLibrary and function name

Functions treat server-side logic like stored procedures that the server owns, which removes the NOSCRIPT dance. Ephemeral scripts with EVALSHA are still common and fully supported, especially when the logic ships with the application code.

EVALSHA with NOSCRIPT fallback. Clients optimistically send the SHA and resend the full script only when the cache was lost.
  1. App → Redis: SCRIPT LOAD <lua body>
  2. Redis → App: SHA1 digest e0e1f9...
  3. App → Redis: EVALSHA e0e1f9... 1 rl:42 100
  4. Redis → App: Result (fast path)
  5. App → Redis: EVALSHA after restart
  6. Redis → App: NOSCRIPT error
  7. App → Redis: EVAL <lua body> (re-caches it)

Code examples

Manual SCRIPT LOAD and EVALSHA

# Atomic stock decrement: fail if not enough stock
SCRIPT LOAD "local s = tonumber(redis.call('GET', KEYS[1]) or '0') if s < tonumber(ARGV[1]) then return -1 end return redis.call('DECRBY', KEYS[1], ARGV[1])"
# -> "b6c1..." (40 hex chars)

SET stock:sku123 10
EVALSHA b6c1... 1 stock:sku123 3
SCRIPT EXISTS b6c1...

Replace b6c1... with the full digest returned by SCRIPT LOAD. The check and the decrement cannot be interleaved with other clients.

Library-managed caching (Node.js, ioredis)

import Redis from 'ioredis';
const redis = new Redis();

redis.defineCommand('takeStock', {
  numberOfKeys: 1,
  lua: `
    local s = tonumber(redis.call('GET', KEYS[1]) or '0')
    if s < tonumber(ARGV[1]) then return -1 end
    return redis.call('DECRBY', KEYS[1], ARGV[1])`,
});

// ioredis sends EVALSHA and falls back to EVAL on NOSCRIPT
const left = await redis.takeStock('stock:sku123', 3);
console.log(left === -1 ? 'Out of stock' : `Left: ${left}`);

Defining the command once lets the library handle hashing, EVALSHA and the NOSCRIPT retry for you.

Key points

  • SCRIPT LOAD caches a script and returns its SHA1; EVALSHA runs it by digest
  • The script cache is in memory only and can vanish on restart, failover or SCRIPT FLUSH
  • Always handle NOSCRIPT by falling back to EVAL; most libraries do it automatically
  • Scripts are atomic and block the server, so keep them short and pass all keys in KEYS
  • Redis 7.0 Functions (FUNCTION LOAD, FCALL) are persisted and replicated

Common follow-up questions

  • Why must all keys be passed through KEYS in Redis Cluster?
  • What happens if a Lua script runs for 10 seconds?
  • When would you choose MULTI/EXEC with WATCH over a Lua script?
  • How do Redis Functions differ from EVAL scripts?

Interview tips

  • Do not stop at 'saves bandwidth'; explain the NOSCRIPT case and how clients recover
  • Mention atomicity as the real reason scripts are used
  • Bringing up Redis 7 Functions shows you are current

Concepts covered

Lua scripting, SCRIPT LOAD, EVALSHA, NOSCRIPT, Redis Functions

More Redis & Caching questions