Logic Next to the Data
Sometimes you need several Redis operations to happen together, depending on each other's results. Lua scripting lets you send a script that Redis runs server side and atomically, eliminating round trips and race conditions.
- EVAL runs a script with declared keys and arguments.
- SCRIPT LOAD caches a script and returns a hash, then EVALSHA runs it by hash to avoid resending the body.
Atomic by Design
A script runs as a single unit: no other command interleaves while it executes. This makes patterns like check then set trivially safe. For example, read a counter, compare it to a limit, and increment only if under the limit, all without another client sneaking in between.
Rules That Keep It Safe
- Declare every key the script touches in the KEYS array so it works correctly on a cluster, where all keys must share a slot.
- Scripts must be deterministic: avoid random values or wall clock time that would make replicas diverge.
- Keep scripts short. Because they block the server, a slow script stalls every other client.
Lua is the classic tool for atomic multi step operations like rate limiters, conditional updates, and dequeue with bookkeeping.
Key idea
A Lua script runs atomically on the Redis server in one round trip, making multi step check then act logic safe, provided it is short, deterministic, and declares its keys.