Database
NoSQL
Redis
Pub/Sub Messaging

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_channel

Publishing 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

FeaturePub/SubStreams
PersistenceNo (Real-time only)Yes (Stored on disk)
Delivery ModelPush (Fan-out)Pull (Iterators/Consumer Groups)
HistoryCannot retrieve past messagesCan replay history
SuitabilitySimple real-time signalsComplex message workflows