Pub/Sub Messaging

Difficulty: Beginner

Question

What is Redis Pub/Sub, how does it work, and when should you not use it?

Answer

Redis Pub/Sub is a fire-and-forget messaging system: publishers send a message to a channel with PUBLISH, and Redis immediately pushes it to every client currently subscribed to that channel. Nothing is stored, so a subscriber that is offline or disconnected simply misses the message. It is ideal for real-time notifications such as live score updates, chat typing indicators, or telling every app server to clear a local cache.

How it works

  • Subscribers call SUBSCRIBE channel [channel ...] or PSUBSCRIBE pattern (for example PSUBSCRIBE order:*).
  • Publishers call PUBLISH channel message. The reply is the number of clients that received it, which is 0 if nobody was listening.
  • Redis loops over the subscribers and writes the message into each one's output buffer. Delivery is at-most-once: no acknowledgements, no retries, no history.
  • With the RESP2 protocol, a subscribed connection can only run SUBSCRIBE, UNSUBSCRIBE, their pattern and shard variants, PING, RESET and QUIT, so clients use a dedicated connection for subscriptions. RESP3 lifts this restriction.

Pub/Sub in Redis Cluster

Classic PUBLISH in a cluster is broadcast to every node over the cluster bus, which does not scale with node count. Redis 7.0 added sharded Pub/Sub (SPUBLISH, SSUBSCRIBE): the channel name is hashed to a slot like a key, and messages stay within that shard and its replicas.

Pub/Sub vs Streams vs Lists

NeedPub/SubStreamsList with BLPOP
Message storedNoYesYes, until popped
Late subscriber gets old messagesNoYes, from any IDOnly unpopped items
Fan-out to many consumersYesYes (multiple groups)No, each item goes to one consumer
Acknowledgement and retryNoYes (XACK, pending list)Manual

When not to use it

  • Order events, payment callbacks or anything that must not be lost: use Streams or a broker like Kafka or RabbitMQ.
  • Slow subscribers: messages pile up in that client's output buffer. The default client-output-buffer-limit pubsub 32mb 8mb 60 disconnects a subscriber that exceeds 32 MB, or stays above 8 MB for 60 seconds.
  • Expecting persistence: Pub/Sub messages are not written to RDB or AOF.

Real-world uses

  • Socket.IO's Redis adapter uses Pub/Sub so a message emitted on one Node.js server reaches users connected to other servers.
  • Broadcasting "invalidate local cache key X" to every app instance.
  • Keyspace notifications (notify-keyspace-events) are delivered over Pub/Sub, so you can subscribe to events like key expiry, with the same no-guarantee caveat.
A message through Redis Pub/Sub. Redis pushes the message only to clients subscribed at that moment, then forgets it.
  1. Publisher: PUBLISH scores:ipl: Any client can publish to any channel.
  2. Redis looks up subscribers: Exact channel and matching patterns.
  3. Copy into each output buffer: Slow clients accumulate a backlog here.
  4. Subscribers receive message: Offline clients never see it.

Code examples

Publisher and subscriber in Node.js (node-redis v4+)

import { createClient } from 'redis';

// Subscriber needs its own connection
const sub = createClient();
await sub.connect();
await sub.subscribe('scores:ipl', (message) => {
  const update = JSON.parse(message);
  console.log('Live update:', update.over, update.score);
});

// Publisher uses a normal connection
const pub = createClient();
await pub.connect();
const receivers = await pub.publish(
  'scores:ipl',
  JSON.stringify({ over: '18.4', score: '172/5' })
);
console.log('Delivered to', receivers, 'subscriber(s)');

PUBLISH returns the receiver count, which is a quick way to see that nobody was listening. The subscriber runs on a separate connection because a subscribed RESP2 connection cannot issue normal commands.

Key points

  • Pub/Sub is fire-and-forget with at-most-once delivery and no storage.
  • PUBLISH returns how many subscribers received the message.
  • PSUBSCRIBE supports glob patterns like news:*.
  • Redis 7.0 sharded Pub/Sub (SPUBLISH/SSUBSCRIBE) scales in Cluster.
  • Slow subscribers are disconnected by the pubsub output buffer limit.

Common follow-up questions

  • How would you guarantee delivery if a subscriber is temporarily down?
  • Why does classic Pub/Sub not scale well in Redis Cluster?
  • How would you scale WebSocket servers horizontally using Redis?
  • What are keyspace notifications?

Interview tips

  • Lead with 'fire-and-forget, no persistence' and immediately name Streams as the durable alternative.
  • Mention the output buffer limit for slow subscribers; it is a real production failure mode.
  • Give one concrete use case like fanning out chat messages across multiple WebSocket servers.

Concepts covered

PUBLISH, SUBSCRIBE, PSUBSCRIBE, Sharded Pub/Sub, At-most-once Delivery

More Redis & Caching questions