How do you handle reconnection and connection drops in WebSockets?
Learn to handle WebSocket drops with auto-reconnect, exponential backoff, jitter, resubscription, and replaying missed messages for reliable real-time apps.
Expected Interview Answer
You handle WebSocket drops by detecting the close event, then reconnecting automatically with exponential backoff and jitter, and re-establishing state (re-authenticating, resubscribing to channels, and replaying missed messages) once the socket is back.
WebSocket connections can drop from network changes, timeouts, proxies, or server restarts, and the browser fires a close or error event. A robust client wraps the socket in a manager that retries on a growing delay to avoid hammering the server, caps the maximum delay, and adds random jitter so many clients don't reconnect at the same instant. After reconnecting you must restore session context and use message IDs or a last-seen cursor so the server can resend anything missed while offline. Many teams rely on Socket.IO or reconnecting-websocket wrappers that implement this.
- Keeps real-time features working through flaky networks
- Avoids reconnect storms with backoff and jitter
- Restores subscriptions and auth after a drop
- Prevents data loss by replaying missed messages
- Improves perceived reliability on mobile and unstable Wi-Fi
AI Mentor Explanation
A dropped connection is like a rain break stopping play mid-over. You don't abandon the match — you wait, and rather than restarting instantly you give the pitch time to recover, checking again after longer and longer intervals. When play resumes, the scoreboard is restored to exactly where it stopped, and the over continues from the same ball so nothing is lost.
Step-by-Step Explanation
Step 1
Detect the drop
Listen for the socket's close and error events and any missed heartbeats.
Step 2
Retry with backoff
Reconnect after a delay that grows exponentially, capped at a maximum, with random jitter.
Step 3
Re-authenticate
On reopen, resend the auth token or re-run the handshake to restore the session.
Step 4
Resubscribe
Rejoin rooms, channels, and topics the client was subscribed to before the drop.
Step 5
Replay missed data
Send the last-seen message ID or cursor so the server can resend anything missed.
What Interviewer Expects
- Awareness of the close/error events and why drops happen
- Exponential backoff with jitter and a max delay
- Re-authentication and resubscription after reconnect
- A strategy for replaying missed messages (IDs or cursors)
- Knowledge of libraries like Socket.IO or reconnecting-websocket
Common Mistakes
- Reconnecting instantly in a tight loop, causing a reconnect storm
- Using a fixed retry interval with no jitter
- Forgetting to re-authenticate or resubscribe after reconnecting
- Assuming no messages are lost during the outage
- Not capping the maximum backoff, leading to unbounded delays
Best Answer (HR Friendly)
“Real-time connections sometimes drop because of bad networks or server restarts. We detect the drop and quietly reconnect, waiting a little longer between each try so we don't overload the server, then restore the user's session and catch up on anything they missed while offline.”
Code Example
function connect(url, onMessage) {
let attempt = 0
let ws
function open() {
ws = new WebSocket(url)
ws.onopen = () => {
attempt = 0
ws.send(JSON.stringify({ type: 'auth', token: getToken() }))
ws.send(JSON.stringify({ type: 'resume', lastId: getLastSeenId() }))
}
ws.onmessage = (e) => onMessage(JSON.parse(e.data))
ws.onclose = () => {
const base = Math.min(30000, 1000 * 2 ** attempt)
const jitter = Math.random() * 1000
attempt += 1
setTimeout(open, base + jitter)
}
ws.onerror = () => ws.close()
}
open()
return () => ws && ws.close()
}Follow-up Questions
- Why add jitter to the backoff delay?
- How do you know which messages a client missed while offline?
- What is the difference between a clean close and an abrupt drop?
- How would heartbeats help detect a half-open connection?
- When should you stop retrying and surface an error to the user?
MCQ Practice
1. Why use exponential backoff with jitter when reconnecting?
Growing delays plus randomness spread reconnection attempts out, preventing a thundering-herd reconnect storm after an outage.
2. After reconnecting, what must a robust client typically do?
A new socket has no prior state, so the client must restore auth and rejoin its rooms or topics.
3. How can a client recover messages missed during a drop?
Tracking a sequence ID or cursor lets the server replay only the events the client missed while offline.
Flash Cards
How is a WebSocket drop detected? — Via the close and error events, and by noticing missed heartbeats on an idle connection.
What reconnect strategy avoids server overload? — Exponential backoff with a capped max delay plus random jitter.
What must happen after a successful reconnect? — Re-authenticate, resubscribe to rooms/channels, and replay missed messages.
How are missed messages recovered? — The client sends a last-seen message ID or cursor and the server resends anything after it.
Continue Learning
Related Interview Questions
What are heartbeats (ping/pong) in WebSockets and why are they needed?
medium
Why do WebSockets break when a phone switches networks or the app is backgrounded, and how do you handle it?
medium
How do you test a WebSocket application?
medium
How do you implement WebSocket reconnection with exponential backoff and jitter without creating a thundering herd?
medium