Why pub/sub enables real-time messaging in Redis - Performance Analysis
We want to understand how the time it takes to send messages changes as more messages or subscribers are involved in Redis pub/sub.
How does Redis handle sending messages quickly to many listeners?
Analyze the time complexity of the following Redis pub/sub commands.
# Subscriber subscribes to a channel
SUBSCRIBE news
# Publisher sends a message to the channel
PUBLISH news "Hello subscribers!"
# Redis delivers the message to all subscribers of 'news'
This code shows how Redis sends a message to all clients subscribed to a channel.
Look at what repeats when a message is published.
- Primary operation: Redis sends the message to each subscriber of the channel.
- How many times: Once for each subscriber connected to that channel.
As the number of subscribers grows, the work Redis does grows too.
| Input Size (subscribers) | Approx. Operations |
|---|---|
| 10 | 10 message sends |
| 100 | 100 message sends |
| 1000 | 1000 message sends |
Pattern observation: The work grows directly with the number of subscribers. More subscribers mean more message sends.
Time Complexity: O(n)
This means the time to deliver a message grows linearly with the number of subscribers listening to the channel.
[X] Wrong: "Publishing a message takes the same time no matter how many subscribers there are."
[OK] Correct: Redis must send the message to each subscriber, so more subscribers mean more work and more time.
Understanding how message delivery time grows helps you explain real-time systems clearly and shows you know how scaling affects performance.
"What if Redis used a different method that sends one message to all subscribers at once? How would that change the time complexity?"