0
0
Redisquery~5 mins

MULTI command to start in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: MULTI command to start
O(n)
Understanding Time Complexity

We want to understand how the time needed to run Redis commands changes when using the MULTI command to start a transaction.

Specifically, we ask: how does the number of operations grow as we add more commands inside a MULTI block?

Scenario Under Consideration

Analyze the time complexity of the following Redis commands using MULTI.


MULTI
SET key1 value1
SET key2 value2
SET key3 value3
EXEC
    

This code starts a transaction with MULTI, queues three SET commands, then runs them all at once with EXEC.

Identify Repeating Operations

Look for repeated actions inside the transaction.

  • Primary operation: Queuing each SET command inside MULTI.
  • How many times: Once per command added to the transaction (3 times here).
How Execution Grows With Input

As you add more commands inside MULTI, the number of operations grows roughly the same as the number of commands.

Input Size (n commands)Approx. Operations
10About 10 queue operations plus 1 EXEC
100About 100 queue operations plus 1 EXEC
1000About 1000 queue operations plus 1 EXEC

Pattern observation: The total work grows linearly with the number of commands queued.

Final Time Complexity

Time Complexity: O(n)

This means the time to queue commands inside MULTI grows in direct proportion to how many commands you add.

Common Mistake

[X] Wrong: "Using MULTI makes all commands run instantly together, so time does not grow with more commands."

[OK] Correct: Even though commands run as a group, Redis still queues each command one by one, so the time to queue grows with the number of commands.

Interview Connect

Understanding how MULTI queues commands helps you explain transaction costs clearly and shows you know how Redis handles grouped commands efficiently but not magically instantly.

Self-Check

"What if we replaced multiple SET commands inside MULTI with a single Lua script? How would the time complexity change?"