Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Connections and Events

Reconnection, Heartbeats and State Recovery

Learn how Socket.IO reconnects with exponential backoff and jitter, how heartbeats detect dead connections, how to tune options, and how connection state recovery replays missed events.

Networks are unreliable. Phones walk into elevators, laptops sleep, load balancers restart, and Wi-Fi flickers. A real-time app that dies at the first hiccup is a bad app. Socket.IO handles most of this for you, but only if you understand what it does and what it does not do. This lesson covers automatic reconnection, heartbeats, and the newer connection state recovery feature.

Automatic reconnection

When the connection drops for any reason other than io server disconnect or an explicit socket.disconnect(), the client's Manager starts retrying. It waits, tries again, waits longer, and so on, until it connects or runs out of attempts. The wait uses exponential backoff with jitter:

  • Each attempt doubles the delay: 1 s, 2 s, 4 s, then capped by reconnectionDelayMax (5 s by default).
  • A random jitter (randomizationFactor, 0.5 by default) moves each delay up or down by up to 50 percent.

Backoff avoids hammering a server that is struggling. Jitter avoids the thundering herd: if a server restart drops 10,000 clients at the same instant and they all retried at exactly the same moments, each retry wave would knock the server over again. Spreading retries randomly smooths the load.

The client options (read-only snippet):

JavaScript
const socket = io(url, {
  reconnection: true,            // default true
  reconnectionAttempts: Infinity,// default Infinity
  reconnectionDelay: 1000,       // first delay
  reconnectionDelayMax: 5000,    // cap
  randomizationFactor: 0.5,      // jitter
  timeout: 20000,                // per-attempt connection timeout
});

socket.io.on('reconnect_attempt', (n) => console.log('attempt', n));
socket.io.on('reconnect', (n) => console.log('back after', n, 'attempts'));
socket.io.on('reconnect_failed', () => console.log('giving up'));

The following program reimplements the delay formula (our own version of the idea) with a seeded random generator, so the output is the same on every run.

Node.js Exponential backoff with jitter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

All three clients start with the same settings, yet their delays differ, so they spread out instead of arriving in one wave.

Heartbeats: ping and pong

A dropped TCP connection is not always noticed. If a laptop loses Wi-Fi, neither side gets a close message. Heartbeats solve that: every pingInterval the server sends a ping; the client must answer with a pong within pingTimeout. If not, the server declares the connection dead and emits disconnect with ping timeout. The client has the mirror-image rule: if it does not hear a ping for pingInterval + pingTimeout, it also considers the connection lost and begins reconnecting.

With the defaults (25 s and 20 s) a silent loss is detected within about 45 s. The simulation below computes the worst-case detection time for several settings.

Node.js How fast is a dead connection noticed?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Shorter values find dead clients faster, but cost more traffic and risk false alarms on slow or throttled networks (mobile browsers in background tabs often delay timers). Raising pingTimeout is the usual fix for "my users disconnect randomly on bad connections".

What reconnection does not restore

A reconnected socket is a new socket. It has a new socket.id, it is no longer in any rooms, and any events emitted while it was gone are lost. Two things make life easier:

  1. The client buffers outgoing events. Calls to socket.emit while disconnected are queued and sent after reconnection. You can opt out with socket.volatile.emit (dropped when offline).
  2. You can re-establish state in connect. Because connect fires after every reconnection, it is the right place to re-join rooms and ask for fresh data (read-only):
JavaScript
socket.on('connect', () => {
  socket.emit('room:join', currentRoom);   // rooms are not remembered
  socket.emit('sync:request', lastSeenId); // ask for what we missed
});

Connection state recovery

Since version 4.6 the server can restore a briefly disconnected client's state automatically: its id, its rooms, its custom socket.data, and the events it missed. You switch it on in the server options:

JavaScript
const io = new Server(httpServer, {
  connectionStateRecovery: {
    maxDisconnectionDuration: 2 * 60 * 1000, // keep state for 2 minutes
    skipMiddlewares: true,                   // do not re-run auth on recovery
  },
});

io.on('connection', (socket) => {
  if (socket.recovered) {
    // id, rooms, data restored; missed events were already sent
  } else {
    // new or expired session: set up from scratch
  }
});

Conceptually the server remembers recent packets for each room with an offset id. When a client reconnects it presents the id of the last event it processed, and the server replays everything after it. The example models this idea with a plain buffer (an illustration of the mechanism, not the library's implementation).

Node.js Replaying missed events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Recovery has limits. It works only for short outages, needs state kept on the server (the default adapter keeps it in memory, so a server restart loses it), and it is not guaranteed. Always keep a fallback: if socket.recovered is false, fetch a fresh snapshot.

State recovery replays broadcasted events by default, but your own application data (such as unsent messages in a form) is still your responsibility. Treat recovery as an optimization on top of a design that already works with plain reconnection.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Socket.IO add random jitter to reconnection delays?

    Jitter spreads retries over time and prevents a thundering herd that could overload the recovering server.
  2. 2. Which side sends the periodic ping in Socket.IO v4?

    The server pings every pingInterval; the client replies with a pong. Missing pongs lead to a ping timeout.
  3. 3. After an automatic reconnection without state recovery, which statement is true?

    A reconnect creates a new socket. Re-join rooms in the connect handler, or enable connection state recovery.
  4. 4. How do you know on the server that a connection was restored by state recovery?

    In the connection handler, socket.recovered indicates that the session and missed events were restored.

Summary

  • Clients reconnect automatically with exponential backoff and jitter; tune delays and attempts through client options.
  • The server pings, the client pongs; silence for pingInterval + pingTimeout ends the connection.
  • A reconnected socket is a new socket, so re-join rooms and resync in the connect handler.
  • Offline emit calls are buffered by the client unless marked volatile.
  • Connection state recovery restores id, rooms, data and missed events for short outages, with a fallback to a fresh snapshot.

Next: Rooms: Grouping Sockets