← Back to JavaScript, page 10

javascript-0194 · Hard senior

How would you build a WebSocket client that reconnects with backoff, detects dead connections with heartbeats, and does not lose messages while offline?

Wrap the socket in a small state machine. Reconnect with exponential backoff and jitter, reset the delay after a successful open, send a ping on a timer and close the socket if no pong arrives, queue outgoing messages while disconnected and flush them on open, and send the last received id so the server can replay what was missed. Add a maximum number of attempts and a manual close that stops reconnecting.

Full answer

A raw WebSocket does not reconnect and does not tell you when the network silently disappears. A reliable client adds these parts:

  1. States: connecting, open, closed, waiting (before a retry), and stopped (closed by the user). Keep the state explicit so you can test it.
  2. Backoff: delay = min(max, base * 2^attempt), then apply jitter (a random factor, often "full jitter": a random value between 0 and the delay). Jitter prevents thousands of clients from reconnecting at the same second after a server restart. Reset the attempt count when a connection has been open for a stable time, not only at the first open event.
  3. Heartbeat: a half-open connection (a dropped Wi-Fi, a proxy that timed out) can look open for minutes. Send an application-level ping every N seconds and expect a pong within a timeout, or close and reconnect. Browsers do not expose protocol-level ping frames to JavaScript.
  4. Outgoing queue: while not open, keep messages in a bounded queue and send them in order after reconnecting. Decide what to do when the queue is full (drop the oldest, or reject). Messages should carry ids so the server can ignore duplicates.
  5. Resume: remember the id of the last message received and send it on reconnect, so the server replays the gap. Without that, the client should ask for a fresh snapshot of the state.
  6. Close codes: treat authentication failures and policy errors (for example code 1008 or 4401) as fatal, and do not retry them in a loop. Retry on network failures and normal server restarts.
  7. Visibility and network hints: pause or slow down when the tab is hidden, and try early when the browser fires the online event.
  8. Cleanup: remove timers and listeners on close so a stopped client does not retry, and guard against late events from an old socket instance.
  9. Tests: inject the socket class and the timers, as the example does.

Libraries such as Socket.IO and reconnecting-websocket already do most of this, but interviewers ask for the design.

javascript
const { mock } = require('node:test');
mock.timers.enable({ apis: ['setTimeout', 'setInterval'] });

class FakeSocket {
  static instances = [];
  constructor(url) {
    this.url = url;
    this.sent = [];
    this.readyState = 0;
    FakeSocket.instances.push(this);
  }
  send(data) { this.sent.push(data); }
  close(code = 1000) { this.readyState = 3; this.onclose?.({ code }); }
  open() { this.readyState = 1; this.onopen?.(); }
  receive(data) { this.onmessage?.({ data }); }
}

function createClient({ url, SocketClass, random, baseMs = 100, maxMs = 1000, pingMs = 500, pongMs = 200, maxAttempts = 5, log }) {
  let socket = null;
  let attempt = 0;
  let state = 'closed';
  let lastId = 0;
  let retryTimer = null;
  let pingTimer = null;
  let pongTimer = null;
  const queue = [];

  const setState = (next) => { state = next; log(`state: ${next}`); };
  const clearBeat = () => { clearInterval(pingTimer); clearTimeout(pongTimer); };

  function connect() {
    setState('connecting');
    const current = new SocketClass(`${url}?lastId=${lastId}`);
    socket = current;
    current.onopen = () => {
      if (socket !== current) return;
      attempt = 0;
      setState('open');
      while (queue.length) current.send(queue.shift());
      pingTimer = setInterval(() => {
        current.send('ping');
        pongTimer = setTimeout(() => { log('no pong, closing'); current.close(4000); }, pongMs);
      }, pingMs);
    };
    current.onmessage = ({ data }) => {
      if (socket !== current) return;
      if (data === 'pong') return clearTimeout(pongTimer);
      lastId = JSON.parse(data).id;
      log(`received id ${lastId}`);
    };
    current.onclose = ({ code }) => {
      if (socket !== current || state === 'stopped') return;
      clearBeat();
      if (code === 4401 || attempt >= maxAttempts) return setState('stopped');
      const ceiling = Math.min(maxMs, baseMs * 2 ** attempt);
      const delay = Math.round(ceiling / 2 + (random() * ceiling) / 2);
      attempt++;
      setState('waiting');
      log(`retry ${attempt} in ${delay} ms (ceiling ${ceiling})`);
      retryTimer = setTimeout(connect, delay);
    };
  }

  return {
    connect,
    send(message) {
      if (state === 'open') socket.send(message);
      else queue.push(message);
    },
    stop() {
      clearTimeout(retryTimer);
      clearBeat();
      setState('stopped');
      socket?.close(1000);
    },
    state: () => state,
  };
}

const lines = [];
const client = createClient({ url: 'wss://example.test/feed', SocketClass: FakeSocket, random: () => 0.5, log: (line) => lines.push(line) });
const last = () => FakeSocket.instances.at(-1);

client.connect();
client.send('hello while connecting');
last().open();
last().receive(JSON.stringify({ id: 7 }));
console.log('sent after open:', last().sent);

mock.timers.tick(500);
last().receive('pong');
mock.timers.tick(500);
mock.timers.tick(200);
console.log('after a missed pong:', client.state());

mock.timers.tick(10000);
console.log('reconnected with resume id:', last().url);
last().open();
client.send('queued message');
console.log('state:', client.state(), '| sent:', last().sent);

for (let i = 0; i < 6; i++) {
  last().close(1006);
  mock.timers.tick(5000);
}
console.log('gave up after the attempts:', client.state(), '| sockets created:', FakeSocket.instances.length);
console.log(lines.join('\n'));
mock.timers.reset();

Run with Node.js v24.22.1 as js-194.js; two runs gave identical output. Output: sent after open: [ 'hello while connecting' ] after a missed pong: waiting reconnected with resume id: wss://example.test/feed?lastId=7 state: open | sent: [ 'queued message' ] gave up after the attempts: stopped | sockets created: 7 state: connecting state: open received id 7 no pong, closing state: waiting retry 1 in 75 ms (ceiling 100) state: connecting state: open state: waiting retry 1 in 75 ms (ceiling 100) state: connecting state: waiting retry 2 in 150 ms (ceiling 200) state: connecting state: waiting retry 3 in 300 ms (ceiling 400) state: connecting state: waiting retry 4 in 600 ms (ceiling 800) state: connecting state: waiting retry 5 in 750 ms (ceiling 1000) state: connecting state: stopped

Key points

  • Explicit states and exponential backoff with jitter; reset after a stable connection.
  • Application-level ping and pong timeout detects half-open connections.
  • Bounded outgoing queue flushed on open; message ids allow deduplication.
  • Resume with a last received id or ask for a snapshot.
  • Do not retry fatal close codes; clean up timers and ignore events from old sockets.

Common mistakes

  • Reconnecting in a tight loop with no backoff or jitter.
  • Trusting the open state without a heartbeat.
  • Retrying authentication failures forever.
  • Handling events from an old socket after a new one was created.

Follow-ups

  • Why does jitter matter after a server restart?
  • How would you resume without duplicate messages?
  • How do you test this without a real server?

Tips

  • Draw the states and say what triggers each change.
  • Explain half-open connections as the reason for pings.
  • Mention close codes, ids, and cleanup.