patterntypescriptModerate
Exponential Backoff With Jitter Is Required for WebSocket Reconnection
Viewed 0 times
exponential backoffjitterwebsocket reconnectthundering herdbackoff strategyconnection retry
Problem
After a server restart or network outage, all connected WebSocket clients attempt to reconnect simultaneously, creating a thundering herd that overloads the server before it can accept connections.
Solution
Implement exponential backoff with random jitter for reconnection attempts. Cap the maximum backoff to avoid clients giving up too soon but not hammering a still-recovering server.
function reconnectWithBackoff(url: string, onMessage: (data: unknown) => void) {
let attempt = 0;
const MAX_DELAY = 30_000;
const BASE_DELAY = 500;
function connect() {
const ws = new WebSocket(url);
ws.onopen = () => { attempt = 0; };
ws.onmessage = (e) => onMessage(JSON.parse(e.data));
ws.onclose = (event) => {
if (event.code === 1000) return; // normal close
const delay = Math.min(BASE_DELAY * 2 ** attempt, MAX_DELAY);
const jitter = Math.random() * delay * 0.5;
attempt++;
setTimeout(connect, delay + jitter);
};
}
connect();
}Why
Without jitter, all clients compute the same backoff delay and reconnect in synchronized waves. Random jitter spreads reconnection attempts over the delay window, reducing peak load by an order of magnitude.
Gotchas
- Close code 1000 (normal) and 1001 (going away / page unload) should not trigger reconnection.
- Reset attempt counter to 0 on successful open — otherwise the first disconnect after a long session backs off too aggressively.
- Surface reconnecting state in the UI — users should know the app is trying to restore the connection.
- Libraries like reconnecting-websocket implement this pattern — don't reinvent unless you need custom behavior.
Revisions (0)
No revisions yet.