100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Handling Reconnection

Understand Socket.IO's built-in automatic reconnection behavior, how to configure and tune it, and how to restore application state like room membership after a client reconnects.

Rooms & ScalingIntermediate9 min readJul 10, 2026
Analogies

Automatic Reconnection Behavior

The Socket.IO client automatically attempts to reconnect whenever the connection drops for a reason other than the server explicitly calling socket.disconnect() — network blips, server restarts, or a laptop coming back from sleep all trigger the reconnection state machine by default, with no extra code required. The client uses exponential backoff between attempts, controlled by reconnectionDelay (default 1000ms) and reconnectionDelayMax (default 5000ms), with randomizationFactor (default 0.5) jittering each delay so that thousands of clients reconnecting after a server restart don't all hammer the server in the exact same instant.

🏏

Cricket analogy: It's like a rain-delayed match automatically resuming once conditions clear, with the umpires checking pitch readiness at increasing intervals rather than every player rushing back onto the field the second rain stops, avoiding a chaotic pile-up at the boundary rope.

javascript
// Client: configuring reconnection behavior
const socket = io('https://api.example.com', {
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
  randomizationFactor: 0.5,
});

socket.on('disconnect', (reason) => {
  console.log('disconnected:', reason);
  if (reason === 'io server disconnect') {
    // server intentionally kicked us; must reconnect manually
    socket.connect();
  }
  // otherwise the client auto-reconnects
});

socket.io.on('reconnect_attempt', (attempt) => {
  console.log('reconnect attempt #', attempt);
});

socket.io.on('reconnect', () => {
  // Re-join rooms the user was in before disconnecting
  socket.emit('join-room', currentRoomId);
});

Disconnect Reasons and Manual Reconnection

The disconnect event handler receives a reason string that determines whether auto-reconnection will actually happen: reasons like 'transport close' or 'ping timeout' trigger automatic reconnection, but 'io server disconnect' (the server explicitly called socket.disconnect()) and 'io client disconnect' (your own code called socket.disconnect()) are treated as intentional and do NOT auto-reconnect — you must call socket.connect() yourself if you want to resume after those. This distinction exists so that a server deliberately banning or logging out a client doesn't get immediately fought by the client's own reconnection logic reconnecting right back.

🏏

Cricket analogy: It's like the difference between a player retiring hurt (accidental, they'll come back if fit) versus being given out by the umpire (intentional, they must formally appeal or wait for the next innings rather than just walking back to the crease) — only one of these situations invites an automatic return.

Restoring State After Reconnection

Because room membership lives on the server and is tied to a specific socket connection, a reconnected client gets an entirely new socket.id and starts with zero room memberships — any rooms it was in before disconnecting must be explicitly rejoined, typically by listening for the reconnect event on socket.io (not socket) and re-emitting the same join-room events used on initial connection. Since Socket.IO v4.6, connection state recovery (connectionStateRecovery option) offers a built-in alternative: if enabled and the disconnection was brief enough (within a configurable maxDisconnectionDuration), the server can automatically restore the socket's previous rooms and replay any missed broadcast events, avoiding the need to manually re-implement rejoin logic for short blips.

🏏

Cricket analogy: It's like a player who left the field for a brief medical timeout resuming their exact fielding position and over count automatically if they're back within a few minutes, versus a player who missed a whole session needing to be formally re-assigned a position by the captain.

Connection state recovery (connectionStateRecovery) must be explicitly enabled on the server with new Server(httpServer, { connectionStateRecovery: {} }), and it requires a compatible adapter (the in-memory adapter supports it, as does the Redis adapter from a recent enough version) to actually buffer and replay missed events.

Do not assume socket.id stays stable across a reconnect — it does not, even with connection state recovery enabled. Any server-side data structure keyed by the old socket.id (outside of what the adapter itself restores, like room membership) must be re-associated with the new socket.id yourself, typically by keying your own application state off a stable user ID instead.

  • The client automatically reconnects on unintentional disconnects (network drop, ping timeout) using exponential backoff with jitter.
  • reconnectionDelay, reconnectionDelayMax, and randomizationFactor control the backoff timing and spread of reconnect attempts.
  • 'io server disconnect' and 'io client disconnect' reasons do NOT trigger auto-reconnection since they were intentional.
  • A reconnected socket gets a brand-new socket.id and starts with zero room memberships by default.
  • Listen for 'reconnect' on socket.io (not socket) to re-run join-room logic after reconnection.
  • connectionStateRecovery (v4.6+) can automatically restore rooms and replay missed events for short disconnections.
  • Never assume socket.id is stable across reconnects — key your own application state off a stable user ID instead.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#SocketIOStudyNotes#HandlingReconnection#Handling#Reconnection#Automatic#Behavior#StudyNotes#SkillVeris#ExamPrep