14. Server-side Execution: Lua Scripting in Redis
Server-side Logic and Execution Safety
Redis provides a powerful capability: running custom procedural logic directly on the database server using the Lua programming language. By executing code on the server, you bypass the network latency of sending intermediate queries back and forth to the client. A Lua script executes as an atomic transaction block. Because Redis is single-threaded, a running Lua script occupies the execution engine completely. No other command or script can run until the Lua script completes, guaranteeing absolute isolation without the need for optimistic locks.
This server-side isolation is highly useful for complex read-then-write logic. For example, in a dynamic inventory system, an application must check if a product is in stock, write a reservation log, and decrement the stock counter. If these steps are executed as separate client queries, race conditions can occur. A Lua script executes these steps inside the Redis engine, ensuring no other client can modify the data during execution.
However, because Lua scripts block the execution thread, developers must ensure they are fast. Running scripts with complex loops or slow O(N) operations will freeze the entire Redis server, causing all other client requests to timeout. Developers should design scripts to execute in microseconds and avoid slow operations.
Script Management: SCRIPT LOAD and EVALSHA
To run a Lua script, developers use the EVAL command, passing the script source code, key names, and arguments on every request. While convenient during development, sending large script blocks over the network on every query wastes bandwidth and increases parsing overhead. To optimize this, Redis uses script caching.
Using the SCRIPT LOAD command, clients pre-load a Lua script into the Redis cache. Redis compiles the script and returns a 40-character SHA1 hash of the source code. The client can then execute the script using the EVALSHA command, passing only the SHA1 hash instead of the full script source. If the script is not cached, the server returns a NOSCRIPT error, prompting the client to load the script and retry. This mechanism reduces network overhead, making script execution highly efficient.
When writing scripts, developers must follow a strict rule: scripts must be deterministic. Redis replicates Lua scripts to replica servers. If a script generates random numbers or reads the current system clock, the replica state will drift from the master. To prevent this, Redis requires all script inputs (such as random seeds or timestamps) to be passed as arguments from the client, keeping replication consistent.
// Executing a Atomic Lua Rate Limiting Script in Node.js const Redis = require('ioredis'); const redis = new Redis({ host: '127.0.0.1', port: 6379 }); const rateLimitScript = ` local key = KEYS[1] local limit = tonumber(ARGV[1]) local window = tonumber(ARGV[2]) local current = tonumber(redis.call('get', key) or '0') if current >= limit then return 0 -- Rate limit exceeded else redis.call('incr', key) if current == 0 then redis.call('expire', key, window) end return 1 -- Request allowed end `; async function checkRateLimit(key, limit, window) { // Execute Lua script atomically on the Redis server // Key count is specified as 1, followed by keys and arguments const allowed = await redis.eval(rateLimitScript, 1, key, limit, window); return allowed === 1; }
Knowledge Check
Ready to test your understanding of 14. Server-side Execution: Lua Scripting in Redis?