Redis Pub/Sub notifications setup

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

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.