Real-Time Messaging Architecture: WebSockets, Pub/Sub Fanout, Presence, and Reconnects
A team inbox feels responsive when new customer messages, assignment changes, and delivery ticks appear instantly without refreshing the page. Yet mobile networks sleep, laptops close lids, and servers redeploy. Treat WebSockets as a best-effort notification accelerator paired with a durable database source of truth, never as your only message transport.
Scaling WebSockets Horizontally With Pub/Sub
A single WebSocket gateway server holds connections in local memory. When you scale to multiple gateway instances behind a load balancer, User A may connect to Node 1 while a webhook worker publishes an event on Node 2. A lightweight Pub/Sub broker (such as Redis or Valkey) bridges all gateway nodes:
- Webhook worker persists the message to the database first (durable commit).
- Worker publishes a compact event envelope to channel
tenant:{tenantId}:inbox. - Every gateway instance subscribed to that tenant fans out the frame to authorized sockets.
| Pattern | Best For | Key Failure Mode to Handle |
|---|---|---|
| Optimistic UI Send | Instant feel when teammate hits Enter | Reconcile client temp ID with server ID; surface retry on error |
| Cursor Catch-Up on Reconnect | Recovering missed messages after laptop sleep | Fetch messages WHERE created_at > lastSeenCursor upon onopen |
| Heartbeat Ping/Pong | Detecting half-open dead TCP connections | Exponential backoff reconnect with jitter to avoid thundering herds |
Reconnect-Safe Client Catch-Up Pattern
export class RealtimeInboxClient {
private lastEventSeq = 0;
handleSocketEvent(event: { seq: number; message: InboxMessage }): void {
if (event.seq <= this.lastEventSeq) return; // Deduplicate replay
this.lastEventSeq = event.seq;
this.upsertMessageInStore(event.message);
}
async handleReconnect(): Promise<void> {
const missed = await fetchMissedEventsSince(this.lastEventSeq);
for (const event of missed) {
this.handleSocketEvent(event);
}
}
private upsertMessageInStore(_msg: InboxMessage): void {}
}
Channel Authorization
Never allow a WebSocket client to subscribe to arbitrary room strings without server-side authorization. Issue short-lived signed channel tokens bound to (userId, tenantId) and revalidate on reconnect.
Next: choose the right database engine for transactional config vs append-heavy message streams in Polyglot Persistence.