Video in progress

A user opens the app in 10 tabs, and each tab opens its own WebSocket connection. How do you move to one connection per browser, and is it worth it?

A single "leader" tab or a SharedWorker holds the connection, and the other tabs receive messages through a BroadcastChannel or the worker port. This cuts server connections several times over, but leader switching, tab closing and browser support add complexity.

📖 Answer

First I measure: how many connections per user on average? In business apps (CRM, admin panels) 4 to 6 tabs is normal. 50,000 users means 250,000 connections, most of them sitting idle in background tabs. Then this optimization is worth it. For a typical site, probably not.

Two main ways:

SharedWorker. One worker shared by all tabs opens the WebSocket:

// worker.js
const ports = new Set();
const ws = new WebSocket('wss://app.uz/ws');
ws.onmessage = e => ports.forEach(p => p.postMessage(e.data));
onconnect = e => {
  const port = e.ports[0];
  ports.add(port);
  port.onmessage = m => ws.send(m.data);
};

But SharedWorker isn't available everywhere in mobile browsers, and the worker can't reliably tell that a tab closed (you need your own heartbeat for the ports).

Leader tab. The tabs elect a leader with the Web Locks API (navigator.locks.request). The tab that gets the lock connects and distributes messages through a BroadcastChannel. If the leader tab closes, the lock is released and another tab becomes the leader and reconnects.

Whichever way you choose, you'll have to deal with:

  • subscriptions: each tab states its needs, the connection owner manages the shared set and removes a subscription when a tab closes;
  • the browser "puts to sleep" background tabs: if the leader is a background tab, its timers slow down and heartbeats may be late;
  • authentication: if logout happens in one tab, the shared connection must be closed too.

On the server side I also add insurance: a connection limit per user (say 5), and when it's exceeded the oldest is closed. This also protects you when the client logic breaks.