How do you handle reconnection and heartbeats for persistent connections?

Topic: microservices, Real-Time Communication. Level: Intermediate.

Answer

Networks drop; persistent connections must detect death and recover. Use **heartbeats** (periodic ping/pong) to detect a half-open connection faster than TCP timeouts. On disconnect, **reconnect with exponential backoff + jitter** to avoid thundering herds. Preserve continuity: resume from a last-seen id/offset (SSE `Last-Event-ID`, or an app-level sequence) so no messages are lost or duplicated. Make message handling idempotent since reconnection can replay. ```js let delay = 1000 function connect() { const ws = new WebSocket(`wss://x/stream?since=${lastSeenId}`) // resume point const hb = setInterval(() => ws.readyState === 1 && ws.send('ping'), 15000) ws.onmessage = e => { if (e.data !== 'pong') { lastSeenId = handle(e.data); } } ws.onclose = () => { clearInterval(hb) setTimeout(connect, Math.min(delay *= 2, 30000) + Math.random() * 1000) // backoff+jitter } ws.onopen = () => { delay = 1000 } } connect() ```