Implementing Reconnection Strategies

1. Implementing Automatic Reconnection

Example: Auto-reconnect skeleton

function connect() {
  const ws = new WebSocket(URL);
  ws.addEventListener("close", (e) => {
    if (e.code !== 1000) setTimeout(connect, backoff());
  });
  return ws;
}
ComponentDetail
Triggerclose with non-1000 code
BackoffExponential + jitter
CapMax attempts / max delay
StatePreserve subscriptions, pending requests

2. Using Exponential Backoff

Example: Backoff function

function backoff(attempt, base = 500, cap = 30000) {
  return Math.min(cap, base * 2 ** attempt);
}
AttemptDelay (base=500ms)
1500ms
21s
32s
44s
58s
6+Capped (30s)

3. Setting Maximum Retry Attempts

PolicyWhen to Use
InfiniteBackground app needs to stay connected
Bounded (e.g. 10)Foreground UX — give up + show error
Time-bound"Retry for 5 minutes then give up"

4. Implementing Jitter

Example: Full jitter

function jitter(base, attempt, cap = 30000) {
  const exp = Math.min(cap, base * 2 ** attempt);
  return Math.random() * exp; // full jitter
}
TypeFormula
Fullrand(0, exp)
Equalexp/2 + rand(0, exp/2)
Decorrelatedmin(cap, rand(base, prev*3))
Note: Jitter prevents thundering-herd reconnect storms after server restart.

5. Handling Network Status

APIUse
navigator.onLineCoarse online state
online / offline eventsTransition signals
navigator.connectionType/RTT/downlink
visibilitychangePause when tab hidden

6. Preserving Connection State

StateRestore On Reconnect
SubscriptionsReplay subscribe messages
AuthRe-authenticate
Pending requestsRe-send or reject
Last seq receivedRequest resume from N+1

7. Implementing Circuit Breaker Pattern

StateBehavior
ClosedNormal connect attempts
OpenStop attempts for cool-down window
Half-openSingle trial; on success → Closed

Example: Trip on threshold

if (failureCount >= 5) {
  state = "open";
  setTimeout(() => state = "half-open", 60000);
}

8. Detecting Connection Health

SignalHealth Indicator
Missed pongsStale connection
High bufferedAmountNetwork slow
No messages X msMaybe dead idle
High RTTDegraded

9. Handling Manual Reconnection

Example: User-triggered reconnect

document.querySelector("#retry").addEventListener("click", () => {
  attempts = 0; // reset backoff
  connect();
});
UXDetail
Show retry buttonAfter auto-retries exhausted
Reset countersManual implies fresh attempt
Inline statusDon't block UI

10. Testing Reconnection Logic

TestHow
Server killStop process; expect backoff
Network dropToggle Wi-Fi or DevTools offline
Slow handshakeAdd proxy delay
Auth expiryForce 401 mid-stream
Restart stormCycle many clients; verify jitter