Skip to content

Real-Time Messaging Architecture: WebSockets, Pub/Sub Fanout, Presence, and Reconnects

2 min read

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:

  1. Webhook worker persists the message to the database first (durable commit).
  2. Worker publishes a compact event envelope to channel tenant:{tenantId}:inbox.
  3. Every gateway instance subscribed to that tenant fans out the frame to authorized sockets.
PatternBest ForKey Failure Mode to Handle
Optimistic UI SendInstant feel when teammate hits EnterReconcile client temp ID with server ID; surface retry on error
Cursor Catch-Up on ReconnectRecovering missed messages after laptop sleepFetch messages WHERE created_at > lastSeenCursor upon onopen
Heartbeat Ping/PongDetecting half-open dead TCP connectionsExponential backoff reconnect with jitter to avoid thundering herds

Reconnect-Safe Client Catch-Up Pattern

ts
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.

Was this helpful?