Originally published on tjalam.com.
The naive implementation and why it fails
The first version of most WebSocket integrations looks the same: open a connection, subscribe to a symbol, update the UI on every message. It works perfectly in a demo and falls over within days in production - usually when the connection silently drops (no error thrown, just no more messages) and nobody notices until a user reports stale prices.
Heartbeats and dead-connection detection
Most exchange WebSocket APIs support (or require) a ping/pong heartbeat. If you don't implement one, you need your own: track the timestamp of the last received message, and if it exceeds an expected threshold (e.g., 1.5x the expected update interval), assume the connection is dead and force a reconnect - even if the socket object itself hasn't fired a close event. TCP connections can go stale without any client-side signal.
Reconnection strategy
Use exponential backoff with jitter for reconnect attempts to avoid hammering the exchange's API and getting rate-limited or IP-banned during an outage. On reconnect, always re-fetch a full snapshot via REST before resuming to trust incremental WebSocket updates - otherwise a missed message during the disconnect window leaves your local state permanently wrong.
- Exponential backoff: 1s, 2s, 4s, 8s... capped at a reasonable max (e.g., 30s)
- Add random jitter so many clients reconnecting after a shared outage don't all hit the server simultaneously
- Always resync via REST snapshot before trusting further deltas
Handling multiple exchanges with different message formats
If you're aggregating data from Binance, Kraken, Coinbase, or others, normalize every incoming message into one internal shape immediately at the connection layer. Don't let exchange-specific field names or units (satoshis vs. BTC, different timestamp formats) leak into your application logic - it becomes unmaintainable within a few integrations.
Related: Crypto trading bot development· Broker and exchange API integration
Client-side performance at scale
For UIs subscribing to many symbols (a full order book or a large watchlist), batch incoming updates and flush them to the render layer on a fixed interval (e.g., every 100–250ms) rather than re-rendering on every single message. This single change often has more impact on perceived performance than any component-level optimization.
Monitoring is part of the architecture
Track connection uptime, reconnect frequency, and message latency per feed as first-class metrics, not an afterthought. A feed that reconnects constantly is telling you something - usually a rate limit issue or a bug in your subscription logic - long before users start complaining about stale prices.
Related: Custom trading platform development
Snapshots, sequence numbers and gap detection
Order book feeds send changes, not the full book. To build a correct local book you need a starting snapshot and every change after it, in order. Most exchanges number their updates so you can check that nothing was missed; Binance's documentation for its depth stream describes this exact procedure.
The pattern is the same everywhere. Open the WebSocket first and buffer updates. Fetch a REST snapshot, which carries its own update ID. Drop buffered updates older than the snapshot, apply the rest, and from then on check that each update's number follows the last one. If a number is skipped, the book is wrong: discard it and start again from a new snapshot. Never try to patch a gap.
Some exchanges, such as Kraken and OKX, also send a checksum of the top of the book. Compare it with your own after each update; a mismatch is the fastest way to catch a bug in your merge logic.
A reconnecting feed client in TypeScript
The client below is on GitHub as ws-feed-client (MIT), with tests.
The sketch below puts the earlier sections together: a watchdog for silent drops, reconnects with exponential backoff and jitter, and a resync after every new connection.
type FeedHandlers = {
onMessage: (msg: unknown) => void;
resync: () => Promise<void>; // load a REST snapshot, then apply buffered deltas
};
export function connectFeed(url: string, subscribe: object, h: FeedHandlers) {
const STALE_MS = 15_000; // about 1.5x the feed's slowest normal gap
let ws: WebSocket | null = null;
let attempt = 0;
let lastMessage = Date.now();
let stopped = false;
const reconnect = () => {
if (stopped) return;
const cap = Math.min(30_000, 1_000 * 2 ** attempt++);
setTimeout(open, cap / 2 + Math.random() * (cap / 2)); // backoff with jitter
};
function open() {
if (stopped) return;
const sock = new WebSocket(url);
ws = sock;
lastMessage = Date.now();
sock.onopen = () => {
attempt = 0;
sock.send(JSON.stringify(subscribe));
void h.resync();
};
sock.onmessage = (ev) => {
lastMessage = Date.now();
h.onMessage(JSON.parse(String(ev.data)));
};
sock.onerror = () => sock.close();
sock.onclose = () => {
if (ws === sock) ws = null;
reconnect();
};
}
// A dead TCP connection can stay "open" with no close event: watch the clock.
const watchdog = setInterval(() => {
if (ws && Date.now() - lastMessage > STALE_MS) {
const dead = ws;
ws = null;
dead.onclose = null;
dead.close();
reconnect();
}
}, 5_000);
open();
return () => {
stopped = true;
clearInterval(watchdog);
if (ws) {
ws.onclose = null;
ws.close();
}
};
}
One exchange connection, many users
Do not open an exchange connection from every user's browser. Exchanges cap connections and subscriptions per IP and per key, and browsers cannot hold API keys safely. Run one connection per stream on your server, normalise the messages there, and publish to your own clients over your own WebSocket or server-sent events.
This also lets you keep the latest snapshot in memory, so a user who opens the page gets a full book at once instead of waiting for the next update. And it gives you one place to measure latency and gaps, instead of thousands of browsers you cannot see.
Testing a feed before it goes live
Feeds fail in production in ways a quick local test never shows. Test these on purpose:
- Replay recorded messages from a real session and check the final book matches a snapshot taken at the same moment
- Cut the network in the middle of a busy period and confirm the client resyncs instead of carrying on with a stale book
- Inject a skipped sequence number and a duplicate message, and check both are caught
- Run a soak test for at least a day with metrics on reconnects, gaps and latency
- Load the client UI with your largest realistic watchlist and check it still renders smoothly on a mid-range laptop
Related: Broker and exchange API integration· How to build a trading platform
I'm TJ Alam. I build custom trading platforms, bots and broker integrations at tjalam.com. The full version of this guide stays up to date there.
Top comments (0)