0
0
Redisquery~5 mins

Atomic operations with Lua in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Atomic operations with Lua
O(1)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

The script runs a fixed number of commands regardless of the value size.

Input Size (n)Approx. Operations
103 Redis commands
1003 Redis commands
10003 Redis commands

Pattern observation: The number of operations stays the same no matter how big the number is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the script stays constant no matter the input size.

Common Mistake

[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.

Interview Connect

Understanding how atomic Lua scripts run helps you write safe and efficient Redis operations in real projects.

Self-Check

"What if the script included a loop to increment multiple keys? How would the time complexity change?"