0
0
Redisquery~5 mins

UNSUBSCRIBE behavior in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: UNSUBSCRIBE behavior
O(n)
Understanding Time Complexity

When using Redis PUB/SUB, the UNSUBSCRIBE command stops the client from receiving messages on certain channels.

We want to understand how the time it takes to unsubscribe changes as the number of channels grows.

Scenario Under Consideration

Analyze the time complexity of this Redis UNSUBSCRIBE command usage.


# Client is subscribed to multiple channels
UNSUBSCRIBE channel1 channel2 channel3
# Server removes client from these channels
# If no channels specified, unsubscribe from all

This code unsubscribes the client from one or more channels, or all if none are specified.

Identify Repeating Operations

Look for repeated actions inside the UNSUBSCRIBE process.

  • Primary operation: Removing the client from each specified channel's subscriber list.
  • How many times: Once per channel to unsubscribe; if no channels given, once per all subscribed channels.
How Execution Grows With Input

The time to unsubscribe grows with the number of channels you ask to leave.

Input Size (channels to unsubscribe)Approx. Operations
10About 10 removals
100About 100 removals
1000About 1000 removals

Pattern observation: The work grows directly with how many channels you unsubscribe from.

Final Time Complexity

Time Complexity: O(n)

This means the time to unsubscribe grows in a straight line with the number of channels you remove.

Common Mistake

[X] Wrong: "Unsubscribing from many channels happens instantly, no matter how many."

[OK] Correct: Each channel requires work to remove the client, so more channels mean more time.

Interview Connect

Understanding how commands scale helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

What if Redis stored subscribers in a way that allowed instant removal regardless of channel count? How would the time complexity change?