# Fan-out Across Servers with Pub/Sub — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-pubsub-fanout

> Use Redis pub/sub so a message received on one server reaches room members connected to other servers.

## Why rooms break with two servers

With two app servers, Asha may be connected to server A and Ravi to server B. When Asha posts, server A's in-memory room only knows its own sockets, so Ravi never sees it. The common fix is a **message broker** that every server subscribes to. When server A receives a chat message, it **publishes** it to a channel like `room:cse-2nd-year`. Every server, A included, is subscribed, receives the message and sends it to the sockets it holds locally for that room. **Redis pub/sub** is the usual first choice: simple and fast, but fire-and-forget, so a server that is disconnected from Redis misses messages. If you need durability or replay, use **Redis Streams**, **NATS JetStream** or **Kafka**, and persist chat history in a database anyway. Socket.IO packages this pattern as an *adapter*. Keep published payloads small and already serialised, because every server receives every message for every subscribed channel.

## Redis fan-out with ws and node-redis

One Redis connection publishes and a duplicate subscribes, because node-redis puts a subscribing connection into a dedicated mode. Each server forwards broker messages only to its local sockets in that room.

```js
import { createClient } from 'redis';
import { WebSocketServer, WebSocket } from 'ws';

const pub = createClient({ url: process.env.REDIS_URL });
const sub = pub.duplicate(); // subscriptions need their own connection
await Promise.all([pub.connect(), sub.connect()]);

const wss = new WebSocketServer({ port: Number(process.env.PORT ?? 3000) });
const local = new Map(); // room -> Set of sockets on THIS node

await sub.pSubscribe('room:*', (message, channel) => {
  const room = channel.slice('room:'.length);
  for (const ws of local.get(room) ?? []) {
    if (ws.readyState === WebSocket.OPEN) ws.send(message);
  }
});

wss.on('connection', (ws, req) => {
  const room = new URL(req.url, 'http://x').searchParams.get('room') ?? 'lobby';
  if (!local.has(room)) local.set(room, new Set());
  local.get(room).add(ws);

  ws.on('message', (text) => pub.publish(`room:${room}`, text.toString()));
  ws.on('close', () => local.get(room)?.delete(ws));
});
```

## Pub/sub is not storage

Redis pub/sub delivers only to subscribers connected at that moment. Save messages to a database first, publish second, and let reconnecting clients fetch missed messages from the database or a stream, not from pub/sub.

## The college notice board relay

Each hostel has its own notice board (server). A notice posted at one hostel is phoned to the central office (broker), which phones every hostel warden, and each warden pins it on their own board for their residents.

**Quiz:** Why is Redis pub/sub alone not enough to guarantee clients receive every chat message?

- [x] It is fire-and-forget: subscribers that are disconnected at publish time miss the message
- [ ] It only supports one channel per server
- [ ] It cannot carry JSON
- [ ] It requires sticky sessions

*Answer:* It is fire-and-forget: subscribers that are disconnected at publish time miss the message. Pub/sub has no persistence or replay. Durable storage or a log-based system such as Redis Streams or Kafka is needed for guaranteed delivery.
