Real-Time PubSub
Discover how real-time publish-subscribe systems instantly push messages to all connected subscribers, enabling ultra-low-latency communication for chat apps and live updates.
Unlike queues and streams where consumers pull messages, PubSub pushes messages instantly to everyone subscribed. No buffering, no waiting - just immediate broadcast to all connected clients.
EXERCISE
1Push vs Pull: The Key Difference
Message queues and Kafka use pull: consumers fetch messages when ready. PubSub uses push: messages broadcast instantly to all subscribers the moment they arrive.
The Pull Model: Queues and Kafka
Message Queues (RabbitMQ, SQS): Workers pull messages from the queue when ready.
Kafka: Consumers pull messages and track progress with offsets.
Key characteristic: Consumers control the pace. They ask for messages when ready to process them.
The Push Model: PubSub
Redis PubSub: When a message arrives, immediately pushes it to all connected subscribers.
No pulling needed: Subscribers sit idle, listening. Messages arrive automatically.
Why This Difference Matters
Pull Model Benefits:
- Workers process at their own pace
- Messages buffer if workers are slow
- Good for background jobs
Push Model Benefits:
- Ultra-low latency (milliseconds)
- Instant delivery to all subscribers
- Perfect for real-time updates
Real-World Analogy
Pull (Queue): Restaurant kitchen. Waiters grab orders when ready to serve.
Push (PubSub): Fire alarm. When triggered, sound blasts to everyone instantly. No one pulls the alarm sound - it pushes to everyone.
When to Use Each
Use Pull (Queues/Kafka): Background processing, video encoding, email sending, data pipelines.
Use Push (PubSub): Chat messages, live notifications, configuration updates, real-time dashboards.
EXERCISE
2How Redis PubSub Works
Redis PubSub acts as a broadcast channel. Subscribers connect to a channel. When a publisher sends a message, Redis pushes it instantly to everyone subscribed at that moment.
Redis PubSub Architecture
Channels: Named topics like "chat-room-5" or "config-updates".
Publishers: Services that send messages to channels.
Subscribers: Services that listen to channels and receive messages instantly.
Simple Flow
- Subscriber A connects to channel "notifications"
- Subscriber B connects to channel "notifications"
- Subscriber C connects to channel "notifications"
- Publisher sends message to "notifications"
- Redis immediately pushes to A, B, and C simultaneously
All three receive the message at nearly the same instant.
Code Example
Subscriber (listening):
import redis
r = redis.Redis()
pubsub = r.pubsub()
pubsub.subscribe("chat")
for message in pubsub.listen():
print(f"Received: {message}")
Publisher (sending):
import redis
r = redis.Redis()
r.publish("chat", "Hello everyone!")
The moment publish executes, all subscribers listening to "chat" receive "Hello everyone!" instantly.
Key Properties
Instant broadcast: No delay. Message arrives in milliseconds.
Multiple subscribers: All connected subscribers receive the same message.
No persistence: Redis does not store messages. Only live subscribers receive them.
Pattern Matching
Subscribers can listen to multiple channels using patterns:
pubsub.psubscribe("room:*") # Matches room:1, room:2, room:3
Now subscriber receives messages from all channels starting with "room:".
EXERCISE
3Real-World Use Cases
Chat applications use PubSub for instant message delivery. Configuration management uses it to push updates to all servers simultaneously without polling.
Use Case 1: Live Chat Applications
Problem: Users expect instant message delivery. Polling every second wastes resources.
PubSub Solution:
- User A sends message in chat room
- Backend publishes to Redis channel "room:123"
- All users in room 123 are subscribed to "room:123"
- Redis pushes message instantly to all connected users
- Messages appear in milliseconds
Why PubSub wins: No polling. Instant delivery. Scales to thousands of concurrent users per room.
Use Case 2: Configuration Updates
Problem: You have 100 servers. Need to update or config value across all servers instantly.
PubSub Solution:
- All 100 servers subscribe to "config-updates" channel
- Admin changes config in dashboard
- Dashboard publishes new config to "config-updates"
- All 100 servers receive update instantly
- Servers apply new config without restart
Why PubSub wins: No need to poll config service. Instant propagation. Zero restart downtime.
Use Case 3: Real-Time Dashboards
Problem: Dashboard shows live metrics (active users, orders per minute). Needs fresh data constantly.
PubSub Solution:
- Dashboard subscribes to "metrics-stream"
- Backend publishes new metrics every second
- Dashboard receives and updates graphs in real-time
- Users see live data without refreshing
Why PubSub wins: Push eliminates constant polling. Lower latency. Smoother user experience.
Use Case 4: Multiplayer Game State
Problem: Game state changes need instant sync across all players.
PubSub Solution:
- Player moves character
- Game publishes "player-moved" event
- All connected players receive update instantly
- Character positions sync in real-time
Why PubSub wins: Low latency critical for games. PubSub provides sub-100ms delivery.
Common Pattern: Broadcast to Multiple Servers
Many servers connected to same PubSub channel. One server publishes. All receive. Perfect for:
- Invalidating caches across servers
- Broadcasting system events
- Coordinating distributed tasks
EXERCISE
4The No-Buffering Trade-off
PubSub does not store messages. If a subscriber disconnects, it misses messages sent during downtime. When it reconnects, it only receives new messages - no historical replay.
The Critical Limitation
Redis PubSub does not buffer messages. This is not a bug - this is by design for speed.
What Happens When Subscribers Disconnect
Scenario:
- Subscriber connects to "notifications"
- Receives messages 1, 2, 3
- Subscriber crashes (network issue, server restart)
- Messages 4, 5, 6, 7 are published
- Subscriber reconnects
Result: Subscriber receives messages starting from 8 onward. Messages 4-7 are permanently lost for this subscriber.
Why No Buffering?
Speed: Storing messages adds latency. PubSub optimizes for instant delivery, not reliability.
Memory: Buffering millions of messages consumes massive memory.
Design philosophy: PubSub assumes subscribers are always connected. If they are not, they miss messages.
Testing This Yourself
Experiment:
- Start subscriber listening to channel
- Publish 5 messages - subscriber receives all 5
- Stop subscriber
- Publish 5 more messages
- Restart subscriber
- Publish 2 messages
Observation: Subscriber only receives the final 2 messages. The 5 sent during downtime are lost.
When This Is Acceptable
Chat apps: Missing a few messages during disconnect is fine. User scrolls up to see recent history from .
Live dashboards: Only current data matters. Missing a few seconds of metrics is acceptable.
Configuration updates: Servers can query latest config on startup. Missing one push message is not critical.
When This Is NOT Acceptable
Financial transactions: Cannot afford to miss any event. Use Kafka instead.
Audit logs: Every event must be recorded. Use message queues with persistence.
Critical notifications: Payment confirmations, security alerts need guaranteed delivery. Use queues.
Hybrid Approach
Many systems combine both:
Redis PubSub: Real-time delivery to online users Database + Polling: Backup for offline users or critical messages
Example: WhatsApp uses PubSub for instant delivery to online users. If you are offline, messages wait in a persistent queue until you reconnect.
Key Takeaway
Redis PubSub is fast but not reliable. Use it when:
- Speed is more important than guaranteed delivery
- Subscribers stay connected most of the time
- Missing occasional messages is acceptable
For critical data requiring durability, use Kafka or message queues instead.
