SWR via Cache-Control vs Service Worker revalidation

This comparison sits within the stale-while-revalidate implementation guide under Advanced Caching Strategies & CDN Architecture, and resolves a recurring architecture question: you want stale-while-revalidate behaviour, but should it live as an HTTP Cache-Control directive enforced at the CDN edge, or as logic inside a Service Worker on the device?

Both deliver the same user-facing promise — instant cached response now, fresh copy next time — but they operate at different layers, with different blast radius, freshness guarantees, and effects on Interaction to Next Paint and Largest Contentful Paint. The targets are the same either way: TTFB ≤ 200ms, LCP < 2.5s, INP < 200ms, and no main-thread task over the 50ms long-task budget. Pick the wrong layer and you either serve a returning user a week-old page, block the site behind a sticky worker you cannot recall, or spend INP budget on a background cache write. This page triages that choice.

Rapid diagnosis: which layer is your SWR actually on?

Before choosing, confirm where staleness is being produced today — the two layers leave distinct fingerprints in DevTools:

  • Open the Network panel and reload the route. If the served response carries a CDN cache-status header (cf-cache-status, x-cache, age) and no (ServiceWorker) label, your SWR is running at the edge. If the row is labelled (ServiceWorker) and shows Size: (ServiceWorker), a worker answered it.
  • Check Application → Service Workers. A registered, activated worker with a fetch handler means the device can intercept and serve stale independent of any edge header — this is the layer most teams forget is even live.
  • Read the response headers. Cache-Control: ...stale-while-revalidate=<n> in the response is the edge/shared-cache contract; its absence means any staleness you see is coming from the worker's Cache API, not HTTP.
  • Throttle to Offline and reload. A page that still paints proves a worker is serving from the local cache; a network error proves you are edge-only, with no on-device copy.
  • Diff the body across two rapid reloads just after expiry. Edge SWR updates for every visitor to that point of presence after one background refresh; worker SWR updates only on the specific device once its own revalidation completes.

That checklist tells you which layer owns freshness right now. The rest of this page decides which layer should.

Root cause: why the wrong layer bites

Four named failure modes account for almost every regret after shipping SWR at the wrong layer:

  1. Per-device staleness divergence. A Service Worker cache is private to one browser, so a worker chosen for frequently-read shared content serves each returning user their own stale copy — someone who has not visited in a week gets a week-old page no matter how many others refreshed. The mechanism is simple: there is no shared object to converge on freshness.
  2. Offline blank-out. Edge SWR still requires a network hop to the nearest PoP; pick it for an installable app shell or a flaky-network audience and the first failed request paints nothing, because no copy lives on the device.
  3. Main-thread revalidation tax. A worker's cache.put and response clone/parse run on the device event loop. A large synchronous body handled inline can produce a task over the 50ms long-task budget and regress Interaction to Next Paint — a cost the edge never imposes because its refetch happens off-device.
  4. Sticky-worker lock-in. Once installed, a worker intercepts every request on the origin, including the request for its own replacement. A buggy fetch handler can therefore make its own fix un-fetchable — the operational asymmetry that makes worker rollbacks the riskier of the two.

Where each layer revalidates

With Cache-Control: stale-while-revalidate, the edge owns the logic. The first byte the browser receives still comes over the network, but from the nearest point of presence, and the edge — not the device — handles the background refetch from origin. It is declarative: one header, applied to every visitor of every PoP, with no client code.

With a Service Worker, the device owns the logic. The worker intercepts fetch, answers from the Cache API with zero network on a hit, and issues its own background revalidation. It is imperative: JavaScript you ship and version, running per browser, and it works offline.

How each SWR layer answers a request, and who it serves stale Edge SWR reaches a shared cache over a network hop and heals for every visitor behind the point of presence after one background refetch; worker SWR reads a per-device cache with zero network and works offline, but a returning visitor who has been away a week is still served a week-old copy. Both revalidate the origin off the response path. How each layer answers a request — and who it serves stale Cache-Control SWR · CDN edge Service Worker SWR · on device Browser returning visitor network hop 20–80ms CDN edge · shared cache serves stale instantly one refresh heals the PoP Browser + Service Worker zero network · same device Cache API · per device serves stale offline week-away user still stale background refetch background put · costs INP Origin source of truth Both revalidate off the response path — the difference is who holds the stale copy.

Decision matrix

DimensionCache-Control SWR (edge)Service Worker SWR (device)
LayerCDN / shared cachePer-device, in the browser
Hit latencyNetwork hop to nearest PoP (~20-80ms)Zero network — reads local Cache API
Offline supportNone — needs the networkFull — serves from cache offline
Freshness controlCoarse: one TTL/window per routeFine: arbitrary per-request logic
Who is served staleEvery visitor on first request after expiryOnly the specific device, per its cache
INP impactNone — work happens off-deviceSlight — background fetch/put on device
LCP impactDepends on PoP RTTBest — instant on repeat visits
First-visit benefitYes — shared cache helps cold clientsNo — cache is empty until first fetch
Setup complexityLow — one header / edge ruleHigh — register, version, debug a worker
Failure blast radiusEdge config, easy to roll backBuggy worker can break the whole site

Step-by-step resolution, ordered by impact

Work these in order. Most sites finish at step 1; only add the later layers when a named failure mode above actually applies.

1. Default to Cache-Control SWR at the edge

Make the shared edge the baseline for HTML, API JSON, and any resource where a sub-100ms PoP response is good enough and you do not need offline. It benefits first-time and cold-cache visitors (a shared edge object is warm for everyone), needs no client JavaScript, and keeps the main thread free.

http
# Origin/edge response — the CDN owns the background refresh.
Cache-Control: public, max-age=60, stale-while-revalidate=600
# trade-off: the window is one coarse value for all visitors. You cannot
# revalidate "only when the user's permissions changed" — for per-request
# freshness logic you need the worker version in step 2, not this header.

Expected outcome: TTFB holds ≤ 200ms across PoPs, the first visitor after expiry absorbs the single background refresh, and freshness converges for the whole audience behind that node within one revalidation cycle. Rollback is a one-line header revert that propagates in seconds.

2. Add a Service Worker layer only where HTTP cannot reach

Add worker SWR when you specifically need true offline support, zero-network repeat-visit reads (an installable PWA or app shell), or per-request revalidation logic too nuanced for a single header — for example revalidating only when a client-side ETag or auth scope changes.

javascript
// Device-side SWR — zero-network hits, works offline, per-request logic.
async function swr(request) {
  const cache = await caches.open('data-v1');
  const cached = await cache.match(request);
  const fresh = fetch(request).then((res) => {
    if (res.ok) cache.put(request, res.clone());
    return res;
  });
  // trade-off: this runs on the device's main-thread event loop. A large
  // synchronous response body cloned/parsed here can blow the 50ms long-task
  // budget and regress INP — do NOT use it for big payloads without chunking,
  // and prefer edge SWR when you don't actually need offline.
  return cached || fresh;
}

Expected outcome: repeat-visit LCP drops toward the local-read floor (a Cache API hit is effectively zero-network), and the page paints offline. You accept that you are now shipping, versioning, and debugging code with a site-wide blast radius. For the per-route strategy choice inside the worker (cache-first vs SWR in a React app), see the SWR vs cache-first Service Worker comparison.

3. Keep the worker's revalidation off the critical path

Defer the write so a large body clone/parse never lands on the interaction path.

javascript
// In the fetch handler: respond immediately, revalidate after.
event.respondWith(swr(event.request));
event.waitUntil(revalidateInBackground(event.request)); // heavy put/parse here

Expected outcome: the worker's cache.put and parse work leaves the critical path, no task exceeds the 50ms long-task budget, and INP stays under 200ms on repeat visits.

4. Compose both layers deliberately

The strongest setups run edge SWR in front of origin to protect it and warm cold clients, with a worker layered in front of the edge to give returning users offline and instant reads. They are not mutually exclusive — they revalidate at different layers.

Expected outcome: cold and first-time visitors get the shared edge object; returning visitors get zero-network local reads and offline resilience; origin load stays flat because both layers absorb it.

The most consequential difference, and the one that decides most real cases, is who gets served stale and for how long. Edge SWR is a shared cache: when the window opens, the very next visitor to that PoP gets the stale object and triggers the single background refresh that then benefits everyone behind that node. The staleness is broad but short-lived and self-healing across the whole audience. Worker SWR is per-device: each browser carries its own copy and its own revalidation cycle, so a user who has not returned in a week is served a week-old object on their next visit regardless of how many other users refreshed in the meantime. For frequently-read shared content, the edge's shared cache converges on freshness far faster; for a returning-after-a-gap individual on a flaky connection, the worker's local copy is the only thing that paints at all. Naming which of those two users you are optimising for usually settles the choice.

There is also an operational asymmetry worth weighing explicitly. An edge header change propagates in seconds and reverts just as fast, and a mistake degrades to "slightly staler than intended" — annoying, rarely catastrophic. A Service Worker, once installed, is sticky: a buggy fetch handler can intercept every request on the origin and a bad deploy can be hard to claw back, because the broken worker is the very thing that controls whether the fixed worker can be fetched. That is why a worker-based approach demands a tested update-and-skipWaiting path and a rehearsed kill switch before it ships, whereas edge SWR carries almost none of that operational tax.

Verification

Confirm SWR is genuinely active at the layer you chose:

  1. Edge SWR. curl -sI the route twice just after expiry. Expected outcome: both return 200 fast, the cache-status header flips from STALE/REVALIDATING to HIT, and the body updates on the second call — proving the edge revalidated in the background, not on the critical path.
  2. Worker SWR. In DevTools, Application, Service Workers, reload and watch the Network tab: a hit shows the (ServiceWorker) response plus one background request to the same URL. Throttle to Offline and confirm the page still paints.
  3. INP guard (worker only). Record a reload in the Performance panel and confirm the worker's cache.put/parse callback creates no task over 50ms; defer heavy writes with event.waitUntil so they leave the critical path.
  4. RUM field check. Compare TTFB p75 for edge SWR and repeat-visit LCP for worker SWR before and after rollout. Expected outcome: edge SWR holds TTFB ≤ 200ms across PoPs; worker SWR drops repeat-visit LCP toward the local-read floor.
  5. Rollback drill. For edge, revert the header and reconfirm; for the worker, ship a no-op fetch passthrough and confirm the site still works — a worker rollback is the riskier of the two, so rehearse it.

Choosing the layer deliberately — and composing them where it pays — is what separates a resilient cache from a fragile one. When either layer hands you a stale object you must actively evict, the cache invalidation patterns guide covers the purge mechanics.