3.5 Hours

6. Pub/Sub: Real-Time Messaging

Messaging

Real-Time Messaging with Redis Pub/Sub

Redis Pub/Sub is a messaging system for real-time communication. Publishers send messages to channels. Subscribers receive messages from channels. Pub/Sub is ideal for notifications, real-time updates, and event-driven architectures. It's fast, simple, and supports pattern subscriptions.

Pub/Sub is fire-and-forget — publishers don't wait for subscribers. Messages are delivered instantly to all connected subscribers. There's no message persistence — if a subscriber is offline, messages are lost. Pub/Sub is best for real-time notifications and event broadcasting, not critical messaging. Use Streams for durable messaging. Pub/Sub is ideal for chat applications, live dashboards, and real-time analytics.

Understanding Pub/Sub is essential for building reactive applications. It enables loose coupling between components and real-time communication. This module covers Pub/Sub architecture, use cases, limitations, and best practices with practical examples.

Publishing and Subscribing

Publishing sends messages to channels. Subscribing receives messages from channels. You can subscribe to multiple channels using patterns. Pub/Sub is fire-and-forget — publishers don't wait for subscribers. Messages are distributed instantly. Use Pub/Sub for real-time notifications and event broadcasting.

Pub/Sub supports two types of subscriptions: direct (SUBSCRIBE) and pattern (PSUBSCRIBE). Direct subscriptions receive messages from specific channels. Pattern subscriptions receive messages from any channel that matches a glob-style pattern. For example, PSUBSCRIBE user:* subscribes to all user-related channels. Pub/Sub is ideal for broadcasting updates to multiple subscribers.

JavaScript
// Publisher (Node.js)
import { createClient } from 'redis';

const client = createClient();
await client.connect();

// Publish a message
await client.publish('notifications', JSON.stringify({
  type: 'user_login',
  userId: '123',
  timestamp: new Date().toISOString()
}));

// Subscriber (Node.js)
const subscriber = createClient();
await subscriber.connect();

// Subscribe to a channel
await subscriber.subscribe('notifications', (message) => {
  const data = JSON.parse(message);
  console.log('Received:', data);
});

// Subscribe with pattern
await subscriber.pSubscribe('user:*', (message, channel) => {
  console.log(`Channel ${channel}:`, message);
});

// Unsubscribe
await subscriber.unsubscribe('notifications');
await subscriber.pUnsubscribe('user:*');

Pub/Sub Use Cases

Pub/Sub has many use cases in modern applications. Real-time notifications alert users of events like messages, comments, or system updates. Live dashboards update in real time with metrics and analytics. Event-driven architecture decouples services with events. Chat applications broadcast messages to chat rooms. Analytics pipeline processes events in real time.

Pub/Sub is particularly effective for applications that need to push updates to multiple clients simultaneously. For example, a sports score app pushes score updates to all connected clients. A stock trading app pushes price updates to all subscribers. A collaborative editing app pushes changes to all editors. Pub/Sub makes these patterns simple and efficient.

  • Real-Time Notifications: Alert users of events in real time (messages, comments, system alerts).
  • Live Dashboards: Update dashboards with real-time metrics and analytics.
  • Event-Driven Architecture: Decouple services with events and event handlers.
  • Chat Applications: Broadcast messages to chat rooms and channels.
  • Analytics Pipeline: Process events in real time for analytics and monitoring.
  • Game Updates: Broadcast game state changes to players.

Limitations and Best Practices

Pub/Sub has important limitations to understand. Messages are not persisted — offline subscribers miss messages. There's no message acknowledgment or guarantee of delivery. Pub/Sub is best for real-time notifications, not critical messaging. Use Streams for durable messaging with persistence and acknowledgment.

Best practices for Pub/Sub include using pattern subscriptions for flexibility, monitoring Pub/Sub performance (throughput and latency), and designing for message loss. For critical messages, use Streams instead of Pub/Sub. For ephemeral messages, Pub/Sub is ideal. Monitor channel activity and subscriber counts to ensure health.

  • No Message Persistence: Offline subscribers miss messages — design for this limitation.
  • No Acknowledgment: No guarantee of message delivery — messages are fire-and-forget.
  • Pattern Subscriptions: Subscribe to multiple channels with patterns for flexibility.
  • Monitor Performance: Track Pub/Sub throughput and latency.
  • Use Streams for Critical Messaging: For messages that must not be lost, use Streams.

Knowledge Check

Ready to test your understanding of 6. Pub/Sub: Real-Time Messaging?

Back