UNSUBSCRIBE behavior in Redis - Time & Space 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.
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.
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.
The time to unsubscribe grows with the number of channels you ask to leave.
| Input Size (channels to unsubscribe) | Approx. Operations |
|---|---|
| 10 | About 10 removals |
| 100 | About 100 removals |
| 1000 | About 1000 removals |
Pattern observation: The work grows directly with how many channels you unsubscribe from.
Time Complexity: O(n)
This means the time to unsubscribe grows in a straight line with the number of channels you remove.
[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.
Understanding how commands scale helps you write efficient code and explain your reasoning clearly in interviews.
What if Redis stored subscribers in a way that allowed instant removal regardless of channel count? How would the time complexity change?