WebSocket Client With Exponential Reconnect

Keep a WebSocket client alive through disconnects with exponential backoff reconnect, jitter, heartbeat pings, and a bounded retry budget.

JavascriptResilience

Code

javascriptsnippet
34 lines
import WebSocket from 'ws';

function createResilientSocket(url, { maxRetries = 8, baseMs = 500 } = {}) {
  let attempts = 0;
  let closed = false;
  let socket;

  const connect = () => {
    socket = new WebSocket(url);

    socket.on('open', () => {
      attempts = 0;
      socket.ping();
      socket.on('pong', () => console.log('heartbeat ok'));
    });

    socket.on('message', (data) => console.log('recv:', data.toString()));

    socket.on('close', (code) => {
      if (closed || attempts >= maxRetries) return;
      const jitter = Math.random() * baseMs;
      const delay = Math.min(2 ** attempts * baseMs + jitter, 30_000);
      attempts += 1;
      console.log('closed', code, 'retrying in', Math.round(delay), 'ms');
      setTimeout(connect, delay);
    });
  };

  connect();
  return { close: () => { closed = true; socket.terminate(); } };
}

const client = createResilientSocket('wss://stream.example.com/feed');
setTimeout(() => client.close(), 60_000);

How it works

WebSocket Client With Exponential Reconnect keeps everything in the functions connect and createResilientSocket.

A fresh value is allocated for the result; the arguments stay untouched.

Points of care

  • Plan for an install step: ws is a real dependency, resolved by the package manager.
  • The guard closed || attempts >= maxRetries short-circuits the flow with an early return when its condition holds.

Using it

The primary signature is const connect = ()

Running the file prints labeled results such as heartbeat ok, recv:, closed — each operation’s effect is visible in the output.

Key statements

return { close: () => { closed = true; socket.terminate(); } };
setTimeout(() => client.close(), 60_000);
socket.on('close', (code) => {
  if (closed || attempts >= maxRetries) return;
  const jitter = Math.random() * baseMs;
  const delay = Math.min(2 ** attempts * baseMs + jitter, 30_000);
  attempts += 1;
  console.log('closed', code, 'retrying in', Math.round(delay), 'ms');
  setTimeout(connect, delay);
});

Interactive Tools for This Topic

FAQ

Does `connect` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
What does this need from the package registry?
These are real dependencies: `ws`. Without it the snippet will not load.