0
0
Redisquery~5 mins

Transactions vs Lua scripts in Redis - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Transactions vs Lua scripts
O(n)
Understanding Time Complexity

We want to understand how the time cost changes when using Redis transactions compared to Lua scripts.

How does the number of operations grow as we handle more commands inside these two methods?

Scenario Under Consideration

Analyze the time complexity of these Redis commands.


MULTI
SET key1 value1
SET key2 value2
SET key3 value3
EXEC

-- vs --

EVAL "redis.call('SET', KEYS[1], ARGV[1]); redis.call('SET', KEYS[2], ARGV[2]); redis.call('SET', KEYS[3], ARGV[3]);" 3 key1 key2 key3 value1 value2 value3
    

The first snippet uses a transaction with multiple commands queued and executed together. The second uses a Lua script to run the same commands atomically.

Identify Repeating Operations

Look at what repeats inside each method.

  • Primary operation: Setting keys with SET commands.
  • How many times: Three times in both cases.
  • In transactions, commands are queued then executed in one batch.
  • In Lua scripts, commands run inside the script without network round trips.
How Execution Grows With Input

As the number of commands increases, the total work grows.

Input Size (n)Approx. Operations
10About 10 SET commands executed
100About 100 SET commands executed
1000About 1000 SET commands executed

Pattern observation: The number of commands grows linearly with input size, so total work grows linearly too.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in direct proportion to the number of commands you run.

Common Mistake

[X] Wrong: "Lua scripts always run faster than transactions because they are scripts."

[OK] Correct: Both run commands one after another, so time grows with command count. Lua scripts reduce network trips but do not change the total command work.

Interview Connect

Understanding how Redis handles multiple commands helps you explain performance trade-offs clearly and shows you know how to reason about scaling operations.

Self-Check

What if we replaced multiple SET commands with a single Lua script that uses a loop to set keys? How would the time complexity change?