2.5 Hours

11. Pub/Sub: Real-time Messaging Channels

Messaging

Real-time Message Distribution

Redis provides a Publish/Subscribe (Pub/Sub) engine, allowing applications to implement event-driven architectures. In this pattern, clients do not poll for messages; instead, they subscribe to channels. When another client publishes a message to a channel, Redis routes the payload to all subscribed clients. This decouples message senders (publishers) from receivers (subscribers), making it ideal for building real-time applications like chat rooms, collaboration tools, and live notification services.

The key characteristic of Redis Pub/Sub is its Fire-and-Forget nature. Channels are ephemeral and do not store messages. If a client is disconnected when a message is published, that message is lost forever. There is no historical playback or retry mechanism. This lack of storage overhead makes the Pub/Sub system fast: Redis routes messages directly in memory to subscriber socket buffers, maintaining low latencies under high throughput.

For scenarios requiring guaranteed delivery or consumer group scaling, Redis Pub/Sub is not a good fit. In those cases, developers should use Redis Streams or dedicated brokers like RabbitMQ. However, for ephemeral real-time notifications, Pub/Sub is highly efficient.

Client Output Buffers and Disconnection Risks

In high-throughput Pub/Sub systems, a common bottleneck is the Slow Consumer. If a publisher broadcasts messages at 10,000 requests per second, but a subscriber's network connection can only handle 1,000, where do the remaining messages go? Redis cannot block the publisher (as doing so would stall the event loop for all clients). Instead, it buffers unread messages in memory inside the client's output buffer allocation.

If the slow consumer continues to fall behind, its output buffer will grow, consuming server RAM. To prevent this buffer bloat from causing OOM crashes, Redis uses strict limits (configured via client-output-buffer-limit pubsub). The moment a client's buffer exceeds these size limits (or stays above a soft limit for too long), Redis terminates the client connection. This protects server stability, but means subscriber clients must process messages asynchronously to avoid disconnection.

To implement Pub/Sub reliably in Node.js, applications must manage connections carefully. When a Redis client runs the SUBSCRIBE command, it enters subscriber mode and can only run connection-management commands (like UNSUBSCRIBE or PING). To publish messages or query data, the application must use a separate Redis connection. Managing multiple connections is a key requirement when building Pub/Sub architectures.

JavaScript
// Complete Pub/Sub Notification Listener and Publisher setup
const Redis = require('ioredis');

// Subscriber connection: exclusively handles incoming channel events
const subscriber = new Redis({ host: '127.0.0.1', port: 6379 });
// Publisher connection: runs normal database queries and publishes
const publisher = new Redis({ host: '127.0.0.1', port: 6379 });

async function setupMessaging() {
  await subscriber.subscribe('alerts');
  
  subscriber.on('message', (channel, message) => {
    console.log(`Received message from ${channel}: ${message}`);
    // Process message asynchronously to avoid blocking the client connection
  });
}

async function emitAlert(payload) {
  // Publish message to 'alerts' channel
  const receiverCount = await publisher.publish('alerts', JSON.stringify(payload));
  console.log(`Alert broadcasted to ${receiverCount} active subscribers.`);
}

Knowledge Check

Ready to test your understanding of 11. Pub/Sub: Real-time Messaging Channels?

Back