Skip to content

SPA Deploy Resilience — Strategy for Stale Bundles at Scale

Version: 1.1 Last Updated: 2026-05-29 15:58:00 Status: Layers 1, 2, 5 implemented 2026-05-29 (Layer 5 added same day after a real user incident — see §3.5). Layer 3 (polite update toast) and Layer 4 (preserve old chunks) sequenced for later sprints. Trigger: Production incident PS0APLI3 — user saw “something went wrong” after saving a prescription, because their browser was running an index.html from a previous deploy that referenced lazy chunks the new container no longer served.


Should we be putting in as part of our implementation process some sort of mandatory browser refresh so it’s not stale? What if I’d made this change and there were 100,000 users?

Short answer: yes, and the “mandatory refresh” must happen automatically, not via a banner that asks the user. A 100k-user deploy is not the time to depend on user attention.

The full solution is layered. Each layer covers a different failure mode. You want all of them eventually — but they have very different costs and we should ship them in order.


LayerWhat it doesStatus todayCost
1. Recovery — auto-reload on chunk fetch failureCatches the user mid-failure and reloads them onto the new build before they ever see the error.Done 2026-05-29Trivial
2. Invalidation — every deploy produces a byte-different sw.jsForces the service worker to reinstall + post SW_UPDATED to every open tab, which then triggers an already-existing reload handler.Done 2026-05-29Trivial
3. Visibility — polite in-app “Update available — refresh” toastGives the user agency, surfaces deploys before they ever hit a stale-chunk error.Not startedSmall (1–2 days)
4. Preservation — keep old chunks served for N hours after deployPrevents the 404 entirely for users mid-form. Belt-and-braces.Not startedMedium (changes the deploy pipeline)
5. Proactive checking — SPA polls for new SWs every 5 min + on tab focusCatches users who never navigate (single-page sessions — e.g. carer sitting on a dispense-schedule view for hours).Done 2026-05-29Trivial

Layers 1 + 2 catch users at the moment a stale chunk fails. Layer 5 catches users before a chunk fails by proactively polling the SW for updates so they pick up new deploys within ~5 min of the deploy landing, without needing to navigate or refresh. Layer 3 (polite toast) and Layer 4 (asset preservation) remain TODO as polish.


frontend/src/lib/lazyWithReload.ts is a drop-in replacement for React.lazy() that:

  1. Catches the four error wordings browsers use for “I asked for a JS module and got a 404 or wrong MIME type”:
    • Loading chunk N failed (Webpack name, still emitted by some Vite plugins)
    • Failed to fetch dynamically imported module (Vite/Rollup default)
    • error loading dynamically imported module
    • ChunkLoadError
    • Importing a module script failed
    • 'text/html' is not a valid JavaScript MIME type (Safari, when the 404 returns HTML)
  2. Calls window.location.reload() exactly once.
  3. Uses sessionStorage['lyncareos.lazyReload.attempted'] as a one-shot sentinel — so a chunk that is genuinely missing for some other reason (not a stale-deploy 404) cannot cause an infinite reload loop. On the second hit we let the original error bubble to the ErrorBoundary so the user still gets a “Try again” surface.

All 22 lazy() callsites in frontend/src/App.tsx were converted. Unit tests cover the error-classification matrix and the one-shot guard (src/lib/lazyWithReload.test.ts — 14 tests).

3.2 Layer 2 — Build-ID-stamped service worker

Section titled “3.2 Layer 2 — Build-ID-stamped service worker”

frontend/public/sw.js used to declare const CACHE_NAME = 'lyncareos-v8-offline-sync'. That string only changed if a developer remembered to bump it. A “regular” deploy that only touched pages/Foo.tsx left sw.js byte-identical, so the browser never reinstalled it, never activated a new one, never posted SW_UPDATED, and never triggered the existing controllerchange → reload handler in index.html.

The fix is two files:

  • sw.js now declares const CACHE_NAME = 'lyncareos-__BUILD_ID__'.
  • frontend/scripts/inject-sw-version.mjs runs as part of npm run build and substitutes __BUILD_ID__ with the Vite main-bundle hash (e.g. lyncareos-BwH_j4HM).

Because the main-bundle hash is content-derived, any change to any module in the import graph produces a different sw.js. The browser hashes the served file, sees the difference, and installs the new SW. Existing activate handler fires SW_UPDATED → existing bootstrap script in index.html reloads the tab → user lands on the new build.

3.3 Layer 2.5 — sw.js no-cache at origin and at the edge

Section titled “3.3 Layer 2.5 — sw.js no-cache at origin and at the edge”

backend/main.py was updated to send Cache-Control: no-cache, no-store, must-revalidate for sw.js (matching the existing index.html treatment). Origin alone is not enough on Cloudflare — by default Cloudflare’s “Cache Everything” behaviour for static JS files applies its own 4-hour max-age and ignores origin’s no-cache. We therefore added a Cloudflare Cache Rule:

  • Ruleset: lyncareos-sw-bypass (phase http_request_cache_settings)
  • Rule ID: e9c9910a1df640959e2ae05ca6008ea1
  • Expression: (http.request.uri.path eq "/sw.js")
  • Action: set_cache_settings with cache: false, browser_ttl: respect_origin

Verification command (must show Cache-Control: no-cache, no-store, must-revalidate and cf-cache-status: DYNAMIC):

Terminal window
curl -s -D - -o /dev/null https://app.lyncareos.com/sw.js | grep -iE 'cache-control|cf-cache-status'

If you ever migrate Cloudflare zones, recreate this Cache Rule via the API (the create request body is in this plan’s git history) or it will silently regress.

3.5 Layer 5 — Proactive SW update polling (added evening 2026-05-29 after user incident)

Section titled “3.5 Layer 5 — Proactive SW update polling (added evening 2026-05-29 after user incident)”

Why this was retro-fitted the same day: the initial layers 1 + 2 ship recovered users from a stale chunk only when something failed. A real-world session showed the alternative: a carer sat on /medication-schedule for hours without navigating, kept rendering the (now buggy) old UI successfully, and the dispense button silently went missing because the old bundle pre-dated a fix that had landed in a later deploy. Nothing ever failed — so layer 1 never fired. The page never re-fetched — so the SW never noticed there was a new version available. The browser’s default 24-hour SW poll was the only safety net, and a clinical app cannot wait a day.

The fix is in frontend/index.html’s production SW bootstrap:

  • setInterval(reg.update, 5 * 60 * 1000) — every 5 minutes the existing ServiceWorkerRegistration is told to check the network for a newer sw.js. If layer 2 has shipped a new build, the new SW is downloaded, installed, claims the tab (self.skipWaiting() + clients.claim() already in sw.js), and the existing SW_UPDATED postMessage fires the reload chain.
  • document.addEventListener('visibilitychange', …) — when the tab returns from hidden state (user switches back from another tab/app), trigger reg.update() immediately before they touch the UI. This catches the common “tab open all morning, look at it in the afternoon” pattern.
  • safeReload() — both the SW_UPDATED and controllerchange handlers now route through a helper that defers the reload while a form field (INPUT, TEXTAREA, SELECT, [contenteditable]) is focused. If the user is typing when an update lands, the reload is held back and retried every 30 seconds until focus moves off the input. This prevents the periodic poll from blowing away a half-typed dose log mid-keystroke.

Cost: ~40 lines of inline JavaScript in index.html, no runtime dependencies, no backend changes. The 5-min reg.update() poll is a single conditional HTTP request to /sw.js (small, ETag-validated by the browser), so the bandwidth cost is negligible.

3.6 Already in place (verified, not changed)

Section titled “3.6 Already in place (verified, not changed)”
  • backend/main.py already serves index.html with Cache-Control: no-cache, no-store, must-revalidate — Cloudflare passes that through (cf-cache-status: DYNAMIC).
  • sw.js already does network-first for navigation requests with caches.put() only as a fallback. Verified intact.
  • index.html already listens for SW_UPDATED and controllerchange and reloads once.

4. The end-to-end recovery flow after layers 1 + 2

Section titled “4. The end-to-end recovery flow after layers 1 + 2”
Cloudflare / VPSService WorkerBrowser"User tab loaded pre-deploy"Cloudflare / VPSService WorkerBrowser"User tab loaded pre-deploy"New deploy lands.\nOld chunks deleted.\nsw.js bytes changed.navigate('/scripts/123') (lazy route)1"GET /assets/ScriptDetail-OLDHASH.js"24043import() rejects (ChunkLoadError)4"lazyWithReload catches, sets sentinel,\ncalls location.reload()"5full document reload6"GET / (no-store on index.html)"7"fresh index.html with NEWHASH references"8"GET /sw.js"9"sw.js with new CACHE_NAME=lyncareos-NEWHASH"10install + activate new SW11postMessage SW_UPDATED12(already reloaded - bootstrap no-ops)13"GET /assets/ScriptDetail-NEWHASH.js"1420015user lands on the requested page16

End-state for an open tab during a deploy:

  1. They navigate, hit a 404, get auto-reloaded (worst case: ~400 ms blank).
  2. They sit idle, then navigate later — sw.js was already swapped on a prior network call, SW posted SW_UPDATED, bootstrap reloaded them silently.

5. What we should add later (layers 3–5)

Section titled “5. What we should add later (layers 3–5)”

Layer 3 — “Update available” toast (polite)

Section titled “Layer 3 — “Update available” toast (polite)”

The safeReload() helper added on 2026-05-29 already defers reloads while a form field is focused, so the “we yanked the carpet during a dose log” risk is gone. But it still reloads silently the moment they tab away. For full UX polish, replace the silent reload with a non-blocking banner:

A new version of LynCareOS is available. Refresh now | Later

This would let users finish their current train of thought even after they tab away from the form. After a configurable timeout (e.g. 30 min idle) we can force-reload as a last resort.

Effort: 1 day. Add to bootstrap.ts or App.tsx. Lower priority now that Layer 5 + safeReload() already handle the worst cases.

Layer 4 — Preserve old chunks for a grace window

Section titled “Layer 4 — Preserve old chunks for a grace window”

The current backend/Dockerfile builds the SPA into the container image. When the container is replaced, all old chunks vanish instantly. This is the cause of the 404 that layer 1 then recovers from.

Two ways to fix the root cause:

  • Option A — Persistent assets volume. Mount /app/frontend/dist/assets/ on a Docker volume that survives container replacement. The new image’s entrypoint copies its assets/ into the volume on startup, without removing old files. A daily cron prunes files older than 48 h. Cost: small change to Dockerfile + compose. Pro: simplest path. Con: assets accumulate, container startup gets a bit slower.
  • Option B — Move static assets to Cloudflare Pages / R2. App container only serves index.html + /api/*. Static /assets/* go to Cloudflare’s edge with a long-TTL cache and content-addressed filenames. The CDN keeps old chunks effectively forever and we never have to think about it. Pro: best for 100k users — every chunk served from edge, ~10× faster. Con: requires splitting the deploy pipeline (one for the SPA, one for the API).

For our current scale (a few thousand users) Option A is enough. Option B becomes worth it around 10k+ DAU or when latency on initial page load starts mattering.

Layer 5 — Version polling (DONE — see §3.5)

Section titled “Layer 5 — Version polling (DONE — see §3.5)”

Implemented 2026-05-29 in frontend/index.html via setInterval(reg.update, 5min) + document.visibilitychange listener. Uses the SW registration’s own update mechanism rather than a separate /api/version endpoint, which keeps the implementation surface to ~40 lines of inline JavaScript with zero backend changes.

A backend /api/version endpoint would be slightly faster (every API call’s response could carry an X-App-Version header that the client compares against its own build ID, catching staleness within milliseconds of any user interaction). That’s a future enhancement if the 5-min poll proves too slow for any operational reality.


6. The release-hygiene checklist (to add to PRODUCTION-DEPLOYMENT-GUIDE)

Section titled “6. The release-hygiene checklist (to add to PRODUCTION-DEPLOYMENT-GUIDE)”

For every production deploy from now on:

  • Backend lints clean — ruff check .
  • Frontend lints clean — npm run lint:strict
  • Frontend builds clean — npm run build emits [inject-sw-version] sw.js CACHE_NAME → lyncareos-<hash> with a different hash from the last deploy. If the hash is the same, the build was a no-op and SW invalidation will not fire.
  • index.html is served Cache-Control: no-store — confirm with curl -sI https://app.lyncareos.com/ | grep -i cache-control. Required for layers 1 + 2 to work at all.
  • Service worker is reachable — curl -sI https://app.lyncareos.com/sw.js | head -5 should return 200.
  • Smoke test from a clean incognito window — open /, navigate to a lazy route, confirm no console errors.
  • Mid-session smoke test — open the app in a normal window before deploy, deploy, then navigate to a lazy route. Confirm the auto-reload fires and the user lands on the new build.

7. Why we did not add a “force refresh on save” prompt

Section titled “7. Why we did not add a “force refresh on save” prompt”

The user’s original instinct was “should we make the user refresh after a deploy?” The answer is no — for two reasons:

  1. The user does not know a deploy happened. Asking them to refresh assumes they have context they don’t have.
  2. A forced refresh interrupts work. If the user is filling in a form, a refresh blows away their unsaved input. The pattern of “show a toast on SW_UPDATED, reload on next idle moment” gives us the recovery without the interruption.

What we implemented — silent auto-recovery — is the right shape for a clinical app. The user never has to know.