Connection Lifecycle and Reconnection
Understand disconnection reasons, automatic reconnection, recovery behavior, connection state, and how to handle temporary network failures.
Understand Socket Disconnection
A Socket.IO connection can close for several reasons.
Examples include:
- The user closes the browser tab.
- The network connection disappears.
- The server shuts down.
- A reverse proxy closes an inactive connection.
- The client explicitly disconnects.
- A transport error occurs.
The server receives the disconnect event when a socket connection closes.
The event callback provides a reason describing why the disconnection happened.
Use this event to clean up connection-specific resources and update application presence information.
io.on('connection', (socket) => {
console.log('Connected:', socket.id);
socket.on('disconnect', (reason) => {
console.log('Disconnected:', socket.id);
console.log('Reason:', reason);
});
});Registers a disconnect listener and logs the connection identifier and disconnection reason.
Disconnections can occur for several reasons.
The disconnect event provides a reason.
Connection-specific resources should be cleaned up.
Understand Automatic Reconnection
The Socket.IO client automatically attempts to reconnect after certain unexpected connection failures.
For example:
- A user opens the chat application.
- The connection is established.
- The network becomes temporarily unavailable.
- The connection closes.
- The browser attempts to reconnect.
- When the network becomes available, the client may reconnect successfully.
The server receives a new connection when reconnection succeeds.
A reconnection does not mean that the original connection has remained alive. The new connection may receive a different socket ID.
Automatic reconnection does not apply to every disconnection. For example, a deliberate client disconnect does not automatically trigger reconnection.
Socket.IO clients support automatic reconnection.
A reconnection establishes a new connection.
Socket IDs should not be treated as permanent identifiers.
Configure Reconnection Options
Socket.IO allows you to customize reconnection behavior when initializing the client.
Important options include:
reconnection: Enables or disables automatic reconnection.reconnectionAttempts: Maximum number of reconnection attempts.reconnectionDelay: Initial delay between attempts.reconnectionDelayMax: Maximum delay between attempts.randomizationFactor: Adds randomness to retry delays.
The client uses backoff behavior to avoid repeatedly reconnecting at an excessive rate.
Use reasonable retry limits and delays. Aggressive reconnection can increase load when a server or network is experiencing an outage.
const socket = io({
reconnection: true,
reconnectionAttempts: 10,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
randomizationFactor: 0.5
});Enables automatic reconnection with a maximum of ten attempts, an initial delay of one second, and a maximum delay of five seconds.
Reconnection behavior is configurable.
Backoff reduces excessive retry traffic.
Choose retry policies according to application requirements.
Handle Client Reconnection Events
The Socket.IO client exposes lifecycle events that help monitor reconnection attempts.
Useful events include:
connect.disconnect.connect_error.reconnect_attempt.reconnect.reconnect_failed.
Some reconnection-related events are emitted by the Socket.IO Manager rather than the individual Socket instance.
You can access the Manager through socket.io.
socket.on('disconnect', (reason) => {
console.log('Connection lost:', reason);
});
socket.on('connect_error', (error) => {
console.error('Connection error:', error.message);
});
socket.io.on('reconnect_attempt', (attempt) => {
console.log('Reconnection attempt:', attempt);
});
socket.io.on('reconnect', (attempt) => {
console.log('Reconnected after attempts:', attempt);
});
socket.io.on('reconnect_failed', () => {
console.error('Reconnection attempts exhausted');
});Registers listeners for connection errors and reconnection lifecycle events. Manager-level events are registered through socket.io.
Socket.IO exposes connection lifecycle events.
Manager-level reconnection events are registered through socket.io.
Use lifecycle events to update application status.
Understand Connection State Recovery
Socket.IO supports connection state recovery, which can restore certain session details and missed packets after a temporary disconnection.
The feature is useful when a client loses connectivity briefly and reconnects within the configured recovery window.
However, recovery is not guaranteed in every situation. The server may be unable to recover a session after a process restart, expired recovery window, or unsupported adapter configuration.
Connection state recovery does not replace persistent application storage.
Important considerations:
- Configure an appropriate recovery duration.
- Decide whether middleware should be skipped during recovery.
- Verify the recovered session and permissions.
- Handle cases where recovery fails.
- Persist important messages in a database.
Connection state recovery is a best-effort feature. Do not use it as a replacement for storing important messages or business data in a database. The standard Redis adapter does not support connection state recovery.
import { Server } from 'socket.io';
const io = new Server(httpServer, {
connectionStateRecovery: {
maxDisconnectionDuration: 2 * 60 * 1000,
skipMiddlewares: false
}
});Enables recovery for a two-minute window. Setting skipMiddlewares to false allows the connection middleware to run again during recovery.
Connection state recovery can restore certain session information.
Recovery is not guaranteed.
Persistent data must be stored independently.