Learn Redis · 9/15

Real-time Messaging: The Pub/Sub Paradigm

6 min read

Real-time Messaging: The Pub/Sub Paradigm 📢

Welcome! In the world of modern applications, instant communication is often key. Think of live chat applications, real-time notifications for a food delivery app, or live dashboards for data analytics. The challenge is how to get information from one part of a system to another, or even to multiple other parts, instantly and efficiently.

This is where the Publish/Subscribe, or Pub/Sub, pattern comes into play. It's a messaging pattern that allows for communication between different components of a system without them having to know about each other directly.


1. The Publisher/Subscriber Pattern Explained 🤔

The Problem: Imagine a central announcement system in a large airport. The announcer doesn't need to know every single passenger's name and location to deliver a message. They just make an announcement over the PA system for a specific flight, and only the passengers at the relevant gate will pay attention.

In software, a similar problem exists. If one service (e.g., a payment service) needs to notify other services (e.g., an order fulfillment service and a notification service) about a new transaction, a direct connection would create tight coupling. If a new service needs to be notified, the payment service's code would have to be changed. This is not scalable or maintainable.

The Solution: The Pub/Sub pattern introduces a middleman, often called a "broker" or "channel".

  • Publishers: These are the components that send messages. They don't send messages to specific recipients. Instead, they publish messages to a specific channel. In our airport analogy, the announcer is the publisher.
  • Subscribers: These are the components that receive messages. They express interest in one or more channels and will receive any messages sent to those channels. The passengers waiting for a specific flight are the subscribers.
  • Channels: These are the pathways through which messages are sent. Think of them as the different radio frequencies or the specific gates at the airport.

This decoupling of publishers and subscribers is a core benefit, allowing for greater scalability and a more dynamic network topology.

Fun Fact: The publish-subscribe pattern is a key enabler for many of the real-time features we use daily. Social media platforms use it to send notifications about new posts or comments to interested users.


2. Sending Messages: The PUBLISH Command 📤

In Redis, the PUBLISH command is how you send a message to a channel. It's a straightforward command that takes two arguments: the name of the channel and the message you want to send.

How it works: When a client issues a PUBLISH command, Redis sends the message to all clients currently subscribed to that channel. The command itself returns the number of clients that received the message.

Let's see it in action:

Imagine we have a channel for a live chat in a specific game lobby, let's call it game:lobby:123.

To send a message to this channel, you would use the following command in redis-cli:

bash
PUBLISH game:lobby:123 "Hey everyone, ready to start?"

If there are, for example, 3 other players subscribed to this channel, Redis would return:

hy
(integer) 3

What if no one is listening? 🦗 If you publish a message to a channel that has no subscribers, the message is simply discarded. It doesn't get stored anywhere. This "fire-and-forget" nature is a crucial aspect to remember, which we'll discuss more later.

Industry Practice: It's a good practice to use a consistent and descriptive naming convention for your channels. Using a colon-separated format like object:id:action (e.g., user:123:updated) can make your channels more organized and easier to manage, especially when using pattern-based subscriptions.


3. Listening for Messages: SUBSCRIBE and PSUBSCRIBE 🎧

Now that we know how to send messages, let's see how to receive them. Redis provides two primary commands for this: SUBSCRIBE and PSUBSCRIBE.

SUBSCRIBE

The SUBSCRIBE command allows a client to subscribe to one or more specific channels. Once a client is in "subscribe mode," it can only listen for messages and cannot execute any other commands (with a few exceptions like UNSUBSCRIBE).

Example:

To subscribe to our game:lobby:123 channel, you would use:

bash
SUBSCRIBE game:lobby:123

The client will then block and wait for messages on this channel. When a message is published to game:lobby:123, the subscribed client will receive it.

You can also subscribe to multiple channels at once:

bash
SUBSCRIBE game:lobby:123 game:lobby:456

PSUBSCRIBE

What if you want to listen to all game lobbies? Or all updates related to a specific user? This is where PSUBSCRIBE (Pattern Subscribe) comes in handy. It allows you to subscribe to channels that match a certain pattern using wildcards.

The supported patterns are:

  • *: Matches any sequence of characters.
  • ?: Matches a single character.
  • []: Matches any of the characters enclosed in the brackets.

Example:

To subscribe to all messages in any game lobby, you could use:

bash
PSUBSCRIBE game:lobby:*

Now, this client will receive messages published to game:lobby:123, game:lobby:456, and any other channel that starts with game:lobby:.

Under the Hood: When you use PSUBSCRIBE, Redis doesn't just match the pattern at the time of subscription. It actively matches incoming PUBLISH commands against the registered patterns and forwards the messages accordingly.

Funny Exaggeration: Imagine trying to listen to every conversation at a party. That's PSUBSCRIBE *! You'd get a lot of noise, but you wouldn't miss a thing. Use patterns wisely to filter out the chatter you don't care about.


4. Limitations of Pub/Sub: Fire-and-Forget Messaging 🔥

Redis Pub/Sub is incredibly fast and simple, but it comes with some important limitations you need to be aware of. The most significant is its "fire-and-forget" nature.

No Message Persistence: If a subscriber is not connected when a message is published, it will miss that message forever. Redis does not store messages for later delivery. Once a message is sent, it's gone.

At-Most-Once Delivery: This means that a message will be delivered either once or not at all. There are no guarantees that a message will be delivered. If a subscriber disconnects at the exact moment a message is being sent, it might miss it.

Scalability Concerns: While Redis itself is very scalable, the Pub/Sub mechanism can face challenges with a very large number of subscribers, as it has to push the message to every single one.

When is this a problem?

If your application requires:

  • Guaranteed message delivery: For things like financial transactions or critical system events, you cannot afford to lose messages.
  • Message history or replayability: If a new service comes online, it might need to process past events.
  • Complex routing and message queuing: For more advanced messaging scenarios, you might need features like message acknowledgment and routing.

In these cases, other technologies like Redis Streams (which offers more durability) or dedicated message brokers like RabbitMQ or Apache Kafka might be a better fit.

So, when is Redis Pub/Sub a great choice?

It excels in situations where real-time, transient messaging is the priority. Think of:

  • Live chat applications
  • Real-time notifications and updates
  • Event-driven architectures for non-critical events

It's all about choosing the right tool for the job! 🛠️


Extra Reading & References 📚

Challenge

Challenge: Real-Time Game Lobby Notifications

You are tasked with designing the command sequence for a real-time game lobby notification system using Redis Pub/Sub. The system has three components: a Player Client, an Admin Client, and a Game Server.

The channel naming convention for lobby-specific events is game:lobby:<lobby_id>:<action>.

Your task is to write the correct Redis commands for the following operations:

  1. Player Client: This client needs to receive all updates (e.g., join, leave, start) for a specific game lobby with the ID solaris-7.
  2. Admin Client: This client needs a high-level view and must receive all updates for every game lobby, regardless of the lobby ID or the action.
  3. Game Server: This client is responsible for publishing events. Write the commands for these sequential events:
    • A player named 'Riker' joins lobby solaris-7. The message payload should be {"player":"Riker", "rank":"Commander"}.
    • A global system-wide announcement is published on the system:alerts channel. The message is Maintenance window scheduled.

Expected result

Correct Redis Commands

The solution requires the correct application of SUBSCRIBE, PSUBSCRIBE, and PUBLISH to fulfill the requirements of each client.

  1. Player Client Subscription:
    To subscribe to a specific channel pattern, the PSUBSCRIBE command is used with a wildcard. This ensures the client receives messages for any action within the solaris-7 lobby.

    redis
    PSUBSCRIBE game:lobby:solaris-7:*
  2. Admin Client Subscription:
    To monitor all lobby activities, the admin client uses PSUBSCRIBE with wildcards for both the lobby ID and the action.

    redis
    PSUBSCRIBE game:lobby:*:*
  3. Game Server Publications:
    The server uses the PUBLISH command, specifying the exact channel and the message for each event.

    redis
    PUBLISH game:lobby:solaris-7:join "{\"player\":\"Riker\", \"rank\":\"Commander\"}"
    PUBLISH system:alerts "Maintenance window scheduled"
plaintext

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.