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
Enter fullscreen mode
Exit fullscreen mode
1. Closed vs dead connections
A close event only fires when the TCP connection is actually torn down.…