MULTI command to start in Redis - Time & Space 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?
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.
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).
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 |
|---|---|
| 10 | About 10 queue operations plus 1 EXEC |
| 100 | About 100 queue operations plus 1 EXEC |
| 1000 | About 1000 queue operations plus 1 EXEC |
Pattern observation: The total work grows linearly with the number of commands queued.
Time Complexity: O(n)
This means the time to queue commands inside MULTI grows in direct proportion to how many commands you add.
[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.
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.
"What if we replaced multiple SET commands inside MULTI with a single Lua script? How would the time complexity change?"