Pub/Sub and StreamsLesson 4.1
Redis Pub/Sub: how PUBLISH and SUBSCRIBE work
PUBLISH command, SUBSCRIBE command, channel model, fire-and-forget semantics, no message persistence, multiple subscribers, PSUBSCRIBE pattern matching
Publish/Subscribe messaging in Redis
Redis Pub/Sub is a fire-and-forget messaging system. Publishers send messages to a channel. All current subscribers receive a copy. If no subscribers are connected, the message is lost.
Basic example
# Terminal 1 — subscriber
redis-cli
> SUBSCRIBE notifications
# Waiting for messages...
# Terminal 2 — publisher
redis-cli PUBLISH notifications "User 42 logged in"
# → (integer) 1 (number of subscribers who received it)In Node.js
const sub = redis.createClient();
const pub = redis.createClient();
await sub.subscribe('notifications', (message) => {
console.log('Received:', message);
});
await pub.publish('notifications', 'Hello subscribers');Pattern subscriptions
# Subscribe to all channels matching a glob
PSUBSCRIBE news.* # matches news.sports, news.tech, etc.Limitations to know
Pub/Sub has no message persistence. A subscriber that disconnects misses all messages sent while offline. There is no acknowledgement — you cannot confirm a message was processed. For reliable messaging with replay and consumer groups, use Redis Streams (next lesson). Use Pub/Sub for ephemeral real-time events: live notifications, chat, presence indicators.
