पाठ 19 / 32

Reconnecting with Backoff and Resume

यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।

Write a client that reconnects with exponential backoff and jitter and resumes from the last sequence number.

लेखक: · 15 साल से वेब डेवलपर

Why naive reconnects hurt

WebSocket clients do not reconnect on their own, so you write that logic. The naive version, "reconnect immediately on close", causes two problems. If the server is down, every client hammers it in a tight loop. And when a server restarts, all its clients disconnect at the same instant and reconnect at the same instant, a thundering herd that can knock the new process over. The standard fix is exponential backoff with jitter: the maximum wait doubles after each failed attempt up to a cap (0.5 s, 1 s, 2 s, ... 30 s), and the actual wait is a random value below that maximum, which spreads clients out. Reset the attempt counter once a connection succeeds. Reconnecting is only half the job: the client must also resume, telling the server the last sequence number it processed so the server can replay what was missed, or fetching a fresh snapshot over HTTP if the gap is too large.

Backoff ceilings

The ceiling doubles from 500 ms and is capped at 30 s; the real delay is a random value below it ("full jitter").

function backoffCeiling(attempt, base = 500, cap = 30_000) {
  return Math.min(cap, base * 2 ** attempt);
}

function nextDelay(attempt) {
  return Math.random() * backoffCeiling(attempt); // "full jitter"
}

console.log([0, 1, 2, 3, 4, 5, 6, 7].map((a) => backoffCeiling(a)).join(' '));
const d = nextDelay(3);
console.log(d >= 0 && d < 4000);

Output:

500 1000 2000 4000 8000 16000 30000 30000
true

A reconnecting browser client

On every open it sends a resume message with the last sequence number it saw. On an unexpected close it schedules the next attempt with jittered backoff.

function connect(url, onMessage, attempt = 0) {
  const ws = new WebSocket(url);

  ws.addEventListener('open', () => {
    attempt = 0; // healthy again: reset the backoff
    ws.send(JSON.stringify({ type: 'resume', lastSeq: localStorage.lastSeq ?? 0 }));
  });

  ws.addEventListener('message', (event) => {
    const msg = JSON.parse(event.data);
    if (msg.seq) localStorage.lastSeq = msg.seq;
    onMessage(msg);
  });

  ws.addEventListener('close', (event) => {
    if (event.code === 1000) return; // we closed it on purpose
    const ceiling = Math.min(30_000, 500 * 2 ** attempt);
    const delay = Math.random() * ceiling; // full jitter
    setTimeout(() => connect(url, onMessage, attempt + 1), delay);
  });

  return ws;
}

Listen to the browser's network hints

Reconnect at once when the online event fires or the page becomes visible again (visibilitychange), and consider pausing attempts while navigator.onLine is false. Backoff is for an unhealthy server, not for a user who just walked out of a lift.

त्वरित जाँच: What is the main purpose of adding random jitter to reconnect delays?

  • To make messages arrive in random order
  • To spread reconnects out so clients do not all hit a restarted server at once
  • To encrypt the reconnect request
  • To make the first retry slower than the last
Answer

To spread reconnects out so clients do not all hit a restarted server at once — Without jitter, clients that disconnected together retry together. Randomising each delay smooths the load into a gentle ramp.