[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"verticals":3,"article-websocket-reconnect-exponential-backoff":44,"search-suggestions":273,"path-membership-websocket-reconnect-exponential-backoff":314,"related-websocket-reconnect-exponential-backoff":315,"code:js:true:1l1yqc2":442,"code:js:true:o8chdd":443,"code:js:true:1qvbhx4":444,"code:js:true:77bicw":445,"comments-01a1fce0-d4f1-7184-bf57-f7ad669d6255":446},[4,20,32],{"id":5,"slug":6,"name":7,"tagline":8,"description":9,"accentFrom":10,"accentTo":11,"icon":12,"defaultLocale":13,"locales":14,"features":16,"position":19},"019fe637-3d33-714b-b57f-23e163ffca0c","dev","Web Development","Read it. Run it. Prove it.","A post a day on modern web development — most with an editable playground and a quiz that explains every answer. Free, no account needed.","violet-500","cyan-400","◇","en",[13,15],"fa",{"courses":17,"paths":17,"articles":17,"exams":18,"flashcards":18,"packages":17,"community":17,"certificates":17,"teams":17,"commerce":17},true,false,0,{"id":21,"slug":22,"name":23,"tagline":24,"description":25,"accentFrom":26,"accentTo":10,"icon":27,"defaultLocale":13,"locales":28,"features":30,"position":31},"019fe637-3dc2-754c-8657-0f175bfee7c6","lang","Languages","Learn a language the way you learn a codebase.","Grammar explained the way good documentation explains an API — one idea at a time, each with a quiz.","amber-400","⌘",[13,15,29],"es",{"courses":18,"paths":18,"articles":17,"exams":18,"flashcards":17,"packages":18,"community":17,"certificates":17,"teams":18,"commerce":18},2,{"id":33,"slug":34,"name":35,"tagline":36,"description":37,"accentFrom":38,"accentTo":39,"icon":40,"defaultLocale":13,"locales":41,"features":42,"position":43},"7b3c16f2-931d-410e-802e-e1fa4edab7de","soft","Soft Skills","The half of the job nobody wrote documentation for.","Weekly, on the parts of working life that decide more than your code does — first weeks, meetings, interviews, promotions, and the people around you. Written from what actually happens, and recorded as a podcast you can listen to on the walk.","emerald-400","teal-300","◉",[13],{"courses":18,"paths":18,"articles":17,"exams":18,"flashcards":18,"packages":18,"community":17,"certificates":18,"teams":18,"commerce":18},3,{"id":45,"slug":46,"title":47,"subtitle":48,"excerpt":49,"coverUrl":50,"locale":13,"readingMinutes":51,"publishedAt":52,"viewCount":53,"likeCount":19,"commentCount":19,"author":54,"vertical":59,"topic":60,"tags":63,"_count":75,"playground":77,"body":79,"bodyMd":256,"seo":257,"translationGroupId":260,"series":48,"podcastUrl":48,"verticalId":5,"thread":261,"assessments":263,"translations":269,"quiz":271},"01a1fce0-d4f1-7184-bf57-f7ad669d6255","websocket-reconnect-exponential-backoff","Your WebSocket Reconnects Fine. The Messages It Missed Never Do.",null,"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.","\u002Fmedia\u002Fcovers\u002Fwebsocket-reconnect-exponential-backoff.png",7,"2026-11-27T11:48:00.443Z",20,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},"019fe637-3c25-7088-9034-39c9f15dc3c8","Parsa Jiravand","parsa","Frontend engineer · building bestpractic",{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":61,"name":62},"javascript","JavaScript",[64,66,69,72],{"slug":61,"name":65,"color":48},"Javascript",{"slug":67,"name":68,"color":48},"webdev","Webdev",{"slug":70,"name":71,"color":48},"programming","Programming",{"slug":73,"name":74,"color":48},"frontend","Frontend",{"assessments":76},1,{"slug":46,"title":78},"WebSocket reconnect storm — interactive playground",{"blocks":80,"version":76},[81,85,88,91,95,98,104,107,110,113,116,120,123,129,132,135,138,141,144,147,150,153,156,159,162,165,168,174,178,181,184,188,191,194,198,201,204,207,210,213,216,220,223,226,229,232,238,241,244,247,250],{"id":82,"html":83,"type":84},"b1","\u003Cp>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.\u003C\u002Fp>","paragraph",{"id":86,"html":87,"type":84},"b2","\u003Cp>Two days later, someone on your team says &quot;wait, I never got the update you pushed at 2:14.&quot; You check the logs. The server sent it. The client was definitely connected by 2:16. The message is just gone.\u003C\u002Fp>",{"id":89,"html":90,"type":84},"b3","\u003Cp>It&#39;s gone because &quot;reconnected&quot; and &quot;caught up&quot; are two different claims, and the reconnect loop only ever promised the first one.\u003C\u002Fp>",{"id":92,"html":93,"text":93,"type":94,"level":31},"b4","The reconnect code almost everyone writes first","heading",{"id":96,"html":97,"type":84},"b5","\u003Cp>Here&#39;s the version that looks obviously correct:\u003C\u002Fp>",{"id":99,"code":100,"type":101,"language":102,"highlight":103},"b6","function connect(url) {\n  const ws = new WebSocket(url);\n  ws.onmessage = handleMessage;\n  ws.onclose = () => connect(url); \u002F\u002F reconnect — done, right?\n  return ws;\n}","code","js",[],{"id":105,"html":106,"type":84},"b7","\u003Cp>Run it against a flaky connection and it works. The socket drops, \u003Ccode>onclose\u003C\u002Fcode> fires, a new \u003Ccode>WebSocket\u003C\u002Fcode> opens, messages flow again. Watch the status indicator and you&#39;ll see exactly what you wanted: disconnect, brief gap, reconnect.\u003C\u002Fp>",{"id":108,"html":109,"type":84},"b8","\u003Cp>The test that never runs is the one where \u003Cem>the server\u003C\u002Fem> is the one that went away — a deploy, a restart, a load balancer hiccup that drops every open connection at once. Now every client&#39;s \u003Ccode>onclose\u003C\u002Fcode> fires within the same few hundred milliseconds, and every one of them calls \u003Ccode>connect()\u003C\u002Fcode> 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 \u003Ccode>fetch()\u003C\u002Fcode>.\u003C\u002Fp>",{"id":111,"html":112,"text":112,"type":94,"level":31},"b9","Backoff and jitter fix the storm",{"id":114,"html":115,"type":84},"b10","\u003Cp>The fix is the same one that works for HTTP retries: wait, and don&#39;t all wait the same amount.\u003C\u002Fp>",{"id":117,"code":118,"type":101,"language":102,"highlight":119},"b11","function createReconnectingSocket(url, onMessage, { baseDelay = 500, maxDelay = 15000 } = {}) {\n  let ws, attempt = 0, closedByClient = false;\n\n  function connect() {\n    ws = new WebSocket(url);\n    ws.onmessage = onMessage;\n    ws.onopen = () => { attempt = 0; };\n    ws.onclose = (event) => {\n      if (closedByClient || event.code === 1000) return; \u002F\u002F a deliberate, clean close — don't reconnect\n      const windowMs = Math.min(maxDelay, baseDelay * 2 ** attempt);\n      attempt++;\n      setTimeout(connect, Math.random() * windowMs); \u002F\u002F full jitter — spread attempts, don't synchronize them\n    };\n  }\n\n  connect();\n  return { close: () => { closedByClient = true; ws.close(1000, \"client closed\"); } };\n}",[],{"id":121,"html":122,"type":84},"b12","\u003Cp>Two details carry the fix:\u003C\u002Fp>",{"id":124,"type":125,"items":126,"ordered":18},"b13","list",[127,128],"\u003Cstrong>\u003Ccode>event.code === 1000\u003C\u002Fcode>\u003C\u002Fstrong> is a clean, intentional close — the server said goodbye on purpose, or you called \u003Ccode>.close()\u003C\u002Fcode> yourself. Reconnecting after that would fight your own shutdown logic. Everything else — including \u003Ccode>1006\u003C\u002Fcode>, the code the browser assigns when the connection just vanishes with no close frame at all — is the &quot;something broke, try again&quot; case.","\u003Cstrong>\u003Ccode>Math.random() * windowMs\u003C\u002Fcode>\u003C\u002Fstrong> is 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.",{"id":130,"html":131,"type":84},"b14","\u003C!-- playground:start -->",{"id":133,"html":134,"text":134,"type":94,"level":31},"b15","🎮 Try it yourself",{"id":136,"html":137,"type":84},"b16","\u003Cp>\u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fwebsocket-reconnect-exponential-backoff\u002Fplayground\">▶️ Open the interactive playground →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":139,"html":140,"type":84},"b17","\u003Cp>\u003Cem>Runs right in your browser — poke at it and watch the concept react live.\u003C\u002Fem>\u003C\u002Fp>",{"id":142,"html":143,"type":84},"b18","\u003C!-- playground:end -->",{"id":145,"html":146,"type":84},"b19","\u003Cp>Watch six simulated clients reconnect after a shared outage, with and without jitter, and the storm either does or doesn&#39;t happen in front of you.\u003C\u002Fp>",{"id":148,"html":149,"type":84},"b20","\u003Cp>Ship that, watch the status line go disconnected → reconnecting → connected smoothly, and it&#39;s tempting to call this done. The UI agrees with you. That&#39;s exactly the problem.\u003C\u002Fp>",{"id":151,"html":152,"text":152,"type":94,"level":31},"b21","Reconnecting is not resuming",{"id":154,"html":155,"type":84},"b22","\u003Cp>A \u003Ccode>WebSocket\u003C\u002Fcode> has no concept of &quot;pick up where we left off.&quot; When \u003Ccode>connect()\u003C\u002Fcode> runs again, it isn&#39;t un-pausing the old socket — it&#39;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 &quot;resend me everything since sequence 41.&quot; If your server tried to \u003Ccode>send()\u003C\u002Fcode> a message to a socket that was already closed, that call either no-ops or throws — either way, the message isn&#39;t queued anywhere waiting for you to come back.\u003C\u002Fp>",{"id":157,"html":158,"type":84},"b23","\u003Cp>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 \u003Cem>this\u003C\u002Fem> socket, because \u003Cem>this\u003C\u002Fem> socket didn&#39;t exist yet when it was sent. Nothing errored. Nothing logged a failure. The badge is green. The data just isn&#39;t there.\u003C\u002Fp>",{"id":160,"html":161,"type":84},"b24","\u003Cp>This is the gap every &quot;add exponential backoff and you&#39;re done&quot; tutorial skips, because backoff genuinely does solve the problem it&#39;s aimed at — the storm. It was never aimed at message loss, and a smooth-looking reconnect makes that easy to forget.\u003C\u002Fp>",{"id":163,"html":164,"text":164,"type":94,"level":31},"b25","The actual fix: let the client ask what it missed",{"id":166,"html":167,"type":84},"b26","\u003Cp>Recovering the gap needs a contract the WebSocket protocol doesn&#39;t give you for free — so you build a small one on top of it. The shape is always the same three pieces:\u003C\u002Fp>",{"id":169,"type":125,"items":170,"ordered":17},"b27",[171,172,173],"\u003Cstrong>Every message the server pushes carries an increasing sequence number.\u003C\u002Fstrong>","\u003Cstrong>The client remembers the last one it successfully processed.\u003C\u002Fstrong>","\u003Cstrong>On reconnect, the client asks for everything after that number, before it trusts the new connection as caught up.\u003C\u002Fstrong>",{"id":175,"code":176,"type":101,"language":102,"highlight":177},"b28","let lastSeq = 0;\n\nfunction handleMessage(event) {\n  const msg = JSON.parse(event.data);\n  if (msg.type === \"resume-complete\") return; \u002F\u002F see below\n  lastSeq = Math.max(lastSeq, msg.seq);\n  render(msg);\n}\n\nfunction onSocketOpen(ws) {\n  ws.send(JSON.stringify({ type: \"resume\", since: lastSeq }));\n}",[],{"id":179,"html":180,"type":84},"b29","\u003Cp>The server&#39;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 \u003Ccode>resume\u003C\u002Fcode> request can be answered by replaying the ones after \u003Ccode>since\u003C\u002Fcode>. That buffer can&#39;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 \u003Cem>not\u003C\u002Fem> to silently pretend nothing was missed. It&#39;s to tell the client its \u003Ccode>since\u003C\u002Fcode> 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.\u003C\u002Fp>",{"id":182,"html":183,"type":84},"b30","\u003Cp>That buffer-and-replay logic lives on the server and is genuinely more work than the client-side backoff loop. It&#39;s also the only part of this that actually answers &quot;did I get everything,&quot; which is the question the green badge was never answering in the first place.\u003C\u002Fp>",{"id":185,"html":186,"text":187,"type":94,"level":31},"b31","One more thing backoff doesn&#39;t catch: the socket that&#39;s dead but doesn&#39;t know it","One more thing backoff doesn't catch: the socket that's dead but doesn't know it",{"id":189,"html":190,"type":84},"b32","\u003Cp>There&#39;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&#39;s network stack silently drops a connection without telling the browser. \u003Ccode>ws.readyState\u003C\u002Fcode> can report \u003Ccode>OPEN\u003C\u002Fcode> for a socket that network hardware gave up on minutes ago — no \u003Ccode>close\u003C\u002Fcode> event fires, so none of the reconnect logic above ever triggers, because as far as your JavaScript knows, nothing happened.\u003C\u002Fp>",{"id":192,"html":193,"type":84},"b33","\u003Cp>The browser&#39;s \u003Ccode>WebSocket\u003C\u002Fcode> object gives you no way to send a protocol-level ping to check — there&#39;s no \u003Ccode>.ping()\u003C\u002Fcode> method in the standard; that exists on server-side libraries like Node&#39;s \u003Ccode>ws\u003C\u002Fcode> package, not in the browser API. So you build the check into the one channel you do control: your own messages.\u003C\u002Fp>",{"id":195,"code":196,"type":101,"language":102,"highlight":197},"b34","function startHeartbeat(ws, { interval = 20000, timeout = 5000 } = {}) {\n  let pongTimer;\n  const pingTimer = setInterval(() => {\n    if (ws.readyState !== WebSocket.OPEN) return;\n    ws.send(JSON.stringify({ type: \"ping\" }));\n    pongTimer = setTimeout(() => ws.close(), timeout); \u002F\u002F no pong in time — force the issue\n  }, interval);\n\n  return {\n    onPong: () => clearTimeout(pongTimer),\n    stop: () => { clearInterval(pingTimer); clearTimeout(pongTimer); },\n  };\n}",[],{"id":199,"html":200,"type":84},"b35","\u003Cp>The server replies \u003Ccode>{ type: &quot;pong&quot; }\u003C\u002Fcode> to every ping it gets. No reply within the timeout, and you call \u003Ccode>ws.close()\u003C\u002Fcode> 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&#39;t.\u003C\u002Fp>",{"id":202,"html":203,"type":84},"b36","\u003C!-- quiz:start -->",{"id":205,"html":206,"text":206,"type":94,"level":31},"b37","🧠 Test yourself",{"id":208,"html":209,"type":84},"b38","\u003Cp>Think it clicked? \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fwebsocket-reconnect-exponential-backoff\u002Fquiz\">Take the 8-question quiz →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":211,"html":212,"type":84},"b39","\u003Cp>\u003Cem>Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.\u003C\u002Fem>\u003C\u002Fp>",{"id":214,"html":215,"type":84},"b40","\u003C!-- quiz:end -->",{"id":217,"html":218,"text":219,"type":94,"level":31},"b41","What &quot;connected&quot; actually means now","What \"connected\" actually means now",{"id":221,"html":222,"type":84},"b42","\u003Cp>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&#39;s dead from pretending it&#39;s fine. None of them are hard individually — the entire reconnect-plus-resume contract is maybe 60 lines. The hard part is noticing that &quot;it reconnects&quot; was never the same claim as &quot;it didn&#39;t lose anything,&quot; right up until a teammate asks where their message went.\u003C\u002Fp>",{"id":224,"html":225,"type":84},"b43","\u003Cp>Does your reconnect logic actually ask the server what it missed — or does it just trust the green dot the same way everyone&#39;s first version did?\u003C\u002Fp>",{"id":227,"html":228,"type":84},"b44","\u003C!-- related:start -->",{"id":230,"html":231,"text":231,"type":94,"level":31},"b45","📚 Read next",{"id":233,"type":125,"items":234,"ordered":18},"b46",[235,236,237],"\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Ffetch-retry-exponential-backoff\">Stop Retrying Immediately. Exponential Backoff Fixes It.\u003C\u002Fa>","\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fcss-relative-color-syntax\">Stop Hardcoding Color Variants. Relative Color Syntax Does It.\u003C\u002Fa>","\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Frequestanimationframe-scroll-throttling\">You&#39;re Debouncing Scroll Wrong. requestAnimationFrame Fixes It.\u003C\u002Fa>",{"id":239,"html":240,"type":84},"b47","\u003C!-- related:end -->",{"id":242,"type":243},"b48","divider",{"id":245,"html":246,"type":84},"b49","\u003Cp>🚀 \u003Cstrong>Want more like this?\u003C\u002Fstrong> Every guide, playground, and quiz lives on \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">bestpractic.org\u003C\u002Fa>\u003C\u002Fstrong> — open it and \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">sign up free\u003C\u002Fa>\u003C\u002Fstrong> so the next one finds you.\u003C\u002Fp>",{"id":248,"html":249,"type":84},"b50","\u003Cp>\u003Cem>Thanks for reading! Let&#39;s stay connected:\u003C\u002Fem>\u003C\u002Fp>",{"id":251,"type":125,"items":252,"ordered":18},"b51",[253,254,255],"⭐ \u003Cstrong>GitHub\u003C\u002Fstrong> — follow me and star the projects: \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fparsajiravand\">github.com\u002Fparsajiravand\u003C\u002Fa>","💬 \u003Cstrong>Discord\u003C\u002Fstrong> — join the frontend best-practices community: \u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ\">discord.gg\u002Fd9KRhuAwQ\u003C\u002Fa>","📸 \u003Cstrong>Instagram\u003C\u002Fstrong> — frontend best practices, daily: \u003Ca href=\"https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F\">@bestpractice___\u003C\u002Fa>","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.\n\nTwo 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.\n\nIt's gone because \"reconnected\" and \"caught up\" are two different claims, and the reconnect loop only ever promised the first one.\n\n## The reconnect code almost everyone writes first\n\nHere's the version that looks obviously correct:\n\n```js\nfunction connect(url) {\n  const ws = new WebSocket(url);\n  ws.onmessage = handleMessage;\n  ws.onclose = () => connect(url); \u002F\u002F reconnect — done, right?\n  return ws;\n}\n```\n\nRun 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.\n\nThe 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()`.\n\n## Backoff and jitter fix the storm\n\nThe fix is the same one that works for HTTP retries: wait, and don't all wait the same amount.\n\n```js\nfunction createReconnectingSocket(url, onMessage, { baseDelay = 500, maxDelay = 15000 } = {}) {\n  let ws, attempt = 0, closedByClient = false;\n\n  function connect() {\n    ws = new WebSocket(url);\n    ws.onmessage = onMessage;\n    ws.onopen = () => { attempt = 0; };\n    ws.onclose = (event) => {\n      if (closedByClient || event.code === 1000) return; \u002F\u002F a deliberate, clean close — don't reconnect\n      const windowMs = Math.min(maxDelay, baseDelay * 2 ** attempt);\n      attempt++;\n      setTimeout(connect, Math.random() * windowMs); \u002F\u002F full jitter — spread attempts, don't synchronize them\n    };\n  }\n\n  connect();\n  return { close: () => { closedByClient = true; ws.close(1000, \"client closed\"); } };\n}\n```\n\nTwo details carry the fix:\n\n- **`event.code === 1000`** is 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 — including `1006`, the code the browser assigns when the connection just vanishes with no close frame at all — is the \"something broke, try again\" case.\n- **`Math.random() * windowMs`** is 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.\n\n\u003C!-- playground:start -->\n\n## 🎮 Try it yourself\n\n**[▶️ Open the interactive playground →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fwebsocket-reconnect-exponential-backoff\u002Fplayground)**\n\n_Runs right in your browser — poke at it and watch the concept react live._\n\n\u003C!-- playground:end -->\n\nWatch 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.\n\nShip 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.\n\n## Reconnecting is not resuming\n\nA `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.\n\nSo 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.\n\nThis 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.\n\n## The actual fix: let the client ask what it missed\n\nRecovering 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:\n\n1. **Every message the server pushes carries an increasing sequence number.**\n2. **The client remembers the last one it successfully processed.**\n3. **On reconnect, the client asks for everything after that number, before it trusts the new connection as caught up.**\n\n```js\nlet lastSeq = 0;\n\nfunction handleMessage(event) {\n  const msg = JSON.parse(event.data);\n  if (msg.type === \"resume-complete\") return; \u002F\u002F see below\n  lastSeq = Math.max(lastSeq, msg.seq);\n  render(msg);\n}\n\nfunction onSocketOpen(ws) {\n  ws.send(JSON.stringify({ type: \"resume\", since: lastSeq }));\n}\n```\n\nThe 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.\n\nThat 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.\n\n## One more thing backoff doesn't catch: the socket that's dead but doesn't know it\n\nThere'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.\n\nThe 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.\n\n```js\nfunction startHeartbeat(ws, { interval = 20000, timeout = 5000 } = {}) {\n  let pongTimer;\n  const pingTimer = setInterval(() => {\n    if (ws.readyState !== WebSocket.OPEN) return;\n    ws.send(JSON.stringify({ type: \"ping\" }));\n    pongTimer = setTimeout(() => ws.close(), timeout); \u002F\u002F no pong in time — force the issue\n  }, interval);\n\n  return {\n    onPong: () => clearTimeout(pongTimer),\n    stop: () => { clearInterval(pingTimer); clearTimeout(pongTimer); },\n  };\n}\n```\n\nThe 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.\n\n\u003C!-- quiz:start -->\n\n## 🧠 Test yourself\n\nThink it clicked? **[Take the 8-question quiz →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fwebsocket-reconnect-exponential-backoff\u002Fquiz)**\n\n_Instant feedback, a hint on every question, and an explanation for each answer — right or wrong._\n\n\u003C!-- quiz:end -->\n\n## What \"connected\" actually means now\n\nThree 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.\n\nDoes 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?\n\n\u003C!-- related:start -->\n\n## 📚 Read next\n\n- [Stop Retrying Immediately. Exponential Backoff Fixes It.](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Ffetch-retry-exponential-backoff)\n- [Stop Hardcoding Color Variants. Relative Color Syntax Does It.](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fcss-relative-color-syntax)\n- [You're Debouncing Scroll Wrong. requestAnimationFrame Fixes It.](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Frequestanimationframe-scroll-throttling)\n\n\u003C!-- related:end -->\n\n---\n\n🚀 **Want more like this?** Every guide, playground, and quiz lives on **[bestpractic.org](https:\u002F\u002Fbestpractic.org\u002F)** — open it and **[sign up free](https:\u002F\u002Fbestpractic.org\u002F)** so the next one finds you.\n\n*Thanks for reading! Let's stay connected:*\n\n- ⭐ **GitHub** — follow me and star the projects: [github.com\u002Fparsajiravand](https:\u002F\u002Fgithub.com\u002Fparsajiravand)\n- 💬 **Discord** — join the frontend best-practices community: [discord.gg\u002Fd9KRhuAwQ](https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ)\n- 📸 **Instagram** — frontend best practices, daily: [@bestpractice___](https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F)",{"title":47,"canonical":258,"description":259},"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fwebsocket-reconnect-exponential-backoff","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 goo","01a1fce0-d4f2-76e2-a520-1251f7699151",{"id":262,"locked":18},"01a1fce0-d510-742a-9939-0e585ba834b1",[264],{"id":265,"slug":46,"title":266,"_count":267},"01a1fce0-d535-702f-afa1-47fcf5ffd91d","WebSocket reconnection — storms, resumes, and dead sockets",{"questions":268},8,[270],{"locale":13,"slug":46},{"id":265,"slug":46,"title":266,"_count":272,"questionCount":268},{"questions":268},[274,276,278,280,284,288,292,296,298,302,306,310],{"slug":67,"name":68,"articles":275},195,{"slug":61,"name":65,"articles":277},156,{"slug":73,"name":74,"articles":279},103,{"slug":281,"name":282,"articles":283},"tutorial","Tutorial",85,{"slug":285,"name":286,"articles":287},"css","Css",56,{"slug":289,"name":290,"articles":291},"typescript","Typescript",36,{"slug":293,"name":294,"articles":295},"performance","Performance",33,{"slug":70,"name":71,"articles":297},26,{"slug":299,"name":300,"articles":301},"react","React",23,{"slug":303,"name":304,"articles":305},"node","Node",19,{"slug":307,"name":308,"articles":309},"browser","Browser",18,{"slug":311,"name":312,"articles":313},"nextjs","Nextjs",13,[],{"items":316,"meta":441},[317,336,355,367,386,405,423],{"id":318,"slug":319,"title":320,"subtitle":48,"excerpt":321,"coverUrl":322,"locale":13,"readingMinutes":323,"publishedAt":324,"viewCount":325,"likeCount":19,"commentCount":19,"author":326,"vertical":327,"topic":328,"tags":329,"_count":334,"playground":335,"hasQuiz":17,"hasPlayground":17},"01a1fce0-de91-712e-bc98-72dba2b10bf5","react-use-api-promises-context","`use()` Breaks the Rules of Hooks on Purpose. Here's the Catch.","React's `use()` reads a promise or context mid-render and skips the Rules of Hooks on purpose — but that same freedom hides a caching trap that resuspends your component forever if you miss it.","\u002Fmedia\u002Fcovers\u002Freact-use-api-promises-context.png",6,"2026-11-27T11:49:31.813Z",29,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":299,"name":300},[330,331,332,333],{"slug":299,"name":300,"color":48},{"slug":61,"name":65,"color":48},{"slug":67,"name":68,"color":48},{"slug":73,"name":74,"color":48},{"assessments":76},{"slug":319},{"id":337,"slug":338,"title":339,"subtitle":48,"excerpt":340,"coverUrl":341,"locale":13,"readingMinutes":323,"publishedAt":342,"viewCount":343,"likeCount":19,"commentCount":19,"author":344,"vertical":345,"topic":346,"tags":348,"_count":353,"playground":354,"hasQuiz":17,"hasPlayground":17},"01a1fce0-dac8-71e2-bd25-94b1cc5aa337","typescript-template-literal-types","Template Literal Types Explained: Catching Path Typos at Compile Time","A typo'd dot-path like \"theme.colros.primary\" compiles clean and fails silently at runtime — template literal types make TypeScript catch it before you ship.","\u002Fmedia\u002Fcovers\u002Ftypescript-template-literal-types.png","2026-11-27T11:49:01.332Z",30,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":289,"name":347},"TypeScript",[349,350,351,352],{"slug":289,"name":290,"color":48},{"slug":61,"name":65,"color":48},{"slug":67,"name":68,"color":48},{"slug":281,"name":282,"color":48},{"assessments":76},{"slug":338},{"id":45,"slug":46,"title":47,"subtitle":48,"excerpt":49,"coverUrl":50,"locale":13,"readingMinutes":51,"publishedAt":52,"viewCount":356,"likeCount":19,"commentCount":19,"author":357,"vertical":358,"topic":359,"tags":360,"_count":365,"playground":366,"hasQuiz":17,"hasPlayground":17},21,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":61,"name":62},[361,362,363,364],{"slug":61,"name":65,"color":48},{"slug":67,"name":68,"color":48},{"slug":70,"name":71,"color":48},{"slug":73,"name":74,"color":48},{"assessments":76},{"slug":46},{"id":368,"slug":369,"title":370,"subtitle":48,"excerpt":371,"coverUrl":372,"locale":13,"readingMinutes":373,"publishedAt":374,"viewCount":375,"likeCount":19,"commentCount":19,"author":376,"vertical":377,"topic":378,"tags":379,"_count":384,"playground":385,"hasQuiz":17,"hasPlayground":17},"01a1fce0-ce76-7424-b4da-6db21c69992c","nextjs-weekly-use-cache-remote-vs-private","Next.js 16 use cache: remote vs use cache: private","Next.js 16's use cache: remote shares a cache across instances; use cache: private never leaves one request. Which to pick, plus a copy-paste cheat sheet.","\u002Fmedia\u002Fcovers\u002Fnextjs-weekly-use-cache-remote-vs-private.png",16,"2026-11-27T11:47:29.944Z",28,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":311,"name":312},[380,381,382,383],{"slug":311,"name":312,"color":48},{"slug":67,"name":68,"color":48},{"slug":281,"name":282,"color":48},{"slug":61,"name":65,"color":48},{"assessments":76},{"slug":369},{"id":387,"slug":388,"title":389,"subtitle":48,"excerpt":390,"coverUrl":391,"locale":13,"readingMinutes":392,"publishedAt":393,"viewCount":394,"likeCount":19,"commentCount":19,"author":395,"vertical":396,"topic":397,"tags":398,"_count":403,"playground":404,"hasQuiz":17,"hasPlayground":17},"01a1fce0-c9cc-7004-b075-6c0ff7c7b600","weekly-typescript-type-narrowing","TypeScript Type Narrowing: The Complete Guide","Learn how TypeScript type narrowing really works — typeof, instanceof, discriminated unions, and custom type guards — plus a copy-paste cheat sheet.","\u002Fmedia\u002Fcovers\u002Fweekly-typescript-type-narrowing.png",15,"2026-11-27T11:46:59.418Z",27,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":289,"name":347},[399,400,401,402],{"slug":289,"name":290,"color":48},{"slug":61,"name":65,"color":48},{"slug":281,"name":282,"color":48},{"slug":67,"name":68,"color":48},{"assessments":76},{"slug":388},{"id":406,"slug":407,"title":408,"subtitle":48,"excerpt":409,"coverUrl":410,"locale":13,"readingMinutes":411,"publishedAt":412,"viewCount":373,"likeCount":19,"commentCount":19,"author":413,"vertical":414,"topic":415,"tags":416,"_count":421,"playground":422,"hasQuiz":17,"hasPlayground":17},"01a1fce0-bedd-7648-b22e-4b7afd1cce13","typescript-branded-types-nominal-typing","TypeScript Can't Tell userId From orderId. Branded Types Can.","TypeScript's structural typing treats userId and orderId as the same type if both are `string` — branded types make them incompatible at compile time.","\u002Fmedia\u002Fcovers\u002Ftypescript-branded-types-nominal-typing.png",5,"2026-11-27T11:45:58.086Z",{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":289,"name":347},[417,418,419,420],{"slug":289,"name":290,"color":48},{"slug":61,"name":65,"color":48},{"slug":67,"name":68,"color":48},{"slug":70,"name":71,"color":48},{"assessments":76},{"slug":407},{"id":424,"slug":425,"title":426,"subtitle":48,"excerpt":427,"coverUrl":428,"locale":13,"readingMinutes":411,"publishedAt":429,"viewCount":430,"likeCount":19,"commentCount":19,"author":431,"vertical":432,"topic":433,"tags":434,"_count":439,"playground":440,"hasQuiz":17,"hasPlayground":17},"01a1df1b-32db-7638-a86f-5cea99530919","typescript-noinfer-generic-widening","A Typo Widened My Generic Instead of Erroring. NoInfer\u003CT> Fixes It.","Why a typo'd default argument sailed through a generic function with zero errors — and how TypeScript's NoInfer\u003CT> stops it from silently widening the inferred type.","\u002Fmedia\u002Fcovers\u002Ftypescript-noinfer-generic-widening.png","2026-11-27T11:45:27.674Z",14,{"id":55,"name":56,"username":57,"avatarUrl":48,"headline":58},{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":289,"name":347},[435,436,437,438],{"slug":289,"name":290,"color":48},{"slug":61,"name":65,"color":48},{"slug":70,"name":71,"color":48},{"slug":67,"name":68,"color":48},{"assessments":76},{"slug":425},{"page":76,"perPage":51,"total":277,"totalPages":301},"\u003Cdiv class=\"shj shj-lang-js shj-multiline\" data-lang=\"js\">\u003Cdiv class=\"shj-scroll\">\u003Cdiv class=\"shj-numbers\">\u003Cdiv>1\u003C\u002Fdiv>\u003Cdiv>2\u003C\u002Fdiv>\u003Cdiv>3\u003C\u002Fdiv>\u003Cdiv>4\u003C\u002Fdiv>\u003Cdiv>5\u003C\u002Fdiv>\u003Cdiv>6\u003C\u002Fdiv>\u003C\u002Fdiv>\u003Cdiv class=\"shj-code\">\u003Cspan class=\"shj-kwd\">function\u003C\u002Fspan> \u003Cspan class=\"shj-func\">connect\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>url\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n  \u003Cspan class=\"shj-kwd\">const\u003C\u002Fspan> ws \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">new\u003C\u002Fspan> \u003Cspan class=\"shj-class\">WebSocket\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>url\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n  ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>onmessage \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> handleMessage;\n  ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">onclose\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-func\">connect\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>url\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>; \u003Cspan class=\"shj-cmnt\">\u002F\u002F reconnect — done, right?\n\u003C\u002Fspan>  \u003Cspan class=\"shj-kwd\">return\u003C\u002Fspan> ws;\n\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003C\u002Fdiv>\u003C\u002Fdiv>\u003C\u002Fdiv>","\u003Cdiv class=\"shj shj-lang-js shj-multiline\" data-lang=\"js\">\u003Cdiv class=\"shj-scroll\">\u003Cdiv class=\"shj-numbers\">\u003Cdiv>1\u003C\u002Fdiv>\u003Cdiv>2\u003C\u002Fdiv>\u003Cdiv>3\u003C\u002Fdiv>\u003Cdiv>4\u003C\u002Fdiv>\u003Cdiv>5\u003C\u002Fdiv>\u003Cdiv>6\u003C\u002Fdiv>\u003Cdiv>7\u003C\u002Fdiv>\u003Cdiv>8\u003C\u002Fdiv>\u003Cdiv>9\u003C\u002Fdiv>\u003Cdiv>10\u003C\u002Fdiv>\u003Cdiv>11\u003C\u002Fdiv>\u003Cdiv>12\u003C\u002Fdiv>\u003Cdiv>13\u003C\u002Fdiv>\u003Cdiv>14\u003C\u002Fdiv>\u003Cdiv>15\u003C\u002Fdiv>\u003Cdiv>16\u003C\u002Fdiv>\u003Cdiv>17\u003C\u002Fdiv>\u003Cdiv>18\u003C\u002Fdiv>\u003C\u002Fdiv>\u003Cdiv class=\"shj-code\">\u003Cspan class=\"shj-kwd\">function\u003C\u002Fspan> \u003Cspan class=\"shj-func\">createReconnectingSocket\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>url\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> onMessage\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> baseDelay \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">500\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> maxDelay \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">15000\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n  \u003Cspan class=\"shj-kwd\">let\u003C\u002Fspan> ws\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> attempt \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">0\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> closedByClient \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bool\">false\u003C\u002Fspan>;\n\n  \u003Cspan class=\"shj-kwd\">function\u003C\u002Fspan> \u003Cspan class=\"shj-func\">connect\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n    ws \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">new\u003C\u002Fspan> \u003Cspan class=\"shj-class\">WebSocket\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>url\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n    ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>onmessage \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> onMessage;\n    ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">onopen\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> attempt \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">0\u003C\u002Fspan>; \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>;\n    ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">onclose\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>event\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n      \u003Cspan class=\"shj-kwd\">if\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>closedByClient \u003Cspan class=\"shj-oper\">||\u003C\u002Fspan> event\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>code \u003Cspan class=\"shj-oper\">===\u003C\u002Fspan> \u003Cspan class=\"shj-num\">1000\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">return\u003C\u002Fspan>; \u003Cspan class=\"shj-cmnt\">\u002F\u002F a deliberate, clean close — don't reconnect\n\u003C\u002Fspan>      \u003Cspan class=\"shj-kwd\">const\u003C\u002Fspan> windowMs \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-class\">Math\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">min\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>maxDelay\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> baseDelay \u003Cspan class=\"shj-oper\">*\u003C\u002Fspan> \u003Cspan class=\"shj-num\">2\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">**\u003C\u002Fspan> attempt\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n      attempt\u003Cspan class=\"shj-oper\">++\u003C\u002Fspan>;\n      \u003Cspan class=\"shj-func\">setTimeout\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>connect\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> \u003Cspan class=\"shj-class\">Math\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">random\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">*\u003C\u002Fspan> windowMs\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>; \u003Cspan class=\"shj-cmnt\">\u002F\u002F full jitter — spread attempts, don't synchronize them\n\u003C\u002Fspan>    \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>;\n  \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\n\n  \u003Cspan class=\"shj-func\">connect\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n  \u003Cspan class=\"shj-kwd\">return\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> close\u003Cspan class=\"shj-oper\">:\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> closedByClient \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bool\">true\u003C\u002Fspan>; ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">close\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-num\">1000\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> \u003Cspan class=\"shj-str\">\"client closed\"\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>; \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>;\n\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003C\u002Fdiv>\u003C\u002Fdiv>\u003C\u002Fdiv>","\u003Cdiv class=\"shj shj-lang-js shj-multiline\" data-lang=\"js\">\u003Cdiv class=\"shj-scroll\">\u003Cdiv class=\"shj-numbers\">\u003Cdiv>1\u003C\u002Fdiv>\u003Cdiv>2\u003C\u002Fdiv>\u003Cdiv>3\u003C\u002Fdiv>\u003Cdiv>4\u003C\u002Fdiv>\u003Cdiv>5\u003C\u002Fdiv>\u003Cdiv>6\u003C\u002Fdiv>\u003Cdiv>7\u003C\u002Fdiv>\u003Cdiv>8\u003C\u002Fdiv>\u003Cdiv>9\u003C\u002Fdiv>\u003Cdiv>10\u003C\u002Fdiv>\u003Cdiv>11\u003C\u002Fdiv>\u003Cdiv>12\u003C\u002Fdiv>\u003C\u002Fdiv>\u003Cdiv class=\"shj-code\">\u003Cspan class=\"shj-kwd\">let\u003C\u002Fspan> lastSeq \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">0\u003C\u002Fspan>;\n\n\u003Cspan class=\"shj-kwd\">function\u003C\u002Fspan> \u003Cspan class=\"shj-func\">handleMessage\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>event\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n  \u003Cspan class=\"shj-kwd\">const\u003C\u002Fspan> msg \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">JSON\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">parse\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>event\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>data\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n  \u003Cspan class=\"shj-kwd\">if\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>msg\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>type \u003Cspan class=\"shj-oper\">===\u003C\u002Fspan> \u003Cspan class=\"shj-str\">\"resume-complete\"\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">return\u003C\u002Fspan>; \u003Cspan class=\"shj-cmnt\">\u002F\u002F see below\n\u003C\u002Fspan>  lastSeq \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-class\">Math\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">max\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>lastSeq\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> msg\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>seq\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n  \u003Cspan class=\"shj-func\">render\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>msg\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\n\n\u003Cspan class=\"shj-kwd\">function\u003C\u002Fspan> \u003Cspan class=\"shj-func\">onSocketOpen\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>ws\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n  ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">send\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-num\">JSON\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">stringify\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> type\u003Cspan class=\"shj-oper\">:\u003C\u002Fspan> \u003Cspan class=\"shj-str\">\"resume\"\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> since\u003Cspan class=\"shj-oper\">:\u003C\u002Fspan> lastSeq \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003C\u002Fdiv>\u003C\u002Fdiv>\u003C\u002Fdiv>","\u003Cdiv class=\"shj shj-lang-js shj-multiline\" data-lang=\"js\">\u003Cdiv class=\"shj-scroll\">\u003Cdiv class=\"shj-numbers\">\u003Cdiv>1\u003C\u002Fdiv>\u003Cdiv>2\u003C\u002Fdiv>\u003Cdiv>3\u003C\u002Fdiv>\u003Cdiv>4\u003C\u002Fdiv>\u003Cdiv>5\u003C\u002Fdiv>\u003Cdiv>6\u003C\u002Fdiv>\u003Cdiv>7\u003C\u002Fdiv>\u003Cdiv>8\u003C\u002Fdiv>\u003Cdiv>9\u003C\u002Fdiv>\u003Cdiv>10\u003C\u002Fdiv>\u003Cdiv>11\u003C\u002Fdiv>\u003Cdiv>12\u003C\u002Fdiv>\u003Cdiv>13\u003C\u002Fdiv>\u003C\u002Fdiv>\u003Cdiv class=\"shj-code\">\u003Cspan class=\"shj-kwd\">function\u003C\u002Fspan> \u003Cspan class=\"shj-func\">startHeartbeat\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>ws\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> interval \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">20000\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> timeout \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-num\">5000\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan> \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n  \u003Cspan class=\"shj-kwd\">let\u003C\u002Fspan> pongTimer;\n  \u003Cspan class=\"shj-kwd\">const\u003C\u002Fspan> pingTimer \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-func\">setInterval\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n    \u003Cspan class=\"shj-kwd\">if\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>readyState \u003Cspan class=\"shj-oper\">!==\u003C\u002Fspan> \u003Cspan class=\"shj-class\">WebSocket\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-num\">OPEN\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">return\u003C\u002Fspan>;\n    ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">send\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-num\">JSON\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">stringify\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> type\u003Cspan class=\"shj-oper\">:\u003C\u002Fspan> \u003Cspan class=\"shj-str\">\"ping\"\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n    pongTimer \u003Cspan class=\"shj-oper\">=\u003C\u002Fspan> \u003Cspan class=\"shj-func\">setTimeout\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> ws\u003Cspan class=\"shj-oper\">.\u003C\u002Fspan>\u003Cspan class=\"shj-func\">close\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> timeout\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>; \u003Cspan class=\"shj-cmnt\">\u002F\u002F no pong in time — force the issue\n\u003C\u002Fspan>  \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan> interval\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>;\n\n  \u003Cspan class=\"shj-kwd\">return\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan>\n    onPong\u003Cspan class=\"shj-oper\">:\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-func\">clearTimeout\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>pongTimer\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan>\n    stop\u003Cspan class=\"shj-oper\">:\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan> \u003Cspan class=\"shj-kwd\">=&gt;\u003C\u002Fspan> \u003Cspan class=\"shj-bracket\">{\u003C\u002Fspan> \u003Cspan class=\"shj-func\">clearInterval\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>pingTimer\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>; \u003Cspan class=\"shj-func\">clearTimeout\u003C\u002Fspan>\u003Cspan class=\"shj-bracket\">(\u003C\u002Fspan>pongTimer\u003Cspan class=\"shj-bracket\">)\u003C\u002Fspan>; \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003Cspan class=\"shj-oper\">,\u003C\u002Fspan>\n  \u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>;\n\u003Cspan class=\"shj-bracket\">}\u003C\u002Fspan>\u003C\u002Fdiv>\u003C\u002Fdiv>\u003C\u002Fdiv>",{"locked":18,"total":19,"comments":447},[]]