Difficulty: Beginner
What is Redis Pub/Sub, how does it work, and when should you not use it?
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.
SUBSCRIBE channel [channel ...] or PSUBSCRIBE pattern (for example PSUBSCRIBE order:*).PUBLISH channel message. The reply is the number of clients that received it, which is 0 if nobody was listening.SUBSCRIBE, UNSUBSCRIBE, their pattern and shard variants, PING, RESET and QUIT, so clients use a dedicated connection for subscriptions. RESP3 lifts this restriction.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.
| Need | Pub/Sub | Streams | List with BLPOP |
|---|---|---|---|
| Message stored | No | Yes | Yes, until popped |
| Late subscriber gets old messages | No | Yes, from any ID | Only unpopped items |
| Fan-out to many consumers | Yes | Yes (multiple groups) | No, each item goes to one consumer |
| Acknowledgement and retry | No | Yes (XACK, pending list) | Manual |
client-output-buffer-limit pubsub 32mb 8mb 60 disconnects a subscriber that exceeds 32 MB, or stays above 8 MB for 60 seconds.notify-keyspace-events) are delivered over Pub/Sub, so you can subscribe to events like key expiry, with the same no-guarantee caveat.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.
PUBLISH, SUBSCRIBE, PSUBSCRIBE, Sharded Pub/Sub, At-most-once Delivery