Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Reliability and Acknowledgements

Reconnection and Backoff

Tune Socket.IO reconnection: backoff delay and jitter, disconnect reasons, heartbeat settings, and the client events that tell you what the connection is doing.

Socket.IO clients reconnect on their own. Understanding how, and when they do not, lets you build interfaces that stay honest ("reconnecting...") and servers that survive a mass reconnect after a restart. This lesson covers the heartbeat that detects dead connections, the backoff algorithm, the disconnect reasons, and the client events to listen to.

The real client library is not installed in the runner on this site, so the real calls are read-only. The runnable examples are plain Node.js stand-ins that compute the same schedule and run a small state machine.

Detecting a dead connection: the heartbeat

A TCP connection can silently die: the phone loses signal, a NAT forgets the mapping. Neither side gets an error until it tries to write. Socket.IO therefore runs its own heartbeat: since version 4, the server sends a ping every pingInterval (25 000 ms by default) and the client must answer with a pong within pingTimeout (20 000 ms). If no pong arrives, the server closes the socket with the reason ping timeout. The client mirrors this: if it does not hear a ping within pingInterval + pingTimeout, it considers the connection lost.

JavaScript
const io = new Server(httpServer, {
  pingInterval: 25000,
  pingTimeout: 20000,
});

A lower interval detects failures faster and costs more traffic. A proxy or load balancer with an idle timeout shorter than the heartbeat will kill healthy connections, so keep timeouts above the heartbeat sum (see sticky sessions).

The backoff algorithm

When the connection drops (for any reason except an explicit close), the client's Manager tries again after a delay that grows with each failure. Without growth, ten thousand clients would hammer a restarting server at once. The options, all on the client:

Option Default Meaning
reconnection true Reconnect automatically
reconnectionAttempts Infinity Give up after this many tries
reconnectionDelay 1000 First delay in ms
reconnectionDelayMax 5000 Upper limit of the delay
randomizationFactor 0.5 Jitter: delay varies by plus or minus this fraction

The base delay doubles each attempt (1 s, 2 s, 4 s, then capped at 5 s) and a random jitter of up to plus or minus 50 percent is applied so clients spread out.

Node.js Compute a backoff schedule (stand-in)

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.

The two default clients wait different times from the first attempt on. With zero jitter, every client would retry at the same instants, causing a thundering herd. For a large fleet, raise randomizationFactor and reconnectionDelayMax.

Why did it disconnect?

The disconnect event passes a reason. It tells you whether the client will try again.

Reason Who closed Reconnects automatically?
io server disconnect Server called socket.disconnect() No: call socket.connect() yourself
io client disconnect Client called socket.disconnect() No
ping timeout Heartbeat failed Yes
transport close Connection lost (network, server stop) Yes
transport error The transport reported an error Yes
JavaScript
socket.on("disconnect", (reason, details) => {
  if (reason === "io server disconnect") {
    // the server refused or kicked us; reconnecting blindly would just repeat it
    socket.connect(); // only if you do want another try, e.g. after refreshing a token
  }
  // other reasons: the client reconnects by itself
  showBanner("Connection lost, trying to reconnect...");
});

The property socket.active tells you whether the socket will try to reconnect (true for the temporary failures above, false after a server-forced or client-forced disconnect).

Events on the Manager

The reconnection logic lives in the Manager (socket.io), not the socket, because several namespaces share one connection:

JavaScript
socket.io.on("reconnect_attempt", (attempt) => {
  // refresh anything that changes between attempts, e.g. a token
  socket.auth = { token: getFreshToken() };
});
socket.io.on("reconnect", (attempt) => console.log("back after", attempt, "attempts"));
socket.io.on("reconnect_error", (err) => console.log("attempt failed", err.message));
socket.io.on("reconnect_failed", () => console.log("gave up"));

Use reconnect_attempt to refresh credentials and reconnect_failed (only fires when you set reconnectionAttempts) to show a permanent error with a "retry" button.

A connection's life

Connected Pings flow, events flow.
Disconnected A reason is reported.
Reconnecting Backoff delay plus jitter between attempts.
Gave up Only if attempts are limited.

Server-forced disconnects need a manual connect.

1 / 2

A state machine for your UI

Instead of sprinkling booleans, model the connection as a few states and let events move between them. Your banner, disabled buttons and message queue all read from one value.

Node.js Connection state machine (stand-in)

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.

Practical tips

  • Do not trust connect to mean fresh: after each reconnect, re-run any setup your app needs (re-join rooms, re-subscribe, fetch missed data) unless socket.recovered is true. See delivery guarantees.
  • Put "connect" logic inside socket.on("connect", ...), not just once at start-up, because it fires on every reconnection.
  • Prepare for a thundering herd: after a deploy or crash all clients reconnect together. Jitter helps; so does rolling restarts and keeping the handshake cheap (see security and rate limiting).
  • Mobile apps: pause the connection in the background if the OS would kill it anyway, and reconnect on resume.
  • Do not set reconnectionDelay below a few hundred milliseconds, unless you enjoy being a self-inflicted denial of service.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens after a disconnect with the reason io server disconnect?

    The server closed the socket on purpose, so the client does not retry automatically. You must decide to call connect.
  2. 2. Why does the backoff algorithm add random jitter?

    Jitter spreads reconnection attempts, so a server that just restarted is not hit by every client simultaneously.
  3. 3. With the defaults, what is the longest delay between attempts (before jitter)?

    reconnectionDelayMax defaults to 5000 ms; the doubling delay is capped there.
  4. 4. Where do you listen for reconnect_attempt?

    Reconnection is handled by the Manager, which sits on the socket as socket.io.

Summary

  • The server pings every pingInterval; a missing pong within pingTimeout ends the connection.
  • Backoff doubles from reconnectionDelay up to reconnectionDelayMax, with randomizationFactor jitter.
  • io server disconnect and io client disconnect need a manual connect(); other reasons reconnect automatically.
  • Listen to reconnect_attempt, reconnect and reconnect_failed on socket.io.
  • Model connection status as a small state machine and redo setup on every connect.

Next: Socket.IO with Express