Volume 1

Q016: Service Workers, Offline Support and Cache Strategy

Difficulty: SeniorFrequency: HighAnswer time: 7-10 minutes

What Interviewers Want To Evaluate

This question tests whether you understand the difference between a normal worker and a service worker. Interviewers want to hear registration, lifecycle, fetch interception, caching strategies, offline fallback, update behavior, and the risks of caching the wrong thing.

For senior roles, the strongest answer explains how service workers affect reliability, performance, product trust, and release safety.

Short Interview Answer

A service worker is a browser-managed background script that sits between a web page and the network. After registration and activation, it can intercept fetch requests, serve cached responses, update caches, handle offline fallbacks, and support features like push notifications. It cannot directly access the DOM. The main complexity is lifecycle: install, waiting, activate, update, cache versioning, and avoiding stale or unsafe responses.

Detailed Interview Answer

A service worker is registered by the page, then installed and activated by the browser. Once active, it can listen to fetch events and decide whether to respond from cache, network, or a combination. This lets an app load faster, work offline, or recover gracefully when the network is unreliable.

The service worker runs separately from the page. It does not have direct DOM access, and it can be stopped and restarted by the browser. It should be treated as an event-driven network layer, not as long-lived application state.

The important part is strategy. Static assets can often be cache-first with versioned filenames. HTML usually needs network-first or stale-while-revalidate so users do not get stuck on old application shells. API responses need careful rules based on freshness, privacy, and business correctness.

Deep Technical Explanation

The lifecycle is:

page registers service worker
service worker installs
service worker may wait if an old worker controls pages
service worker activates
active worker controls future navigations and fetches

The worker can call event.respondWith() inside a fetch event. That promise resolves to a Response. The response can come from fetch, CacheStorage, generated content, or a fallback.

Common Cache Strategies

Cache-first works well for immutable assets like hashed JavaScript, CSS, fonts, and icons. Network-first works better for HTML and data that should be fresh. Stale-while-revalidate returns cached content immediately while updating the cache in the background.

Offline fallback is useful for navigation requests. If the network fails, the service worker can return an offline page or a previously cached shell.

Code Example

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open("app-static-v1").then((cache) =>
      cache.addAll(["/", "/offline"]),
    ),
  );
});

self.addEventListener("fetch", (event) => {
  const request = event.request;

  if (request.mode === "navigate") {
    event.respondWith(
      fetch(request).catch(async () => {
        const cache = await caches.open("app-static-v1");
        return cache.match("/offline") ?? Response.error();
      }),
    );
  }
});

This is intentionally small. Real applications should include versioning, cleanup, logging, and rules for data sensitivity.

Internal Working

The browser controls when the service worker runs. It can start on an event and terminate when idle. This means global variables are not durable state. Durable state belongs in Cache Storage, IndexedDB, or the server.

An updated service worker is downloaded when the browser checks the script and sees a changed byte. It installs in the background, then usually waits until existing controlled pages close. This prevents one page from being controlled by two incompatible versions at the same time.

Architecture Discussion

Service workers are best treated as infrastructure code. Define cache names, versioning, runtime rules, fallback behavior, and invalidation policy. Do not let random feature code add arbitrary cache behavior without review.

For a Next.js app, be especially careful with HTML and server-rendered routes. A stale HTML shell can point at old assets or hide new server behavior. Asset caching and navigation caching should not use the same strategy.

Trade-Offs

Service workers can make repeat visits faster and make offline behavior feel polished. They also increase release complexity. A bad cache rule can keep broken code alive after a fix ships.

They can also create confusing debugging sessions because DevTools may show a response coming from the service worker rather than the network.

Common Mistakes

A common mistake is caching every request with the same rule. Static assets, HTML, API data, images, and authenticated responses have different correctness requirements.

Another mistake is calling skipWaiting() and clients.claim() without understanding the release behavior. Those APIs can be useful, but they can also swap the network layer under an already-loaded page.

Real Production Story

A PWA can accidentally cache /api/user and show one user's data after logout or account switch if cache keys and privacy rules are wrong. Sensitive responses should usually avoid persistent caching, or should be scoped and cleared on logout.

Enterprise Example

In an enterprise field-sales app, service workers can keep product catalogs, visit notes, and upload queues usable in weak network areas. The architecture must include conflict handling, sync status, cache eviction, and clear user feedback.

Performance Discussion

Service workers can improve repeat-load metrics by serving assets without a network round trip. They can also hurt performance if they add slow JavaScript to every request. Keep fetch handlers small, measure cache hit rates, and avoid blocking critical requests on complex logic.

Security Considerations

Service workers require HTTPS except on localhost. They are powerful because they can intercept requests for their scope. Keep the scope narrow, audit caching of authenticated data, and unregister old workers when changing strategy.

Senior Engineer Perspective

A senior answer should avoid hype. Service workers are not just "offline mode." They are a programmable request layer with lifecycle and correctness concerns.

Lead Engineer Perspective

A lead should define when service workers are allowed, which routes they control, how updates are tested, and how support engineers can diagnose cache-related bugs.

Whiteboard Explanation

Draw page, service worker, network, and cache. Put the service worker between page and network. Then show decisions: cache hit, network fetch, update cache, or offline fallback.

Revision Notes

Service workers intercept network requests after activation. They enable offline and caching strategies, but they require careful lifecycle, versioning, and invalidation.

Key Takeaways

Service workers improve reliability when the cache strategy matches product correctness. The hard part is not storing responses; it is knowing what must stay fresh.

Related Topics

  • Web workers
  • Cache Storage
  • IndexedDB
  • HTTP caching
  • PWA
  • Offline sync

Practice Exercise

Design service worker rules for a documentation site, a banking dashboard, and an ecommerce product listing page. Explain which assets can be cached and which responses must remain fresh.

Follow-Up Questions

  1. How is a service worker different from a Web Worker?
  2. What are install, waiting, and activate?
  3. What does event.respondWith() do?
  4. When would you use cache-first?
  5. When would you use network-first?
  6. Why can stale HTML be dangerous?
  7. How do you clear old caches?
  8. What does skipWaiting() do?
  9. Why is HTTPS required?
  10. How would you debug a service worker cache bug?

Things Interviewers Hate Hearing

"Service workers make the app faster" is too vague. They can make repeat visits faster, but only with measured cache rules and safe update behavior.

How I Would Answer This In A Real Interview

I would say a service worker is a browser-managed background script that can intercept requests for its scope. It is different from a Web Worker because it acts like a programmable network layer, not just a computation thread.

Then I would talk about lifecycle and strategy. Static hashed assets can be cache-first, HTML often needs network-first or stale-while-revalidate, and sensitive API responses need stricter rules. The production risk is stale or unsafe data, so I would include versioning, cache cleanup, and debugging steps.