Course contentsShow
← Web Development
Lesson 880 of 2,98215. Browser NetworkingFree lesson

WebSocket Error Handling and Reconnection

Detecting disconnections, implementing exponential backoff, and maintaining connection resilience.

WebSocket Error Handling and Reconnection

You'll learn how to keep WebSocket connections alive and gracefully recover when they drop.

Why Connections Fail

WebSocket connections are persistent but fragile—they can break due to network hiccups, server restarts, or mobile devices switching between WiFi and cellular. Unlike regular HTTP requests, a dropped WebSocket doesn't automatically retry. You need to detect failures and reconnect intelligently.

Detecting Disconnections

Use the WebSocket's onerror and onclose event handlers to detect when something goes wrong:

const socket = new WebSocket('wss://api.example.com');

socket.onerror = (error) => {
  console.error('WebSocket error:', error);
};

socket.onclose = (event) => {
  console.log('Connection closed:', event.code, event.reason);
  reconnect(); // Trigger reconnection logic
};

Exponential Backoff

Think of exponential backoff like a polite guest who knocks louder each time but waits longer between attempts. Instead of hammering the server every second, wait 1s, then 2s, then 4s, then 8s:

let reconnectDelay = 1000; // Start at 1 second
const maxDelay = 30000; // Cap at 30 seconds

function reconnect() {
  setTimeout(() => {
    console.log(`Reconnecting in ${reconnectDelay}ms...`);
    const socket = new WebSocket('wss://api.example.com');
    
    socket.onopen = () => {
      reconnectDelay = 1000; // Reset delay on success
    };
    
    socket.onclose = () => {
      reconnectDelay = Math.min(reconnectDelay * 2, maxDelay);
      reconnect();
    };
  }, reconnectDelay);
}

This prevents overwhelming a struggling server while maintaining connection resilience.

Key Takeaway: Robust WebSocket apps detect disconnections via onerror/onclose, then reconnect using exponential backoff to balance persistence with server respect.