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.…