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;
}
| Component | Detail |
| Trigger | close with non-1000 code |
| Backoff | Exponential + jitter |
| Cap | Max attempts / max delay |
| State | Preserve subscriptions, pending requests |
2. Using Exponential Backoff
Example: Backoff function
function backoff(attempt, base = 500, cap = 30000) {
return Math.min(cap, base * 2 ** attempt);
}
| Attempt | Delay (base=500ms) |
| 1 | 500ms |
| 2 | 1s |
| 3 | 2s |
| 4 | 4s |
| 5 | 8s |
| 6+ | Capped (30s) |
3. Setting Maximum Retry Attempts
| Policy | When to Use |
| Infinite | Background 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
}
| Type | Formula |
| Full | rand(0, exp) |
| Equal | exp/2 + rand(0, exp/2) |
| Decorrelated | min(cap, rand(base, prev*3)) |
Note: Jitter prevents thundering-herd reconnect storms after server restart.
5. Handling Network Status
| API | Use |
navigator.onLine | Coarse online state |
online / offline events | Transition signals |
navigator.connection | Type/RTT/downlink |
visibilitychange | Pause when tab hidden |
6. Preserving Connection State
| State | Restore On Reconnect |
| Subscriptions | Replay subscribe messages |
| Auth | Re-authenticate |
| Pending requests | Re-send or reject |
| Last seq received | Request resume from N+1 |
7. Implementing Circuit Breaker Pattern
| State | Behavior |
| Closed | Normal connect attempts |
| Open | Stop attempts for cool-down window |
| Half-open | Single trial; on success → Closed |
Example: Trip on threshold
if (failureCount >= 5) {
state = "open";
setTimeout(() => state = "half-open", 60000);
}
8. Detecting Connection Health
| Signal | Health Indicator |
| Missed pongs | Stale connection |
High bufferedAmount | Network slow |
| No messages X ms | Maybe dead idle |
| High RTT | Degraded |
9. Handling Manual Reconnection
Example: User-triggered reconnect
document.querySelector("#retry").addEventListener("click", () => {
attempts = 0; // reset backoff
connect();
});
| UX | Detail |
| Show retry button | After auto-retries exhausted |
| Reset counters | Manual implies fresh attempt |
| Inline status | Don't block UI |
10. Testing Reconnection Logic
| Test | How |
| Server kill | Stop process; expect backoff |
| Network drop | Toggle Wi-Fi or DevTools offline |
| Slow handshake | Add proxy delay |
| Auth expiry | Force 401 mid-stream |
| Restart storm | Cycle many clients; verify jitter |