Your WebSocket Reconnects Fine. The Messages It Missed Never Do.
Exponential backoff fixes the reconnect storm. It does nothing for the messages your server sent while the socket was down — those need an app-level replay, or they're gone for good.

The badge in the corner goes from green to red to green again. Three seconds, tops — long enough to walk through a subway turnstile, short enough that nobody files a bug. Your reconnect logic did exactly its job: it noticed the drop, waited, and opened a fresh connection before the user even looked up.
Two days later, someone on your team says "wait, I never got the update you pushed at 2:14." You check the logs. The server sent it. The client was definitely connected by 2:16. The message is just gone.
It's gone because "reconnected" and "caught up" are two different claims, and the reconnect loop only ever promised the first one.
Here's the version that looks obviously correct:
Run it against a flaky connection and it works. The socket drops, onclose fires, a new WebSocket opens, messages flow again. Watch the status indicator and you'll see exactly what you wanted: disconnect, brief gap, reconnect.
The test that never runs is the one where the server is the one that went away — a deploy, a restart, a load balancer hiccup that drops every open connection at once. Now every client's onclose fires within the same few hundred milliseconds, and every one of them calls connect() immediately. The server comes back up to a wall of simultaneous reconnection attempts from everyone it was serving a second ago — the same retry-storm problem that shows up in any naive retry loop, just wearing a WebSocket instead of a fetch().
The fix is the same one that works for HTTP retries: wait, and don't all wait the same amount.
Two details carry the fix:
event.code === 1000is a clean, intentional close — the server said goodbye on purpose, or you called.close()yourself. Reconnecting after that would fight your own shutdown logic. Everything else — including1006, the code the browser assigns when the connection just vanishes with no close frame at all — is the "something broke, try again" case.Math.random() * windowMsis full jitter: instead of every client waiting exactly 500ms, then exactly 1000ms, then exactly 2000ms (which just re-synchronizes everyone into new, smaller storms), each client picks a random point inside the growing window. The server sees a trickle of reconnects instead of a wave.
Runs right in your browser — poke at it and watch the concept react live.
Watch six simulated clients reconnect after a shared outage, with and without jitter, and the storm either does or doesn't happen in front of you.
Ship that, watch the status line go disconnected → reconnecting → connected smoothly, and it's tempting to call this done. The UI agrees with you. That's exactly the problem.
A WebSocket has no concept of "pick up where we left off." When connect() runs again, it isn't un-pausing the old socket — it's opening a completely new one, with its own handshake, that the server has never seen before. There is no frame in the spec for "resend me everything since sequence 41." If your server tried to send() a message to a socket that was already closed, that call either no-ops or throws — either way, the message isn't queued anywhere waiting for you to come back.
So picture the actual timeline from the hook above: connection drops at 2:14:02, your server pushes an update at 2:14:05 to a socket that no longer exists on the other end, your client reconnects at 2:14:06. The new connection is healthy. The update from 2:14:05 was never sent to this socket, because this socket didn't exist yet when it was sent. Nothing errored. Nothing logged a failure. The badge is green. The data just isn't there.
This is the gap every "add exponential backoff and you're done" tutorial skips, because backoff genuinely does solve the problem it's aimed at — the storm. It was never aimed at message loss, and a smooth-looking reconnect makes that easy to forget.
Recovering the gap needs a contract the WebSocket protocol doesn't give you for free — so you build a small one on top of it. The shape is always the same three pieces:
- Every message the server pushes carries an increasing sequence number.
- The client remembers the last one it successfully processed.
- On reconnect, the client asks for everything after that number, before it trusts the new connection as caught up.
The server's half of the deal is the part that actually matters: it needs to keep a short rolling buffer per connection (or per user) of recently sent messages, so a resume request can be answered by replaying the ones after since. That buffer can't be infinite — if a client comes back after being offline for an hour and the server only kept five minutes of history, the honest answer is not to silently pretend nothing was missed. It's to tell the client its since is too old and trigger a full resync (a normal REST fetch of current state), the same way a CDN tells you a cache entry expired instead of serving stale data as if it were fresh.
That buffer-and-replay logic lives on the server and is genuinely more work than the client-side backoff loop. It's also the only part of this that actually answers "did I get everything," which is the question the green badge was never answering in the first place.
There's a second failure mode worth closing out, because it breaks the resume logic above in a sneaky way: a laptop goes to sleep, or a phone's network stack silently drops a connection without telling the browser. ws.readyState can report OPEN for a socket that network hardware gave up on minutes ago — no close event fires, so none of the reconnect logic above ever triggers, because as far as your JavaScript knows, nothing happened.
The browser's WebSocket object gives you no way to send a protocol-level ping to check — there's no .ping() method in the standard; that exists on server-side libraries like Node's ws package, not in the browser API. So you build the check into the one channel you do control: your own messages.
The server replies { type: "pong" } to every ping it gets. No reply within the timeout, and you call ws.close() yourself — which hands the problem back to the reconnect loop you already wrote, instead of leaving the app sitting on a socket that looks fine and isn't.
Think it clicked? Take the 8-question quiz →
Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.
Three pieces, each fixing a different lie the green badge was telling: backoff-with-jitter stops reconnects from synchronizing into a storm, a sequence number and a resume handshake stop a clean reconnect from quietly hiding data loss, and an app-level heartbeat stops a socket that's dead from pretending it's fine. None of them are hard individually — the entire reconnect-plus-resume contract is maybe 60 lines. The hard part is noticing that "it reconnects" was never the same claim as "it didn't lose anything," right up until a teammate asks where their message went.
Does your reconnect logic actually ask the server what it missed — or does it just trust the green dot the same way everyone's first version did?
- Stop Retrying Immediately. Exponential Backoff Fixes It.
- Stop Hardcoding Color Variants. Relative Color Syntax Does It.
- You're Debouncing Scroll Wrong. requestAnimationFrame Fixes It.
🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.
Thanks for reading! Let's stay connected:
- ⭐ GitHub — follow me and star the projects: github.com/parsajiravand
- 💬 Discord — join the frontend best-practices community: discord.gg/d9KRhuAwQ
- 📸 Instagram — frontend best practices, daily: @bestpractice___
Keep reading
One post a day, in your inbox
Each one with a runnable playground and a quiz. No pitch, no digest, unsubscribe in one click.
0 comments
Sign in to join the discussion, like comments, and save articles for later.