Calm WebSocket Reconnection: Jitter, Queues, and Backpressure
How to avoid thundering herds during deploys and keep real-time UI dashboards responsive when cellular connections drop.
- Realtime
- WebSockets
- Reliability
- TypeScript
When a backend deployment restarts 50,000 open WebSocket connections simultaneously, naive fixed-interval retries turn a routine rollout into a self-inflicted outage. The fix starts on the client.
1. Full jitter beats deterministic backoff
Instead of retrying every 2 seconds, compute a capped exponential ceiling and pick a random delay between zero and that ceiling. Combined with visibility-aware heartbeats, reconnect traffic spreads smoothly over tens of seconds.
export function nextBackoffMs(attempt: number, base = 400, cap = 15000): number {
const exp = Math.min(cap, base * Math.pow(2, attempt));
return Math.round(Math.random() * exp);
}
2. Visibility-aware heartbeats
Mobile browsers aggressively throttle background tabs, which causes false-positive ping timeouts if you rely on fixed setInterval timers. Pause aggressive liveness checks while document.hidden is true and issue a single fast probe when the tab wakes up.
3. Bound offline queues & coalesce state
Finally, bound your offline outbound queue and coalesce stale state updates by entity ID so reconnecting clients sync latest intent instead of replaying stale clicks.