How do you handle WebSocket reconnection logic?

Answer

Robust reconnection uses exponential backoff with jitter to avoid thundering herd problems (all clients reconnecting simultaneously after a server restart). Implementation: let retryDelay = 1000; const maxDelay = 30000; function connect() { const ws = new WebSocket(url); ws.onopen = () => { retryDelay = 1000; }; ws.onclose = () => { const jitter = Math.random() * 1000; setTimeout(() => connect(), Math.min(retryDelay + jitter, maxDelay)); retryDelay *= 2; }; }. Key considerations: (1) State reconciliation — after reconnecting, fetch missed events from the server using a "last seen" event ID; (2) Message queuing — buffer messages sent while disconnected and replay them after reconnection; (3) User feedback — show a "reconnecting..." indicator in the UI; (4) Max attempts — stop retrying after N failures and show an error. Libraries like ReconnectingWebSocket encapsulate this logic.