When to Use Pub/Sub in Redis: Practical Guide and Examples
Pub/Sub in Redis when you need real-time messaging between different parts of your application without storing messages. It is ideal for event notifications, chat systems, or broadcasting updates where subscribers listen to channels and receive messages instantly.How It Works
Redis Pub/Sub works like a simple messaging system where senders (publishers) send messages to channels, and receivers (subscribers) listen to those channels to get messages instantly. Imagine a radio station broadcasting music (publisher) and listeners tuning in to that station (subscribers) to hear the music live.
When a message is published to a channel, Redis immediately delivers it to all clients subscribed to that channel. There is no message storage; if a subscriber is not connected at the time, it misses the message. This makes Pub/Sub fast and lightweight but not suitable for guaranteed delivery.
Example
This example shows a simple Redis Pub/Sub usage where one client subscribes to a channel and another publishes a message to it.
# In one terminal, subscribe to channel 'news' redis-cli SUBSCRIBE news # In another terminal, publish a message to 'news' redis-cli PUBLISH news "Hello subscribers!"
When to Use
Use Redis Pub/Sub when you want to send real-time messages to multiple parts of your app without saving those messages. Common uses include:
- Chat applications where users receive messages instantly.
- Live notifications or alerts in dashboards.
- Broadcasting events to multiple services or microservices.
- Decoupling components so they communicate without knowing each other directly.
It is not suitable when you need message durability or guaranteed delivery because messages are lost if no subscriber is listening.
Key Points
- Pub/Sub delivers messages instantly to all active subscribers.
- Messages are not stored; offline subscribers miss messages.
- Great for real-time, transient communication.
- Not for reliable message queues or persistence.