Video in progress

How do you write reconnect logic on the client when a WebSocket drops?

Retry with a delay that grows on every drop (exponential backoff), add random jitter on top, and cap it at a maximum. After a successful connection the counter resets, and subscriptions and, if needed, the lost state are reloaded.

📖 Answer

let attempt = 0;

function connect() {
  const ws = new WebSocket(URL);

  ws.onopen = () => {
    attempt = 0;
    resubscribe(ws);
    reloadMissedState(); // fetch changes from the time of the drop via REST
  };

  ws.onclose = (e) => {
    if (e.code === 1008) return showLogin(); // not allowed: retrying is pointless
    const base = Math.min(30_000, 1000 * 2 ** attempt);
    const delay = base / 2 + Math.random() * base / 2; // jitter
    attempt++;
    setTimeout(connect, delay);
  };
}

What I pay attention to:

  • Jitter is a must. When a server restarts, 50,000 clients drop within one second. Without jitter they all come back together at exactly 1s, 2s, 4s, and knock the server over again.
  • Don't retry on every error. If the token has expired or access is denied, endless retries only add load.
  • Restore the state. Reconnecting means a new session. The server doesn't remember the old subscriptions, and messages sent during the drop may be lost.
  • When the tab isn't visible (document.hidden), you can lengthen the gap between attempts.

@stomp/stompjs has reconnectDelay, but it's a fixed interval on its own, with no jitter. For a large audience I turn it off and handle it myself.