Pub/Sub Messaging
PUBLISH, SUBSCRIBE, and channel patterns
Skills taught: redis.pub-sub
How Pub/Sub Works
Redis Pub/Sub decouples message producers (publishers) from consumers (subscribers) via named channels. Publishers broadcast to a channel without knowing who is listening. Subscribers receive all messages on their channel in real time.
# Terminal 1 — Subscribe to a channel
redis-cli
127.0.0.1:6379> SUBSCRIBE notifications
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "notifications"
3) (integer) 1
# Terminal 2 — Publish a message
redis-cli PUBLISH notifications "User 42 signed up"
# (integer) 1 <-- number of subscribers that received it
# Back in Terminal 1:
1) "message"
2) "notifications"
3) "User 42 signed up"
Pattern Subscriptions
PSUBSCRIBE lets you subscribe to multiple channels matching a glob pattern. This is useful when channel names are dynamic.
# Subscribe to all order channels
PSUBSCRIBE orders.*
# Matches: orders.created, orders.shipped, orders.cancelled
# Subscribe to multiple patterns
PSUBSCRIBE user:* product:*
# Unsubscribe from pattern
PUNSUBSCRIBE orders.*
# List active subscriptions
PUBSUB CHANNELS # all active channels with subscribers
PUBSUB CHANNELS user:* # matching pattern
PUBSUB NUMSUB notifications # subscriber count per channel
PUBSUB NUMPAT # total pattern subscriptions
Pub/Sub in Node.js
import Redis from 'ioredis';
// IMPORTANT: Use separate connections for pub and sub
// A subscribed connection can ONLY use subscribe commands
const subscriber = new Redis();
const publisher = new Redis();
// Subscribe to a channel
await subscriber.subscribe('chat:room1');
// Listen for messages
subscriber.on('message', (channel, message) => {
console.log(`[${channel}] ${message}`);
});
// Pattern subscribe
await subscriber.psubscribe('orders.*');
subscriber.on('pmessage', (pattern, channel, message) => {
console.log(`Pattern: ${pattern}, Channel: ${channel}, Message: ${message}`);
});
// Publish from another connection
await publisher.publish('chat:room1', JSON.stringify({ user: 'Alice', text: 'Hello!' }));
await publisher.publish('orders.created', JSON.stringify({ orderId: 42, total: 99.99 }));
// Cleanup
await subscriber.unsubscribe('chat:room1');
await subscriber.punsubscribe('orders.*');
Keyspace Notifications
Redis can publish notifications when keys expire, are set, or are deleted — using Pub/Sub internally. Enable it in redis.conf or via CONFIG SET.
# Enable expired key notifications
redis-cli CONFIG SET notify-keyspace-events "Ex"
# Subscribe to expired key events on database 0
redis-cli
SUBSCRIBE __keyevent@0__:expired
# When any key expires, you get a notification:
# 1) "message"
# 2) "__keyevent@0__:expired"
# 3) "session:abc123" <- the expired key name
# Node.js: react when a session expires
await subscriber.subscribe('__keyevent@0__:expired');
subscriber.on('message', (channel, key) => {
if (key.startsWith('session:')) {
console.log('Session expired:', key);
cleanupUserSession(key);
}
});
Pub/Sub vs Redis Streams
- Pub/Sub: Fire-and-forget broadcast
- Redis Streams: Durable append-only log
Tip: Pub/Sub messages are fire-and-forget — if no subscriber is connected at the moment of publish, the message is lost. For durability, use Redis Streams, which persist messages to an append-only log.
Warning: A Redis connection in subscribe mode can only use SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PING, RESET, and QUIT. Use a separate connection for publishing and normal commands.
Frequently Asked Questions
Can I use Pub/Sub for a chat app?
Yes for real-time delivery, but add Redis Streams or a database for message history. Pub/Sub has no message history — joining a room after a message was sent means you missed it.
How do I know how many subscribers a channel has?
PUBSUB NUMSUB channel1 channel2 returns the subscriber count for each channel. PUBSUB CHANNELS lists all channels with at least one subscriber.
What is the difference between SUBSCRIBE and PSUBSCRIBE?
SUBSCRIBE registers for exact channel names. PSUBSCRIBE registers for channels matching a glob pattern (*, ?, [abc]). Pattern subscribers receive pmessage events instead of message events.