Back to results for “Caching”
Node.js › Caching with Redis

What is Redis Pub/Sub, and how would a Node.js application use it to broadcast real-time events across multiple server instances?

Intermediate

Answer

Redis Pub/Sub lets clients subscribe to named channels and receive messages published to those channels in real time -- useful for broadcasting an event (like a chat message or a live notification) to every connected server instance simultaneously, which matters for something like a WebSocket-based chat application running multiple instances behind a load balancer, since a message published by one instance needs to reach clients connected to every other instance too.
const subscriber = client.duplicate();
await subscriber.connect();
await subscriber.subscribe('chat-room-1', (message) => {
  broadcastToLocalWebSocketClients(JSON.parse(message));
});

// Any instance can publish, and all subscribed instances receive it
await client.publish('chat-room-1', JSON.stringify({ user: 'Alice', text: 'Hello!' }));
Real-world example A chat application running four load-balanced Node.js instances uses Redis Pub/Sub so that when a message is sent by a user connected to instance 2, it's published to Redis and received by all four instances, letting each broadcast it to its own locally-connected WebSocket clients regardless of which instance they're connected to.

Common follow-ups: Why does Redis Pub/Sub not persist messages for subscribers that are offline when a message is published, unlike a proper message queue?;How does Redis Streams differ from Pub/Sub for use cases needing message durability and replay?