Course contentsShow
← Node.js
Lesson 1082 of 1,98010. Real-time Communication and WebsocketsFree lesson

Implementing Automated Reconnection Logic

You will design robust client-side reconnection strategies with exponential backoff algorithms.

In this lesson, you will learn how to design a resilient client-side mechanism that automatically restores WebSocket connections using an exponential backoff strategy to prevent server overload.

The Problem with Immediate Retries

When a WebSocket connection drops, a naive approach is to immediately attempt a reconnect. However, if your server experiences a momentary blip or a spike in traffic, having hundreds of clients instantly hammering the server with connection requests creates a "thundering herd" problem. This can crash a recovering server.

The Exponential Backoff Strategy

Instead of retrying immediately, we introduce a delay that grows exponentially with each failed attempt. We calculate the delay as baseDelay * (2 ^ attemptCount). To prevent synchronization across multiple clients, we often add "jitter"—a random amount of time—to the delay. This ensures that clients don't all attempt to reconnect at the exact same millisecond.

Here is how you might structure this logic:

let attempt = 0;
const MAX_DELAY = 30000; // Cap at 30 seconds

function connect() {
  const socket = new WebSocket('ws://api.example.com');

  socket.onclose = () => {
    // Calculate delay: e.g., 1s, 2s, 4s, 8s...
    const delay = Math.min(1000 * Math.pow(2, attempt), MAX_DELAY);
    
    console.log(`Reconnecting in ${delay}ms...`);
    
    setTimeout(() => {
      attempt++;
      connect();
    }, delay + (Math.random() * 1000)); // Add jitter
  };

  socket.onopen = () => {
    console.log("Connected!");
    attempt = 0; // Reset on success
  };
}

Why This Matters

By scaling the wait time, you provide the server breathing room to recover from high load or network instability. The attempt counter ensures that the connection logic remains stateful, allowing the client to "back off" and wait longer if the server remains unresponsive, while the jitter ensures that when the server does come back online, it receives a staggered stream of connection attempts rather than a sudden, destructive surge.

Key Takeaway: Use exponential backoff with jitter to protect your server from recovery-phase congestion and ensure reliable, long-term WebSocket stability.