100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What Are Service Worker Caching Strategies?

Learn Cache First, Network First, and Stale-While-Revalidate service worker strategies and when to use each.

hardQ118 of 224 in Web Development Est. time: 6 minsLast updated:
Open Code Lab

Expected Interview Answer

A service worker caching strategy is the policy a service worker’s `fetch` event handler applies to decide whether a request is served from the Cache API, the network, or some combination of both, trading off freshness against speed and offline availability.

The most common strategies are Cache First (check cache, fall back to network, ideal for versioned static assets like fonts or hashed bundles), Network First (try the network, fall back to cache on failure, ideal for frequently updated content like an API feed where staleness is costly but offline access still matters), and Stale-While-Revalidate (serve the cached response immediately for speed, then fetch a fresh copy in the background to update the cache for next time, ideal for content like a news list where perceived speed matters more than up-to-the-second accuracy). Because the service worker intercepts every fetch inside its scope via the `fetch` event, it can apply different strategies per request pattern — often keyed off URL or destination — rather than one blanket policy for the whole app. Cache versioning (naming caches with a build hash and deleting old caches in the `activate` event) is essential, since stale entries under a reused cache name would otherwise never be evicted and could serve outdated assets indefinitely.

  • Enables offline or flaky-network resilience by serving cached responses
  • Cache First strategy sharply reduces repeat load times for static assets
  • Stale-While-Revalidate balances perceived speed with eventual freshness
  • Per-request-pattern strategy selection avoids one-size-fits-all caching mistakes

AI Mentor Explanation

Cache First is like a scorer who always reads yesterday’s printed stats sheet first and only calls the stadium office if the sheet is missing — fast, but risks being outdated for something that changed. Network First is like calling the live scoring booth first and only falling back to the printed sheet if the phone line is down — fresher, but slower when the network is fine. Stale-While-Revalidate is like handing the fan the printed sheet immediately while quietly sending a runner to fetch the latest numbers for the next request. Each strategy trades speed against freshness differently, exactly as a service worker does with its fetch handler.

Step-by-Step Explanation

  1. Step 1

    Register the service worker

    The page registers a service worker script that installs and takes control of its scope.

  2. Step 2

    Cache assets on install

    The install event pre-caches known static assets into a versioned Cache API bucket.

  3. Step 3

    Intercept fetch and apply a strategy

    The fetch event handler picks Cache First, Network First, or Stale-While-Revalidate per request pattern.

  4. Step 4

    Evict old caches on activate

    The activate event deletes caches from previous versions, keyed by a build hash, to prevent stale entries lingering.

What Interviewer Expects

  • Ability to name and correctly explain Cache First, Network First, and Stale-While-Revalidate
  • Understanding of when each strategy is appropriate (static assets vs frequently updated content)
  • Awareness of cache versioning and eviction in the activate event
  • Mention of the Cache API and fetch event interception mechanics

Common Mistakes

  • Applying one blanket caching strategy to the entire app instead of per-request-pattern
  • Forgetting to version and evict old caches, causing stale assets to persist indefinitely
  • Confusing service worker caching with HTTP Cache-Control headers (a separate, complementary mechanism)
  • Not handling the offline fallback case when both cache and network fail

Best Answer (HR Friendly)

A service worker sits between the browser and the network and can decide how to answer each request — serve a saved copy instantly, always go to the network first, or serve the saved copy immediately while quietly fetching an updated one in the background. Picking the right approach per type of content lets an app feel fast and even work offline, without always showing stale data.

Code Example

fetch handler applying different strategies per request type
const CACHE_NAME = 'app-cache-v3'

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
    )
  )
})

self.addEventListener('fetch', (event) => {
  const { request } = event

  if (request.destination === 'style' || request.destination === 'font') {
    // Cache First for versioned static assets
    event.respondWith(
      caches.match(request).then((cached) => cached || fetch(request))
    )
  } else if (request.url.includes('/api/')) {
    // Network First for frequently changing API data
    event.respondWith(
      fetch(request).catch(() => caches.match(request))
    )
  } else {
    // Stale-While-Revalidate for the rest
    event.respondWith(
      caches.open(CACHE_NAME).then(async (cache) => {
        const cached = await cache.match(request)
        const networkFetch = fetch(request).then((res) => {
          cache.put(request, res.clone())
          return res
        })
        return cached || networkFetch
      })
    )
  }
})

Follow-up Questions

  • When would you choose Network First over Stale-While-Revalidate?
  • How do you handle cache versioning across deployments?
  • What happens if both the cache and the network fail during a fetch?
  • How does service worker caching relate to HTTP Cache-Control headers?

MCQ Practice

1. Which strategy is best suited for versioned, hashed static assets that rarely change?

Cache First serves instantly from cache since a hashed filename guarantees the content never changes.

2. What does Stale-While-Revalidate do?

It returns the cached copy instantly for speed while fetching a fresh copy for next time.

3. Why is cache versioning important in the activate event?

Deleting old-versioned caches on activate prevents outdated assets from being served forever.

Flash Cards

Cache First strategy?Check cache, fall back to network — best for versioned static assets.

Network First strategy?Try network, fall back to cache — best for frequently updated content.

Stale-While-Revalidate?Serve cache instantly, update cache from network in the background.

Why version cache names?So the activate event can evict old caches and avoid stale assets lingering.

1 / 4

Continue Learning