Reconnection Strategies
Reconnect reliably after drops.
Reconnection Strategies is a free JavaScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Reconnect?
Networks are unreliable — Wi-Fi drops, laptops sleep, servers restart. A robust WebSocket client detects closure and automatically re-establishes the connection so the user experience stays seamless.
Naive Reconnect
The simplest approach reopens immediately on close. The danger: if the server is down, this hammers it in a tight loop.
function connect() {
const socket = new WebSocket(url);
socket.onclose = () => connect(); // too aggressive!
}Fixed Delay
Adding a constant delay is gentler but still sends a steady stream of attempts and can synchronize many clients (a thundering herd).
socket.onclose = () => {
setTimeout(connect, 3000);
};Exponential Backoff
Double the wait after each failed attempt: 1s, 2s, 4s, 8s… capped at a maximum. This spreads out retries and relieves a struggling server.
let attempt = 0;
function reconnect() {
const delay = Math.min(1000 * 2 ** attempt, 30000);
attempt++;
setTimeout(connect, delay);
}Adding Jitter
Randomize the delay slightly so thousands of clients do not reconnect at the same instant. Full jitter picks a random value between 0 and the computed cap.
function backoffWithJitter(attempt) {
const cap = Math.min(1000 * 2 ** attempt, 30000);
return Math.random() * cap;
}Resetting on Success
When onopen fires, reset the attempt counter so the next disconnect starts the backoff fresh.
socket.onopen = () => {
attempt = 0;
console.log("reconnected");
};A Complete Reconnecting Client
Combine the pieces: connect, reset on open, backoff on close.
let attempt = 0, socket;
function connect() {
socket = new WebSocket(url);
socket.onopen = () => { attempt = 0; };
socket.onclose = () => {
const delay = Math.min(1000 * 2 ** attempt++, 30000);
setTimeout(connect, delay + Math.random() * 1000);
};
}
connect();Respecting Online/Offline
Listen to the browser online/offline events. Pause reconnection while offline and trigger an immediate attempt when connectivity returns.
window.addEventListener("online", () => {
attempt = 0;
connect();
});
window.addEventListener("offline", () => {
if (socket) socket.close();
});Limiting Attempts
Optionally cap the number of retries and surface a permanent failure to the user instead of retrying forever.
const MAX = 10;
socket.onclose = () => {
if (attempt >= MAX) { showOfflineBanner(); return; }
setTimeout(connect, backoffWithJitter(attempt++));
};Resyncing State After Reconnect
A new connection has no server-side context. On reopen, re-subscribe to channels and request any messages missed while disconnected.
socket.onopen = () => {
attempt = 0;
socket.send(JSON.stringify({ type: "resubscribe", channels }));
socket.send(JSON.stringify({ type: "sync", since: lastSeenId }));
};Avoiding Duplicate Sockets
Guard against opening multiple sockets if reconnect logic fires twice. Track the current socket and ignore stale handlers.
function connect() {
if (socket && socket.readyState <= WebSocket.OPEN) return;
socket = new WebSocket(url);
}Quick Check
Test reconnection design.
Recap: Reconnection
You progressed from naive reconnect to exponential backoff with jitter, reset attempts on success, respected online/offline events, capped retries, resynced state after reconnecting, and avoided duplicate sockets. Your client is now resilient.
Frequently asked questions
Is the “Reconnection Strategies” lesson free?
Yes — the full text of “Reconnection Strategies” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Reconnection Strategies”?
Reconnect reliably after drops. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Reconnection Strategies” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Opening a WebSocket Connection
- Sending and Receiving Messages
- Connection Lifecycle and Errors
- Reconnection Strategies