0
0
RedisHow-ToBeginner · 3 min read

How Pub/Sub Works in Redis: Simple Explanation and Example

Redis Pub/Sub works by letting clients subscribe to channels and other clients publish messages to those channels. Subscribers instantly receive messages published to the channels they listen to, enabling real-time communication.
📐

Syntax

Redis Pub/Sub uses two main commands: SUBSCRIBE and PUBLISH.

  • SUBSCRIBE <channel>: Client listens to messages on the specified channel.
  • PUBLISH <channel> <message>: Client sends a message to all subscribers of that channel.

When a client subscribes, it waits for messages. When a message is published, Redis sends it to all subscribers immediately.

redis
SUBSCRIBE channel_name
PUBLISH channel_name message_text
💻

Example

This example shows one client subscribing to a channel and another client publishing a message. The subscriber receives the message instantly.

bash
# Terminal 1: Subscriber
redis-cli
SUBSCRIBE news

# Terminal 2: Publisher
redis-cli
PUBLISH news "Hello subscribers!"
Output
1) "message" 2) "news" 3) "Hello subscribers!"
⚠️

Common Pitfalls

Some common mistakes when using Redis Pub/Sub:

  • Subscribers must stay connected; if they disconnect, they miss messages.
  • Pub/Sub does not store messages; it only delivers to current subscribers.
  • Using Pub/Sub for critical data delivery is risky because messages can be lost if no subscriber is connected.

To avoid these, consider Redis Streams or other message queue systems for guaranteed delivery.

📊

Quick Reference

CommandDescription
SUBSCRIBE Listen to messages on a channel
UNSUBSCRIBE Stop listening to a channel
PUBLISH Send a message to all subscribers
PSUBSCRIBE Subscribe to channels matching a pattern
PUNSUBSCRIBE Unsubscribe from pattern subscriptions

Key Takeaways

Redis Pub/Sub enables real-time messaging by publishing to channels and subscribing to them.
Subscribers must stay connected to receive messages; messages are not stored.
Pub/Sub is best for transient messages, not guaranteed delivery.
Use SUBSCRIBE to listen and PUBLISH to send messages.
For reliable messaging, consider Redis Streams or other queue systems.