Pub/Sub Messaging
Redis provides a messaging system that allows applications to communicate with each other in real-time using the Publisher/Subscriber pattern.
1. How it Works
In Pub/Sub, the sender (publisher) does not send messages to specific receivers (subscribers). Instead, messages are published to channels. Subscribers listen to one or more channels and receive messages as they are sent.
[!NOTE] Redis Pub/Sub is fire-and-forget. If a subscriber is offline when a message is sent, it will never receive that message. For persistent messaging, use Redis Streams.
2. Basic Commands
Subscribing to a Channel
SUBSCRIBE news_channelPublishing to a Channel
PUBLISH news_channel "Hello, World!"Pattern Matching
You can subscribe to multiple channels using glob-style patterns.
PSUBSCRIBE news_* # Subscribes to news_tech, news_sports, etc.3. Use Cases
- Real-time Notifications: Triggering alerts in web-sockets.
- Microservices Communication: Signaling between services when an event occurs.
- Chat Systems: Basic message routing between users.
4. Pub/Sub vs. Streams
| Feature | Pub/Sub | Streams |
|---|---|---|
| Persistence | No (Real-time only) | Yes (Stored on disk) |
| Delivery Model | Push (Fan-out) | Pull (Iterators/Consumer Groups) |
| History | Cannot retrieve past messages | Can replay history |
| Suitability | Simple real-time signals | Complex message workflows |