Pub/Sub Messaging in Redis

Welcome back! In this lesson, we will dive into another powerful feature of Redis: Publish/Subscribe (Pub/Sub) messaging. This topic builds on our understanding of Redis and introduces a dynamic way to enable real-time communication within your applications.

What You'll Learn

In this lesson, you will learn how to set up and use Redis Pub/Sub messaging to send and receive messages between different parts of your application. This is useful for creating real-time features like notifications, chat systems, or live updates.

Here's a sneak peek at how you can set up a simple Pub/Sub system in Redis:

import Redis from 'ioredis';

// Create two Redis clients: one for publishing, one for subscribing
const publisher = new Redis('redis://localhost:6379');
const subscriber = new Redis('redis://localhost:6379');

publisher.on('error', (err) => {
  console.error('Error connecting to Redis (publisher)', err);
});
subscriber.on('error', (err) => {
  console.error('Error connecting to Redis (subscriber)', err);
});

// Function to handle incoming messages
function messageHandler(channel, message) {
  console.log(`Received message on channel "${channel}": ${message}`);
}

async function runPubSub() {
  // Subscribe to the "notifications" channel
  await subscriber.subscribe('notifications');

  // Listen for messages on the subscribed channel
  subscriber.on('message', messageHandler);

  // Give the subscription a moment to set up
  await new Promise(resolve => setTimeout(resolve, 1000));

  // Publish a message to the "notifications" channel
  const publishResult = await publisher.publish('notifications', 'Hello, Redis!');
  console.log(`Message published, number of subscribers that received the message: ${publishResult}`);

  // Give some time for the message to be received
  await new Promise(resolve => setTimeout(resolve, 1000));

  // Unsubscribe and disconnect
  await subscriber.unsubscribe('notifications');
  subscriber.disconnect();
  publisher.disconnect();
}

runPubSub();

Let's break down the code snippet above:

  • Two Redis clients are created: one for publishing messages and one for subscribing to channels.
  • The messageHandler function prints any message received on a subscribed channel.
  • The subscriber client subscribes to the notifications channel and listens for messages.
  • After a short delay to ensure the subscription is active, a message is published to the notifications channel.
  • The number of subscribers that received the message is printed.
  • After another short delay, the subscriber unsubscribes from the channel, and both clients disconnect.

The output will be:

text
Message published, number of subscribers that received the message: 1
Received message on channel "notifications": Hello, Redis!

Note that Redis Pub/Sub does not support multiplexing commands on the same client once it has subscribed to a channel. That’s why it's necessary to create separate connections for publishing and subscribing. If you attempt to run other Redis commands on a subscribed client, they will be blocked until you unsubscribe. This is a common mistake developers make when using Pub/Sub in real-world apps.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal