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.
Previous
What are Socket.IO rooms and namespaces?
Next
What is the difference between Socket.IO and raw WebSockets?
More WebSockets & Real-time Questions
View all →- Intermediate How do you implement a WebSocket server in Node.js using the `ws` library?
- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do you authenticate WebSocket connections?
- Intermediate How do WebSockets work behind a load balancer?