Lua vs transactions comparison in Redis - Performance Comparison
We want to understand how the time cost changes when using Lua scripts versus transactions in Redis.
Which method grows faster in execution time as the input size increases?
Analyze the time complexity of these two Redis approaches.
-- Lua script example
local vals = redis.call('LRANGE', KEYS[1], 0, -1)
for i, v in ipairs(vals) do
redis.call('HSET', KEYS[2], v, i)
end
-- Transaction example
MULTI
LRANGE mylist 0 -1
HSET myhash field1 val1
EXEC
The Lua script runs commands inside one script; the transaction groups commands to run atomically.
Look for repeated steps that affect time.
- Primary operation: Loop inside Lua script calling HSET for each list item.
- How many times: Once per list element (n times).
As the list size grows, the Lua script runs more HSET commands in one go.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 HSET calls inside Lua |
| 100 | About 100 HSET calls inside Lua |
| 1000 | About 1000 HSET calls inside Lua |
Pattern observation: The Lua script time grows roughly linearly with the number of list items.
Time Complexity: O(n)
This means the time grows in direct proportion to the number of items processed.
[X] Wrong: "Lua scripts always run instantly no matter the input size."
[OK] Correct: Lua scripts still do work for each item, so time grows with input size.
Knowing how Lua scripts and transactions scale helps you choose the right tool for efficient Redis operations.
What if the Lua script called multiple Redis commands per list item? How would the time complexity change?