Setting Up Redis for Pub/Sub Notifications
Redis Pub/Sub is a message delivery mechanism in "fire and forget" mode. The broker does not store history: if subscriber is not listening at publication time, message is lost. This distinguishes it from Redis Streams and makes it suitable for short real-time notifications — event alerts, cache invalidation, state synchronization between multiple service instances.
When to Use Pub/Sub vs Queue
Pub/Sub solves broadcast task: one publisher, multiple subscribers, all receive same message simultaneously. If guaranteed delivery, message history, or consumer groups are needed — Redis Streams or RabbitMQ.
Typical website case: user performs action → backend publishes event to channel → WebSocket server receives event and broadcasts push to all connected clients in corresponding "room". Without Pub/Sub, horizontal scaling of WebSocket servers is impossible: each instance only knows its own connections.
Basic Setup
Redis supports Pub/Sub out of the box without configuration. But it's worth setting few parameters in redis.conf:
# Memory limit — critical if Redis is used as cache too
maxmemory 512mb
maxmemory-policy allkeys-lru
# Number of databases — one logical DB sufficient for prod
databases 16
# Disable persistence for pure pub/sub broker
save ""
appendonly no
For production Redis should be in Sentinel or Cluster mode. Pub/Sub in Cluster has limitation: messages propagate only within shard unless using SPUBLISH/SSUBSCRIBE (Sharded Pub/Sub, Redis 7+).
Implementation on Node.js with ioredis
import Redis from 'ioredis';
const publisher = new Redis({ host: 'redis', port: 6379 });
const subscriber = new Redis({ host: 'redis', port: 6379 });
// Subscriber — separate connection, blocked on listen
subscriber.subscribe('notifications:user:*', (err, count) => {
if (err) throw err;
console.log(`Subscribed to ${count} channels`);
});
subscriber.on('pmessage', (pattern, channel, message) => {
// channel = "notifications:user:42"
const userId = channel.split(':')[2];
const payload = JSON.parse(message);
broadcastToUser(userId, payload);
});
// Publishing from anywhere else
async function notifyUser(userId: string, event: object) {
const channel = `notifications:user:${userId}`;
const count = await publisher.publish(channel, JSON.stringify(event));
// count — number of subscribers who received message
return count;
}
Important: publisher and subscriber are separate connections. After calling subscribe/psubscribe connection enters special mode and accepts only SUBSCRIBE, UNSUBSCRIBE, PING, RESET, QUIT commands.
Pattern-Matching Subscriptions
PSUBSCRIBE supports glob patterns: * (any characters), ? (one character), [chars] (character set). Useful for subscribing to whole class of channels:
// All events of specific tenant
subscriber.psubscribe('tenant:acme:*');
// Specific event type for all users
subscriber.psubscribe('*:message:new');
WebSocket Integration (Socket.io)
Classic Socket.io scaling through Redis Adapter:
import { createServer } from 'http';
import { Server } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
const httpServer = createServer();
const io = new Server(httpServer);
const pubClient = createClient({ url: 'redis://redis:6379' });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
io.adapter(createAdapter(pubClient, subClient));
// Now io.to('room').emit() works across all server instances
httpServer.listen(3000);
Redis Adapter uses Pub/Sub internally: when calling io.to('room').emit() on one instance, command is published to Redis channel, and all other instances receive it and broadcast to their connected clients in that room.
Laravel Integration
Laravel Echo Server or Soketi — standard path. But direct via predis or phpredis:
// Publishing event from Laravel
use Illuminate\Support\Facades\Redis;
Redis::publish('notifications:user:' . $userId, json_encode([
'type' => 'order.status_changed',
'orderId' => $order->id,
'status' => $order->status,
'timestamp' => now()->toISOString(),
]));
For Laravel Broadcasting with Redis:
// config/broadcasting.php
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => '{default}',
'retry_after' => 90,
],
],
# Starting Laravel Echo Server
npx laravel-echo-server start
# or Soketi (more modern alternative)
soketi start --config=soketi.json
Monitoring
# View active Pub/Sub channels
redis-cli PUBSUB CHANNELS "*"
# Number of subscribers on channel
redis-cli PUBSUB NUMSUB notifications:user:42
# Pattern subscriptions
redis-cli PUBSUB NUMPAT
# Monitor all commands in real time (caution on prod)
redis-cli MONITOR
In Redis Exporter for Prometheus, Pub/Sub metrics available through redis_connected_slaves and custom scripts. Important metric — instantaneous_ops_per_sec: if it spikes with Pub/Sub load, check message size and publication frequency.
Limitations and Pitfalls
Message loss on reconnect. If subscriber disconnects and reconnects, missed messages not recovered. For critical notifications — Redis Streams with consumer groups or storing recent events in separate key.
No delivery acknowledgment. PUBLISH returns number of recipients, but does not guarantee they processed message. For at-least-once delivery need queue.
CPU load with many patterns. PSUBSCRIBE matches each published message against all registered patterns. With 10,000+ patterns becomes noticeable.
Timeline
Basic Redis Pub/Sub integration with Socket.io or Soketi on existing project — 1–2 days. Full notification system with channel personalization, reconnect handling, and monitoring — 4–6 days.







