Redis Pub/Sub (Publish/Subscribe) is a lightweight messaging system that lets applications communicate in real time. It’s widely used in chat apps, live dashboards, notifications, and microservices. In this post, you’ll learn how to implement Redis Pub/Sub in Node.js using a simple example.
⚡ Redis Pub/Sub allows one part of your system to publish messages while others subscribe to receive them — instantly, without polling.
Introduction
The Publish/Subscribe pattern in Redis is ideal for event-driven systems. It lets you create channels where messages are broadcasted and received by multiple subscribers in real time.
1. Install and Connect Redis
First, install the official Redis client:
Then, import and connect the client in your Node.js application:
import { createClient } from "redis";
const client = createClient({
url: "redis://127.0.0.1:6379",
});
client.on("error", (err) => console.log("Redis Error", err));
// Connect to Redis
await client.connect();
console.log("Connected to Redis!");
2. Publisher — Send Messages
The publisher sends messages to a Redis channel using publish(). Here’s a simple example that sends the current time every 2 seconds.
// publisher.js
setInterval(async () => {
const message = `Current Time: ${new Date().toISOString()}`;
await client.publish("time_channel", message);
console.log("📤 Published:", message);
}, 2000);
Every 2 seconds, a message is sent to the time_channel.
🧠 Tip: Each channel acts as a topic — you can have multiple publishers and subscribers communicating through different channels.
3. Subscriber — Receive Messages
In another file, create a subscriber that listens for messages on the same channel:
// receiver.js
await client.subscribe("time_channel", (message) => {
console.log("📥 Received:", message);
});
Once the subscriber is connected, it will automatically receive every message published on that channel.
✅ Redis Pub/Sub is blazing fast — it delivers messages instantly across connected clients without writing anything to disk.
Redis Pub/Sub offers a simple yet powerful way to implement real-time communication in Node.js applications. Whether you’re building chat apps, dashboards, or distributed systems, it provides instant message delivery between services with minimal setup.