Atomic operations with Lua in Redis - Time & Space Complexity
When using Lua scripts in Redis, operations run as one single step without interruption.
We want to see how the time needed grows as the data size changes.
Analyze the time complexity of the following Lua script in Redis.
local key = KEYS[1]
local increment = tonumber(ARGV[1])
local current = redis.call('GET', key)
if not current then
redis.call('SET', key, increment)
else
redis.call('INCRBY', key, increment)
end
return redis.call('GET', key)
This script atomically increments a value stored at a key by a given amount.
Look for repeated actions or loops in the script.
- Primary operation: Single calls to Redis commands (GET, SET, INCRBY)
- How many times: Each command runs once per script execution; no loops or recursion.
The script runs a fixed number of commands regardless of the value size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 Redis commands |
| 100 | 3 Redis commands |
| 1000 | 3 Redis commands |
Pattern observation: The number of operations stays the same no matter how big the number is.
Time Complexity: O(1)
This means the time to run the script stays constant no matter the input size.
[X] Wrong: "The script takes longer if the number we add is bigger."
[OK] Correct: Redis commands here work in constant time; the size of the number does not affect how many steps the script takes.
Understanding how atomic Lua scripts run helps you write safe and efficient Redis operations in real projects.
"What if the script included a loop to increment multiple keys? How would the time complexity change?"