Publish messages to channels, subscribe and handle messages, and use Redis Streams for reliable messaging.
Pub/Sub is fire-and-forget messaging. Publishers send to channels. Subscribers receive messages on channels they're subscribed to. No message history — if no subscriber is listening when a message arrives, it's lost.
import { createClient } from 'redis';
// Subscriber needs its own connection
const subscriber = createClient();
const publisher = createClient();
await subscriber.connect();
await publisher.connect();
// Subscribe to a channel
await subscriber.subscribe('notifications', (message) => {
console.log('Received:', JSON.parse(message));
});
// Publish from elsewhere
await publisher.publish('notifications', JSON.stringify({
type: 'user_signup',
userId: 123,
email: '[email protected]'
}));
// Pattern subscribe (wildcard)
await subscriber.pSubscribe('events:*', (message, channel) => {
console.log(`Channel ${channel}:`, message);
});# Streams have a persistent log — messages are stored
# Consumers can read from a specific position
# Consumer groups enable parallel processing
# Add to stream
XADD events * type order_placed userId 123 amount 49.99
# Read from stream
XRANGE events - + # all messages
XREAD COUNT 10 STREAMS events 0 # from beginning
# Consumer group (parallel workers)
XGROUP CREATE events processors $ MKSTREAM
XREADGROUP GROUP processors worker1 COUNT 1 STREAMS events >
XACK events processors # acknowledge processed