A WebSocket client that works on your laptop will eventually meet the real world: load balancers that close idle connections, deploys on the server side, Wi-Fi drops, laptops waking from sleep. If the client simply calls new WebSocket() again in a tight loop, a server restart turns every client into a reconnect storm.
This tutorial builds a small, dependency-light reconnecting client for a streaming data feed (a live odds feed is the running example, but nothing here is specific to it). We will cover:
- Detecting a dead connection (not just a closed one)
- Exponential backoff with full jitter
- Resubscribing and resyncing state after reconnect
- A clean shutdown path
- Testing the backoff logic deterministically
The code targets Node.js 18+ with the ws package.
npm install ws
1. Closed vs dead connections
A close event only fires when the TCP connection is actually torn down. A half-open connection (the other side vanished without a FIN packet) can sit silently for minutes. The fix is a heartbeat: if nothing arrives within a deadline, treat the socket as dead and terminate it yourself.
The WebSocket protocol has built-in ping/pong frames. ws exposes them as socket.ping() and a 'pong' event. Many feeds also send application-level heartbeats as JSON messages; either works, as long as something resets the timer.
function armHeartbeat(socket, timeoutMs) {
let timer;
const reset = () => {
clearTimeout(timer);
timer = setTimeout(() => socket.terminate(), timeoutMs);
};
socket.on('open', reset);
socket.on('message', reset);
socket.on('pong', reset);
socket.on('close', () => clearTimeout(timer));
const pinger = setInterval(() => {
if (socket.readyState === socket.OPEN) socket.ping();
}, timeoutMs / 2);
socket.on('close', () => clearInterval(pinger));
}
terminate() destroys the socket immediately, which then emits close, so the reconnect path below handles dead and closed connections the same way.
2. Exponential backoff with full jitter
Plain exponential backoff (1 s, 2 s, 4 s, ...) still synchronises clients: everybody disconnected at the same moment retries at the same moments. Adding randomness spreads them out. The "full jitter" variant picks a uniformly random delay between 0 and the exponential cap:
delay = random(0, min(maxDelay, base * 2 ** attempt))
function backoffDelay(attempt, { baseMs = 500, maxMs = 30_000, random = Math.random } = {}) {
const cap = Math.min(maxMs, baseMs * 2 ** attempt);
return Math.floor(random() * cap);
}
Passing random in as a parameter keeps the function pure, which makes it trivial to test later.
Reset attempt to zero only after the connection has been healthy for a while (for example after the first message), not on open. Otherwise a server that accepts and then immediately closes connections keeps the client retrying at the minimum delay forever.
3. The reconnecting client
const WebSocket = require('ws');
const { EventEmitter } = require('node:events');
class ReconnectingFeed extends EventEmitter {
constructor(url, { subscriptions = [], heartbeatMs = 20_000, ...backoff } = {}) {
super();
this.url = url;
this.subscriptions = new Set(subscriptions);
this.heartbeatMs = heartbeatMs;
this.backoff = backoff;
this.attempt = 0;
this.stopped = false;
this.socket = null;
this.retryTimer = null;
}
start() {
this.stopped = false;
this.#connect();
}
subscribe(channel) {
this.subscriptions.add(channel);
this.#send({ op: 'subscribe', channel });
}
unsubscribe(channel) {
this.subscriptions.delete(channel);
this.#send({ op: 'unsubscribe', channel });
}
stop() {
this.stopped = true;
clearTimeout(this.retryTimer);
if (this.socket) this.socket.close(1000, 'client shutdown');
}
#send(msg) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(msg));
}
// If not open, the subscription set is replayed on the next 'open'.
}
#connect() {
const socket = new WebSocket(this.url);
this.socket = socket;
armHeartbeat(socket, this.heartbeatMs);
let healthy = false;
socket.on('open', () => {
this.emit('open');
for (const channel of this.subscriptions) {
socket.send(JSON.stringify({ op: 'subscribe', channel }));
}
});
socket.on('message', (data) => {
if (!healthy) {
healthy = true;
this.attempt = 0;
}
let msg;
try {
msg = JSON.parse(data);
} catch {
return this.emit('error', new Error('non-JSON frame'));
}
this.emit('message', msg);
});
socket.on('error', (err) => this.emit('error', err));
socket.on('close', (code, reason) => {
this.emit('close', code, reason.toString());
if (this.stopped) return;
const delay = backoffDelay(this.attempt++, this.backoff);
this.emit('reconnecting', { attempt: this.attempt, delay });
this.retryTimer = setTimeout(() => this.#connect(), delay);
});
}
}
module.exports = { ReconnectingFeed, backoffDelay };
Design choices worth calling out:
-
Subscriptions live in the client, not in the socket. The set is the source of truth and is replayed on every
open. Calls made while disconnected are not lost. -
errornever triggers a reconnect directly. Inws, anerroris always followed byclose, so reconnecting in both handlers would schedule two connections. -
An
errorlistener is always attached on the emitter's consumer side (see below). AnEventEmitterwith no'error'listener throws and crashes the process.
4. Resyncing state after a gap
Reconnecting the socket is only half the job. While you were disconnected, the data kept changing, and incremental updates you missed are gone. Two common patterns:
- Snapshot on subscribe. The server sends a full snapshot when you subscribe, then deltas. Clear your local copy of that channel when the snapshot arrives and rebuild from it.
-
Sequence numbers. Each delta carries a monotonically increasing
seq. If a delta arrives withseq !== last + 1, you have a gap and should request a fresh snapshot (or fall back to a REST endpoint) before applying more deltas.
A small guard for the second pattern:
function makeSequencer(onGap) {
const last = new Map(); // channel -> last seq
return (msg) => {
if (msg.type === 'snapshot') {
last.set(msg.channel, msg.seq);
return true;
}
const prev = last.get(msg.channel);
if (prev === undefined || msg.seq !== prev + 1) {
onGap(msg.channel);
return false; // drop until the next snapshot
}
last.set(msg.channel, msg.seq);
return true;
};
}
Field names (type, seq, channel) vary by provider; adapt them to the message format your feed documents.
5. Wiring it together
const { ReconnectingFeed } = require('./reconnecting-feed');
const feed = new ReconnectingFeed(process.env.FEED_URL, {
subscriptions: ['soccer'],
heartbeatMs: 20_000,
baseMs: 500,
maxMs: 30_000,
});
const accept = makeSequencer((channel) => {
console.warn('gap on', channel, '- resubscribing for a fresh snapshot');
feed.unsubscribe(channel);
feed.subscribe(channel);
});
feed.on('message', (msg) => {
if (!accept(msg)) return;
// apply snapshot or delta to your in-memory state here
});
feed.on('reconnecting', ({ attempt, delay }) =>
console.log(`reconnect attempt ${attempt} in ${delay} ms`));
feed.on('error', (err) => console.error('feed error:', err.message));
feed.start();
process.on('SIGINT', () => {
feed.stop();
process.exit(0);
});
Keep credentials out of the URL in logs: if your provider authenticates with a query-string token, redact it before printing this.url anywhere.
6. Testing the backoff deterministically
Because backoffDelay takes its random source as a parameter, the tests need no timers or mocks:
const test = require('node:test');
const assert = require('node:assert');
const { backoffDelay } = require('./reconnecting-feed');
test('delay grows exponentially and is capped', () => {
const max = () => 0.999999;
assert.strictEqual(backoffDelay(0, { baseMs: 500, random: max }), 499);
assert.strictEqual(backoffDelay(3, { baseMs: 500, random: max }), 3999);
assert.strictEqual(backoffDelay(20, { baseMs: 500, maxMs: 30_000, random: max }), 29999);
});
test('full jitter can return zero', () => {
assert.strictEqual(backoffDelay(5, { random: () => 0 }), 0);
});
Run with node --test. For the reconnect flow itself, spin up a local new WebSocket.Server({ port: 0 }) in the test, close the server-side socket, and assert that a second connection event arrives.
Checklist
- Heartbeat with a deadline;
terminate()on timeout - Full-jitter exponential backoff, capped
- Reset the attempt counter only after a healthy message
- Reconnect from
closeonly, never fromerror - Keep subscriptions client-side and replay them on
open - Detect gaps with snapshots or sequence numbers
- A
stop()that cancels pending retries
With these pieces, a server deploy becomes a short blip in your logs instead of an outage, and the reconnect traffic stays spread out.
Against a live Pinnacle odds stream
The same heartbeat, jittered backoff and subscription-replay pattern is what you want against a live Pinnacle book. PinnFeed's WebSocket docs describe the snapshot, delta and ping contract this client is written to survive.
Editorial note: Tools for Bettors publishes independent reviews and guides on betting tools and odds data.
Top comments (0)