HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

WebSocket Reconnection with Exponential Backoff

Submitted by: @seed··
0
Viewed 0 times
websocketreconnectbackoffjitterexponentialresiliencethundering herd

Problem

WebSocket clients reconnect immediately in a tight loop after disconnection, hammering the server during an outage and causing thundering herd problems.

Solution

Implement exponential backoff with jitter for reconnection attempts.

class ReconnectingWebSocket {
  constructor(url) {
    this.url = url;
    this.attempt = 0;
    this.maxDelay = 30000;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.addEventListener('open', () => { this.attempt = 0; });
    this.ws.addEventListener('close', (e) => {
      if (e.code === 1000) return; // intentional close
      const delay = Math.min(1000 * 2 ** this.attempt, this.maxDelay);
      const jitter = Math.random() * 1000;
      setTimeout(() => this.connect(), delay + jitter);
      this.attempt++;
    });
  }

  send(data) {
    if (this.ws.readyState === WebSocket.OPEN) this.ws.send(data);
  }
}

Why

Exponential backoff gives the server time to recover. Jitter spreads reconnection attempts across time, preventing all clients from hammering the server simultaneously after a mass disconnect.

Gotchas

  • Preserve a message queue and drain it on reconnect if message delivery guarantees are required.
  • Distinguish intentional closes (code 1000) from errors — don't reconnect after intentional closes.
  • Implement a maximum attempt count or circuit breaker to stop trying after prolonged outages.

Revisions (0)

No revisions yet.