Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

HTTP Caching, Service Workers and PWA Interview Questions

12 HTTP caching, service worker and PWA interview questions with code: Cache-Control directives, ETag and 304 revalidation, cache busting, the service worker lifecycle, cache-first vs network-first vs stale-while-revalidate, offline support and the web app manifest.

Sumit KumarUpdated Oct 12, 20266 min readWeb Performance
HTTP Caching, Service Workers and PWA Interview Questions

The fastest request is the one you never make. Caching questions show up in frontend interviews because they connect performance, deployment and offline support. Here are 12 HTTP caching, service worker and PWA interview questions, from fresher to mid level.

HTTP caching and service workers: the browser checks the service worker, then the HTTP cache using Cache-Control and ETag validation, before going to the network, with cache-first and network-first strategies for a PWA

HTTP caching#

Q1. How does browser HTTP caching work?#

Answer: when a response arrives, the browser stores it according to its headers. For the next request to the same URL it checks:

  1. Fresh? If the response is still within its max-age, it's used directly with no network request ("from disk cache" / "from memory cache" in DevTools).
  2. Stale? The browser revalidates: it sends a conditional request (If-None-Match / If-Modified-Since). If unchanged, the server replies 304 Not Modified with no body and the cached copy is reused.
  3. Not cacheable or changed? A full 200 response is downloaded.

Shared caches such as CDNs and proxies follow the same headers.

Q2. Explain the main Cache-Control directives#

DirectiveMeaning
max-age=NFresh for N seconds
s-maxage=NFreshness for shared caches (CDN) only
no-cacheMay be stored, but must be revalidated before every use
no-storeNever store at all (sensitive data)
public / privateMay be stored by shared caches / only by the user's browser
immutableWill never change, so don't revalidate even on reload
stale-while-revalidate=NServe a stale copy for N seconds while refreshing in the background
must-revalidateOnce stale, must not be used without successful revalidation
Common trap

no-cache does not mean "don't cache". It means "always check with the server first". Use no-store to prevent storage.

Q3. What are ETag and Last-Modified?#

Text
# First response
HTTP/1.1 200 OK
Cache-Control: no-cache
ETag: "a1b2c3"

# Later request
GET /api/profile
If-None-Match: "a1b2c3"

# Unchanged
HTTP/1.1 304 Not Modified

Answer: they are validators. An ETag is a fingerprint of the content; Last-Modified is a timestamp. The browser sends them back as If-None-Match or If-Modified-Since, and the server returns 304 if nothing changed, saving the body download. ETags are more precise because timestamps have one-second resolution.

Q4. What caching strategy would you use for a typical SPA?#

ResourceHeaderWhy
index.htmlCache-Control: no-cacheAlways revalidate so users get the latest asset references
app.3f9a1c.js, styles.8b2e.css (hashed)Cache-Control: public, max-age=31536000, immutableThe name changes when content changes, so cache forever
API responses with user dataprivate, no-cache or no-storePersonal and changing data
Images and fonts without hashesModerate max-age plus an ETagBalance freshness and speed

This pattern is called cache busting with content hashes: build tools put a hash of the file contents in the file name, so a deploy produces new URLs while unchanged files remain cached. See build tools interview questions.

Q5. What's the difference between memory cache, disk cache, CDN cache and the bfcache?#

  • Memory cache: very fast, for resources used in the current page or tab; cleared when the tab closes.
  • Disk (HTTP) cache: persists across sessions and follows Cache-Control.
  • CDN / edge cache: a shared cache near the user, controlled by s-maxage, public and CDN rules, and purged on deploy.
  • Back/forward cache (bfcache): keeps an entire page snapshot in memory so Back and Forward are instant. unload listeners and Cache-Control: no-store on the document can prevent it.

Service workers#

Q6. What is a service worker?#

Answer: a service worker is a JavaScript file that runs in the background, separate from the page, and acts as a programmable network proxy between your app and the network. It can intercept requests, serve cached responses, work offline, receive push messages and do background sync. It has no DOM access, is event-driven (the browser stops it when idle), works only on HTTPS (or localhost), and controls pages within its scope.

JavaScript
// main.js
if ("serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("/sw.js", { scope: "/" });
  });
}

Q7. Explain the service worker lifecycle#

JavaScript
// sw.js
const CACHE = "app-v2";
const PRECACHE = ["/", "/offline.html", "/app.3f9a1c.js", "/styles.8b2e.css"];

self.addEventListener("install", (event) => {
  // Pre-cache the app shell; install fails if any file fails
  event.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)));
});

self.addEventListener("activate", (event) => {
  // Delete caches from old versions
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
    )
  );
});
  1. Register: the page calls register().
  2. Install: fires once per new version; typically pre-caches files.
  3. Waiting: a new version waits while pages controlled by the old version are still open.
  4. Activate: the new version takes over; clean up old caches here.
  5. Fetch / message / push: the active worker handles events for pages in scope.

The browser checks for an updated sw.js on navigation; a byte-different file starts the cycle again.

Q8. What are skipWaiting and clients.claim?#

Answer: self.skipWaiting() (called during install) makes the new worker activate immediately instead of waiting for old tabs to close. self.clients.claim() (called during activate) makes it control already-open pages without a reload. Together they speed up updates, but they can mix an old page with a new worker and new caches. A safer UX is to show an "Update available, reload" prompt and call skipWaiting when the user accepts.

Q9. Explain the common service worker caching strategies#

JavaScript
self.addEventListener("fetch", (event) => {
  const { request } = event;
  if (request.method !== "GET") return;          // let the network handle it

  if (request.mode === "navigate") {
    // Network first for HTML: fresh when online, cached or offline page when not
    event.respondWith(
      fetch(request).catch(async () =>
        (await caches.match(request)) ?? caches.match("/offline.html"))
    );
    return;
  }

  // Cache first for static assets
  event.respondWith(
    caches.match(request).then((cached) => cached ?? fetch(request))
  );
});
StrategyHow it worksUse for
Cache firstCache, then network on a missHashed JS/CSS, fonts, images
Network firstNetwork, falling back to cache when offlineHTML, frequently updated API data
Stale-while-revalidateReturn the cache immediately, update it from the network in the backgroundAvatars, non-critical API data
Network only / cache onlyOne source onlyPayments, analytics / pre-cached shell

Libraries like Workbox implement these strategies, pre-caching and expiry rules so you don't hand-write them.

Q10. What are common service worker pitfalls?#

  • Caching index.html with cache-first, so users are stuck on an old version.
  • Never deleting old caches, which wastes storage.
  • Caching responses with errors or opaque cross-origin responses without checking.
  • Serving sw.js itself with a long max-age (browsers now cap this, but use no-cache).
  • Caching authenticated or personal API data on shared devices.
  • Forgetting that you need a plan to unregister a broken worker (a "kill switch" version).

Progressive Web Apps#

Q11. What is a PWA, and what makes it installable?#

JavaScript
// manifest.webmanifest (linked with <link rel="manifest" href="/manifest.webmanifest">)
{
  "name": "JioCoder Notes",
  "short_name": "Notes",
  "start_url": "/?source=pwa",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#2563eb",
  "icons": [
    { "src": "/icons/192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icons/512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
  ]
}

Answer: a Progressive Web App is a website that uses modern APIs to feel like an app: reliable offline (service worker), installable (manifest) and engaging (push, app-like display). Installability generally requires HTTPS, a web app manifest with a name, icons, start_url and display, and in some browsers a service worker. Chromium browsers fire beforeinstallprompt, which lets you show a custom install button.

Q12. How would you add offline support to an existing app?#

  1. Serve over HTTPS and fix your HTTP caching headers first.
  2. Register a service worker that pre-caches the app shell (HTML, JS, CSS, icons) and an offline fallback page.
  3. Choose a strategy per request type (Q9).
  4. Store user data in IndexedDB and queue writes while offline, syncing when back online (Background Sync where supported, or on the online event).
  5. Show connection state in the UI and handle conflicts when syncing.
  6. Version caches, show an update prompt, and test offline in DevTools (Application panel and "Offline" throttling).

Storage details are in browser storage interview questions.

Quick revision#

ConceptOne-liner
no-cache vs no-storeRevalidate every time vs never store
ETag + 304Reuse the cached body if unchanged
Hashed assetsCache for a year with immutable
Service workerProgrammable proxy: install, waiting, activate, fetch
StrategiesCache first, network first, stale-while-revalidate
PWAHTTPS + manifest + service worker

Related: Core Web Vitals interview questions and critical rendering path interview questions.

Key takeaways#

  • Fresh responses skip the network; stale ones revalidate with ETag or Last-Modified and may get a 304.
  • Use no-cache for HTML and long-lived immutable caching for content-hashed assets.
  • Service workers are background proxies with an install, waiting and activate lifecycle.
  • Pick a caching strategy per resource type, and always version and clean up caches.
  • A PWA needs HTTPS and a manifest, with a service worker for offline support.