Lua Scripting

Difficulty: Advanced

Question

What are the advantages of running Lua scripts in Redis, and what should you watch out for? Write a script that does something atomically.

Answer

Lua scripts let you run multi-step logic inside the Redis server as a single atomic operation. While a script runs, no other command executes, so you get read-modify-write logic without race conditions, plus fewer network round trips because the whole sequence travels in one call. The catch is that a slow script blocks every other client, so scripts must be short and bounded.

Why use scripts at all

  • Atomicity: the classic problem is "check then act". Reading a value, deciding in the app, and writing back can interleave with other clients. Inside a script nothing interleaves.
  • Fewer round trips: a rate limiter that needs INCR, EXPIRE and a comparison becomes one request instead of three. Across a Mumbai to Singapore link at 60 ms RTT, that matters.
  • Conditional logic: MULTI/EXEC queues commands but cannot branch on results. Lua can use if, loops and the return values of redis.call.
  • Safe lock release: deleting a lock only if it still holds your token is a textbook script.

How EVAL, EVALSHA and Functions work

  1. EVAL script numkeys key1 ... arg1 ... sends the script text. Inside it, keys are in KEYS[1..n] and other values in ARGV[1..n].
  2. Redis caches the compiled script by its SHA1. SCRIPT LOAD returns that SHA, and EVALSHA sha ... runs it without resending the body. If the cache was flushed (for example after a restart), you get NOSCRIPT and should fall back to EVAL. Most client libraries do this for you.
  3. Since Redis 7.0, Functions (FUNCTION LOAD, FCALL) are the recommended way to ship server-side logic. Unlike the script cache, functions are persisted and replicated, so they survive restarts.
  4. EVAL_RO and FCALL_RO run read-only scripts that can be routed to replicas.

Rules that matter in production

  • Pass every key the script touches through KEYS, never build key names inside the script. Redis Cluster uses KEYS to route the call, and all keys must hash to the same slot (use hash tags like {user:42}).
  • redis.call raises an error that aborts the script; redis.pcall returns the error so you can handle it. Writes made before an error are not rolled back.
  • Scripts should be deterministic. Since 7.0 Redis replicates the effects of a script, not the script itself, which removed many old restrictions, but keeping scripts pure is still good practice.

The blocking problem

A script that loops over a million elements freezes Redis for everyone. After busy-reply-threshold (formerly lua-time-limit, default 5000 ms) other clients start getting BUSY errors. You can stop a read-only script with SCRIPT KILL, but once a script has written data the only escape is SHUTDOWN NOSAVE, which loses data since the last save. Keep scripts O(1) or O(small N), and never use them for bulk scans.

Common real uses

  • Sliding window or token bucket rate limiters for APIs.
  • Atomic inventory decrement: reduce stock only if it is above zero, used during flash sales.
  • Releasing a distributed lock safely by comparing the token.
  • Moving an item between data structures with validation.
MULTI/EXEC vs Lua script. Both are atomic, but only scripts can make decisions based on intermediate results.
MULTI/EXECLua script
Atomic executionYesYes
Branch on a read valueNo, needs WATCH and retryYes, with if/else
Round tripsSeveral commands pipelinedOne call
Rollback on errorNoNo
RiskOptimistic retries under contentionLong script blocks server

Code examples

Atomic stock decrement for a flash sale

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

// Decrement stock only if enough units remain.
// Returns remaining stock, or -1 if sold out.
redis.defineCommand('reserveStock', {
  numberOfKeys: 1,
  lua: `
    local stock = tonumber(redis.call('GET', KEYS[1]) or '0')
    local qty = tonumber(ARGV[1])
    if stock < qty then
      return -1
    end
    return redis.call('DECRBY', KEYS[1], qty)
  `,
});

await redis.set('stock:sku:7781', 3);
console.log(await redis.reserveStock('stock:sku:7781', 2)); // 1
console.log(await redis.reserveStock('stock:sku:7781', 2)); // -1

ioredis loads the script and calls it with EVALSHA, falling back to EVAL on NOSCRIPT. No other client can change the stock between the GET and the DECRBY.

Safe lock release with EVAL

# Acquire: set only if absent, with a 30s expiry and a unique token
redis-cli SET lock:invoice:55 'tok-8f2a' NX PX 30000

# Release: delete only if the lock still holds our token
redis-cli EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock:invoice:55 tok-8f2a

Without the script, a slow client could delete a lock that already expired and was taken by someone else.

Key points

  • Scripts run atomically; no other command executes until they finish.
  • Pass all keys via KEYS so Redis Cluster can route the call; keys must share a hash slot.
  • EVALSHA avoids resending the script; handle NOSCRIPT by falling back to EVAL.
  • Redis 7 Functions (FUNCTION LOAD, FCALL) are persisted and replicated, unlike the script cache.
  • Errors do not roll back earlier writes in the script.
  • Long scripts block everyone; SCRIPT KILL only works if the script has not written yet.

Common follow-up questions

  • How is a Lua script different from a MULTI/EXEC transaction with WATCH?
  • Why must keys be passed through KEYS instead of being built inside the script?
  • What happens if a script runs longer than busy-reply-threshold?
  • How would you implement a sliding window rate limiter with a script?
  • What changed with Redis Functions in 7.0?

Interview tips

  • Write the lock release or stock decrement script from memory; it is the most common follow-up.
  • Always mention the blocking risk; interviewers want to hear that you know scripts are not free.
  • Bringing up Functions and the Cluster hash-slot rule signals real production experience.

Concepts covered

EVAL and EVALSHA, Atomic Scripts, KEYS and ARGV, Redis Functions, Script Blocking

More Redis & Caching questions