0
0
Redisquery~10 mins

Atomic operations with Lua in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Atomic operations with Lua
Start Lua script
Execute commands inside script
Commands run atomically
Return result
End script execution
Lua scripts in Redis run all commands inside them as one atomic operation, so no other commands run in between.
Execution Sample
Redis
redis.eval("return redis.call('incr', KEYS[1])", 1, 'counter')
This Lua script increments the 'counter' key atomically and returns the new value.
Execution Table
StepActionCommand ExecutedKey State BeforeKey State AfterResult
1Start script----
2Call redis.call('incr', 'counter')INCR countercounter=5counter=66
3Return result---6
4End script----
💡 Script ends after returning the incremented value; all commands ran atomically.
Variable Tracker
VariableStartAfter Step 2Final
counter566
Key Moments - 2 Insights
Why does the counter not change between steps 2 and 3?
Because the Lua script runs atomically, no other commands can run between steps 2 and 3, so the counter stays at 6 as updated in step 2.
Can other Redis commands run while the Lua script is executing?
No, Redis blocks other commands during the Lua script execution to ensure atomicity, as shown by the uninterrupted steps in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'counter' after step 2?
A6
B5
C7
DUndefined
💡 Hint
Check the 'Key State After' column in step 2 of the execution_table.
At which step does the Lua script return the incremented value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Result' column in the execution_table for the return action.
If another client tries to increment 'counter' during the script execution, what happens?
AIt increments immediately
BIt causes an error
CIt waits until the script finishes
DIt increments before the script
💡 Hint
Refer to the key_moments section about atomicity and command blocking.
Concept Snapshot
Lua scripts in Redis run atomically.
All commands inside a script execute without interruption.
Use redis.call() to run Redis commands inside Lua.
No other commands run until the script finishes.
This ensures consistent and safe updates.
Full Transcript
This visual execution trace shows how Redis runs Lua scripts atomically. The script starts and executes the INCR command on the 'counter' key. The counter value changes from 5 to 6 inside the script. Because the script runs atomically, no other commands can run between these steps. The script then returns the new counter value 6 and ends. This atomic behavior prevents race conditions and ensures data consistency in Redis.