Dragonfly

Redis Pub/Sub: Use Cases, Tutorial & Alternatives

Redis Pub/Sub is a messaging feature in Redis that allows applications to send and receive messages in real time using a publish/subscribe pattern.

August 24, 2025

Redis Pub/Sub | Cover Image

What Is Redis Pub/Sub? 

Redis Pub/Sub is a messaging feature in Redis that allows applications to send and receive messages in real time using a publish/subscribe pattern. In this paradigm, publishers send messages to channels without specifying recipients, while subscribers listen to channels to receive messages that are relevant to them. 

Unlike some traditional message queues, there is no need for publishers to be aware of who is listening or how the messages are handled after publishing. This decoupling makes Pub/Sub ideal for event-driven and distributed systems that require real-time updates.

The Redis Pub/Sub mechanism is built into the core Redis server. It can handle hundreds of thousands of messages per second with minimal latency. Subscribers receive messages instantly as soon as they are published to the channel. However, Pub/Sub in Redis is not persistent—if a client is offline when a message is published, it will not receive that message.

In this article:

  • How Redis Pub/Sub Works
  • Use Cases of Redis Pub/Sub
  • Tutorial: How to Use Pub/Sub Channels in Redis
  • Redis Pub/Sub Compared to Other Messaging Systems
  • Best Practices for Using Redis Pub/Sub

How Redis Pub/Sub Works 

Redis Pub/Sub operates on a publish/subscribe messaging model, where clients (publishers) send messages to channels, and other clients (subscribers) listen for those messages.

In Redis, channels are logical pathways for message delivery. However, they do not store messages or maintain a message history. A publisher sends a message to a channel without needing to know who the subscribers are. Subscribers can listen to one or more channels and receive messages as soon as they are published. This decouples the publisher from the subscriber, meaning publishers don’t need to be aware of the number or type of subscribers.

When a client subscribes to a channel in Redis, it starts receiving any messages that are published to that channel. The communication is asynchronous, meaning the publisher does not wait for confirmation from subscribers before continuing its process. This ensures that the messaging system operates with low latency and high throughput.

Redis uses the concept of a broker (the Redis server itself), which manages message routing from publishers to subscribers. The broker ensures messages reach all subscribers in real time, with minimal delay, often within milliseconds, depending on network conditions. However, since Redis Pub/Sub is ephemeral, messages that are published while a client is not connected will be lost. Moreover, Redis Pub/Sub channels and messages are not part of RDB or AOF persistence mechanisms. This characteristic makes it suitable for real-time communication but not for cases where message durability is required.

Redis Pub/Sub supports several communication models:

  • Channel-Based Messaging: This is the core model where publishers send messages to named channels, and subscribers receive messages from those channels. It’s suitable for direct topic-based communication where both sides agree on the channel name.
  • Pattern-Based Subscriptions: Using PSUBSCRIBE, clients can subscribe to multiple channels using pattern matching. For example, a client can subscribe to logs.* to receive messages from all channels that match this pattern. This model is useful when managing dynamic or hierarchical topic structures.
  • Fan-Out Broadcasting: Redis Pub/Sub naturally supports fan-out messaging. When a message is published to a channel, it is broadcast to all active subscribers. This makes it ideal for real-time notification systems or event propagation in distributed systems.
  • One-Way Communication: Pub/Sub is optimized for unidirectional message flow—publishers send messages without waiting for responses. This model fits well with systems that require fire-and-forget messaging or telemetry collection.
  • Stateless Event Streaming: Since messages are transient and not stored, Redis Pub/Sub is suitable for stateless event streaming where each event is processed in real time without the need for history or replay. This supports scenarios like live metrics feeds or ephemeral alerts.

Use Cases of Redis Pub/Sub 

It’s important to realize that Redis Pub/Sub is very lightweight and volatile and may not be suitable for all applications. Read on further in this article to see how it compares to more robust systems like Redis Streams, BullMQ, and Kafka.

Real-Time Notifications and Alerts

Redis Pub/Sub excels in delivering real-time notifications and alerts due to its low-latency nature. Systems such as monitoring dashboards, trading platforms, or social media applications often need to notify users or services instantly when certain events occur. For these scenarios, Pub/Sub channels deliver messages that immediately inform subscribers about state changes, anomalies, or important updates.

By leveraging Redis Pub/Sub, organizations can create notification pipelines where services produce events, and clients or internal services respond automatically. For example, a financial system can alert traders of sudden market changes, or a server health monitor can notify administrators of CPU spikes or outages as soon as they happen.

Chat Applications Implementation

In multi-user chat applications, Redis Pub/Sub can manage message delivery between users who are actively connected. Each chat room can map to a Redis channel; when a participant sends a message, it’s published to the channel and instantly propagated to all other connected users. This model allows for group chat interactions and reduces the complexity of message routing.

Real-time synchronization provided by Pub/Sub ensures that all active users in a chat room see messages appear without lag. However, since Redis Pub/Sub does not persist messages, it is typically used in conjunction with another service responsible for message history or offline delivery.

Event Broadcasting in Microservices Architectures

Microservices often need to broadcast events about domain changes—like user sign-ups, order completions, or data updates—to other services in the system. Redis Pub/Sub provides a straightforward way to disseminate such events across decoupled services without creating hard dependencies between them. Services can subscribe to events they care about and react accordingly, allowing for scalable and maintainable system designs.

This method facilitates event-driven patterns and helps prevent bottlenecks. Instead of repeatedly polling a shared database or central service, microservices can be notified instantly as soon as an event is published.

IoT Sensor Data Distribution

In Internet of Things (IoT) architectures, thousands of sensors might produce data that needs to be ingested and processed by different applications or analytics services. Redis Pub/Sub provides a lightweight, scalable mechanism for distributing this sensor data in real time to interested consumers. Each sensor or device type can publish to its own channel, and processing services subscribe only to channels relevant to them.

This setup reduces network congestion and processing overhead since only services that need specific sensor data receive it. As new sensors or consumer services are added, they can begin sending or receiving data with minimal configuration changes.


Tutorial: How to Use Pub/Sub Channels in Redis 

To use Redis Pub/Sub channels, clients interact with a few core commands: SUBSCRIBE, UNSUBSCRIBE, and PUBLISH. Here’s a step-by-step guide on how to implement these commands in Redis. These instructions are adapted from the Redis documentation.

1. Subscribing to Channels

To start listening to messages, clients use the SUBSCRIBE command. A client can subscribe to one or more channels, which means they will receive messages published to those channels. Here’s an example of how to subscribe to two channels:

$> SUBSCRIBE channel1 channel2

Once a client subscribes to a channel, Redis will push messages sent to those channels in the order they were published. It’s important to note that, while subscribed, a client cannot issue any other Redis commands (except for commands like PING or UNSUBSCRIBE that are specifically allowed in this state).

2. Publishing Messages to Channels

To send messages to a channel, use the PUBLISH command. When you publish a message, Redis pushes the message to all clients that are subscribed to that channel. For example:

$>PUBLISH channel1 "Broadcasting to all subscribers"

This command sends the message "Broadcasting to all subscribers" to clients subscribed to channel1. Subscribers will instantly receive the message, with no delays.

3. Unsubscribing from Channels

If a client no longer wants to receive messages from a channel, it can unsubscribe using the UNSUBSCRIBE command:

$> UNSUBSCRIBE channel1

After unsubscribing, the client will stop receiving any further messages from that channel. If a client unsubscribes from all channels, they can resume issuing regular Redis commands.

4. Pattern Matching for Subscriptions

In addition to subscribing to specific channels, Redis allows clients to use pattern matching to subscribe to multiple channels at once. This is done using the PSUBSCRIBE command, where clients can use glob-style patterns. For example:

$> PSUBSCRIBE updates.*

This would subscribe the client to any channel whose name starts with update. (e.g., update.alerts, update.warnings, etc.). Pattern-based subscriptions are useful for scenarios where a client needs to listen to a range of channels without explicitly subscribing to each one.

5. Delivery Semantics

Redis Pub/Sub follows at-most-once message delivery semantics. This means that messages will only be delivered once to subscribers, and if a subscriber is offline when a message is published, it will not receive that message once it reconnects. This behavior makes Redis Pub/Sub ideal for use cases requiring real-time message delivery, but not for those needing message persistence.

6. Example Workflow

To demonstrate how these commands work together, let’s walk through an example:

A client subscribes to two channels:

$> SUBSCRIBE channel1 channel2

Another client publishes messages to those channels:

$> PUBLISH channel1 "Calling Channel 1"
$> PUBLISH channel2 "Calling Channel 2"

The first client receives the messages in real-time:

1) "message"
2) "channel1"
3) "Calling Channel 1"
1) "message"
2) "channel2"
3) "Calling Channel 2"

If the first client decides to unsubscribe from channel1:

$> UNSUBSCRIBE channel1

Finally, the first client stops receiving messages from channel1, but continues receiving messages from channel2.


Redis Pub/Sub Compared to Other Messaging Systems 

Redis Pub/Sub has several limitations, and many organizations prefer alternative systems for more complex use cases or those requiring reliability. Here are the most common options.

Redis Pub/Sub vs. Redis Streams

While Redis Pub/Sub is a lightweight messaging system that allows publishers to send messages to subscribers, Redis Streams offer more robust features. Streams are designed to provide message durability and persistence, ensuring that messages are saved to disk (if configured with AOF or RDB). This makes Redis Streams a better option for systems requiring message reliability. 

Additionally, Redis Streams support consumer groups, which enable multiple consumers to share the work of processing messages, making them suitable for distributed systems. In contrast, Redis Pub/Sub is more suited for real-time applications where messages are transient, and message loss is acceptable. Redis Streams, however, can be more complex to use and are often integrated into higher-level frameworks.

Redis Pub/Sub vs. BullMQ

BullMQ is a job and task queue framework built on top of Redis, leveraging Redis Streams for message handling. It provides a high-level API that abstracts the complexity of working directly with Redis Streams, offering features like job scheduling, retries, and priorities. With BullMQ, developers can focus on their application logic without worrying about the intricacies of Redis Streams. 

In contrast, Redis Pub/Sub is a much simpler messaging system but lacks the rich features needed for job management, retries, and other advanced use cases. BullMQ adds structure and functionality to Redis, making it a suitable choice for more complex workflows or background job processing.

Redis Pub/Sub vs. Apache Kafka

When it comes to durability and fault tolerance, Apache Kafka is often the preferred solution over Redis Pub/Sub. Redis Pub/Sub is designed as a "write-after" system, meaning messages are written to memory first and then optionally persisted to disk. This approach can lead to message loss in case of system failure, making Redis Pub/Sub unsuitable for applications where data durability is critical. 

Apache Kafka, on the other hand, is built for durability and high throughput, with persistent log storage that ensures messages are not lost. If you’re building a messaging system for applications where message integrity is paramount, like financial transactions or event sourcing, Kafka provides stronger guarantees than Redis Pub/Sub.


Best Practices for Using Redis Pub/Sub 

Use Descriptive and Consistent Channel Naming

Channel names should clearly reflect the type or purpose of the messages they carry. Descriptive and consistent channel naming improves maintainability, aids troubleshooting, and helps prevent accidental cross-talk between unrelated components. Using standard naming patterns, such as app:notifications:alerts or chat:room:123 makes it easier for developers to recognize and subscribe to the right channels.

Consistency in naming also simplifies automation and integration. When integrating with monitoring, alerting, or analytics tools, clear channel names reduce misconfigurations and improve data routing logic. Avoid ambiguities or overloaded terms, and document naming conventions across your engineering organization to ensure long-term maintainability.

Handle Subscriber Disconnections Gracefully

Since Redis Pub/Sub delivers messages only to active subscribers, applications should anticipate and handle disconnections—planned or unplanned. Implement reconnection logic in clients to restore subscriptions if network issues or server crashes occur. This reduces the risk of missing critical updates and ensures system resilience.

It’s also important to log or monitor subscriber status, so operators are aware of which clients are connected and able to receive data. Some use cases might need to combine Pub/Sub with persistent mechanisms for critical messages. Automated alerting on subscriber failures can further help prevent silent data loss in production.

Message Serialization Strategies

Messages sent through Redis Pub/Sub must be encoded in a format understood by all subscribers. JSON is a common serialization format because of its readability and support across languages, but Protocol Buffers or MessagePack may be used for efficiency or type safety. Standardizing message structure prevents bugs and reduces integration effort across heterogeneous systems.

When designing serialization, include versioning in your schema. This allows clients to gracefully handle changes in message formats over time. Avoid large or excessively nested structures when possible, as simpler messages are easier to serialize, transmit, and process in real time.

Consider Message Size and Frequency

Redis Pub/Sub operates with low latency but can be affected by large or overly frequent messages. Keep individual messages small and focused, and verify that subscriber and network capacity meets the expected traffic levels. Broadcasting too many large messages simultaneously can overwhelm subscribers or cause message drops.

For high-frequency or high-volume scenarios, consider segmenting channels by topic or using batching strategies in your application layer. This reduces contention and helps distribute the load more evenly, minimizing the chance of missed deliveries or resource bottlenecks. Test under load conditions that reflect production usage to validate performance.

Implement Message Filtering on the Client Side

Redis Pub/Sub routing is based on channels, not message contents. For scenarios where subscribers are interested in a subset of messages within a channel, implement client-side filtering. Each message should contain metadata that allows recipients to quickly determine if it’s relevant. For example, include fields like type, level, or user ID for efficient filtering logic.

This approach prevents unnecessary processing and ensures that subscribers handle only pertinent data. If strict topic separation is needed, break channels into narrower categories. However, when this is impractical, invest in robust filtering in the client to extract value from broader message streams.

Consider Durability & Guarantees

Redis Pub/Sub does not provide built-in durability or message acknowledgment, meaning that messages can be lost if subscribers are not connected or if there’s a system failure. Therefore, it’s crucial to evaluate whether your use case can tolerate this level of potential data loss. For critical messages, consider combining Pub/Sub with persistence mechanisms such as Redis Streams or external storage solutions. You could also implement message acknowledgment or retry logic at the application level to ensure that important messages are processed reliably.

If message durability is a strict requirement, ensure that your application design accommodates this by using features like Redis persistence (AOF or RDB) or integrating with tools like BullMQ, which provides built-in guarantees for job reliability. This approach can mitigate the risks of message loss and offer a more fault-tolerant architecture, ensuring that key messages are not missed even in the event of failure.


Dragonfly: The Next-Generation In-Memory Data Store

Dragonfly is a modern, source-available, multi-threaded, Redis-compatible in-memory data store that stands out by delivering unmatched performance and efficiency. Designed from the ground up to disrupt existing legacy technologies, Dragonfly redefines what an in-memory data store can achieve. With Dragonfly, you get the familiar API of Redis without the performance bottlenecks, making it an essential tool for modern cloud architectures aiming for peak performance and cost savings. Migrating from Redis to Dragonfly requires zero or minimal code changes.

Key Advancements of Dragonfly

  • Multi-Threaded Architecture: Efficiently leverages modern multi-core processors to maximize throughput and minimize latency.
  • Unmatched Performance: Achieves 25x better performance than Redis, ensuring your applications run with extremely high throughput and consistent latency.
  • Cost Efficiency: Reduces hardware and operational costs without sacrificing performance, making it an ideal choice for budget-conscious enterprises.
  • Redis API Compatibility: Offers seamless integration with existing applications and frameworks running on Redis while overcoming its limitations. Dragonfly works perfectly with BullMQ, as mentioned above, with much higher performance as well.
  • Innovative Design: Built to scale vertically and horizontally, providing a robust solution for rapidly growing data needs.

Dragonfly Cloud is a fully managed service from the creators of Dragonfly, handling all operations and delivering effortless scaling so you can focus on what matters without worrying about in-memory data infrastructure anymore.

Was this content helpful?

Help us improve by giving us your feedback.

Switch & save up to 80%

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost