Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
63

Frontend System Design · Lesson 63 of 86 · 4 min

Service Workers: Lifecycle and Caching Strategies

This is how you explain you can build a resilient, offline-first app without breaking it on updates.

After this, you'll be able to walk an interviewer through the Service Worker lifecycle, explain the trade-offs of different caching strategies, and describe how to ship updates without causing inconsistent states for your users. These are core concepts for any system design question involving PWAs or offline support.

The Service Worker Lifecycle as a State Machine

A Service Worker (SW) is a JavaScript file that runs on a separate thread, acting as a network proxy. Its lifecycle is a state machine that ensures your app can be updated predictably.

  1. Register: Your application code registers the SW file. The browser then attempts to install it.
  2. Installing: The install event fires. This is your one chance to cache essential static assets (the "app shell"). You must use event.waitUntil() to wrap the caching promises. If any promise rejects, the installation fails, and the SW is discarded.
  3. Waiting: If installation succeeds but an older SW is still controlling the page, the new SW enters the waiting state. It won't activate until all browser tabs controlled by the old SW are closed. This is a safety mechanism to prevent two different versions of your app from running at once.
  4. Activating: Once the old SW is gone, the new one activates, and the activate event fires. This is the ideal time to clean up old caches. Again, use event.waitUntil() to ensure your cleanup code finishes.
  5. Activated: The SW is now active and ready to handle events like fetch. By default, it will only control pages loaded after its activation.

This flow prevents race conditions and ensures a smooth transition between versions.

Forcing Updates with skipWaiting and clients.claim

The default lifecycle is safe but slow. Users won't get an update until they close and reopen all tabs. To force an immediate update, you use two methods together.

self.skipWaiting(): Call this during the install event. It tells the SW to bypass the waiting state and move directly to activating as soon as installation is complete.

self.clients.claim(): Call this during the activate event. It allows the newly activated SW to take immediate control of all open client tabs within its scope. Without this, the new SW would only control new tabs.

The interview question: "You've shipped a critical bug fix in a new Service Worker. How do you ensure users get it immediately, and what are the risks?"

Your answer: "I'd use skipWaiting() in the install event and clients.claim() in the activate event. This forces the new SW to take control right away. The risk is creating an inconsistent state. The client-side app might have loaded with assets from the old SW's cache, but now it's making fetch requests that are being handled by the new SW, which might expect different API formats or asset versions. This requires careful versioning and coordination between the client and the SW."

This trade-off—immediacy vs. consistency—is a classic system design talking point. Show you understand it.

Choosing a Caching Strategy

Once active, the SW's main job is intercepting requests via the fetch event. Your caching strategy determines how it responds. There is no single "best" strategy; the right choice depends on the resource.

Cache-first, then Network Check the cache. If a response is found, serve it. If not, go to the network. If the network request succeeds, cache the response for next time and then return it.

  • Use for: Static assets that change predictably with a new deployment. Your app shell (core HTML, CSS, JS), fonts, and versioned images.
  • Trade-off: Blazing fast and works offline. The downside is serving stale content if an asset is updated on the server but the user still has the old version cached. You solve this with cache-busting (e.g., styles.a1b2c3.css) and by updating the SW itself.

Network-first, then Cache Try the network first. If the request succeeds, update the cache with the fresh response and return it. If the network fails (e.g., the user is offline), fall back to the last-known good version from the cache.

  • Use for: Resources that change frequently and where freshness is important. API calls, user avatars, or a news feed.
  • Trade-off: Prioritizes fresh data. The downside is it's slower on initial request than cache-first because it always hits the network. It only provides offline benefits if the user has been online at least once to populate the cache.

A robust SW doesn't use one strategy; it acts as a router, applying the right strategy based on the request URL or type.

A Practical Service Worker Implementation

This example combines the lifecycle management and a simple routing strategy. Static assets are handled cache-first, while API calls are network-first.

// service-worker.js

const CACHE_NAME = 'app-v1';
const APP_SHELL_URLS = [
  '/',
  '/index.html',
  '/styles.css',
  '/app.js',
  '/images/logo.png'
];

// On install, cache the app shell and activate immediately.
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => cache.addAll(APP_SHELL_URLS))
      .then(() => self.skipWaiting())
  );
});

// On activation, clean up old caches and take control of clients.
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames
          .filter((name) => name !== CACHE_NAME)
          .map((name) => caches.delete(name))
      );
    }).then(() => self.clients.claim())
  );
});

// On fetch, apply the appropriate caching strategy.
self.addEventListener('fetch', (event) => {
  const { request } = event;

  // Ignore non-GET requests
  if (request.method !== 'GET') {
    return;
  }

  // For API calls, use Network-first
  if (request.url.includes('/api/')) {
    event.respondWith(
      fetch(request)
        .then((networkResponse) => {
          // Cache the fresh response
          const responseToCache = networkResponse.clone();
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(request, responseToCache);
          });
          return networkResponse;
        })
        .catch(() => {
          // Network failed, fall back to cache
          return caches.match(request);
        })
    );
    return;
  }

  // For all other GET requests, use Cache-first
  event.respondWith(
    caches.match(request).then((cachedResponse) => {
      if (cachedResponse) {
        return cachedResponse;
      }
      return fetch(request).then((networkResponse) => {
        // A response is a stream and can only be consumed once.
        // We must clone it to put one copy in the cache and return the other.
        const responseToCache = networkResponse.clone();
        caches.open(CACHE_NAME).then((cache) => {
          cache.put(request, responseToCache);
        });
        return networkResponse;
      });
    })
  );
});

Try it

Modify the fetch handler above. In the final catch block of the Cache-first strategy, instead of letting the error propagate, serve a pre-cached /offline.html page. You'll need to add /offline.html to your APP_SHELL_URLS list. This is the first step to providing a custom offline experience.

Next: We will build on these fundamentals to implement full Offline Support and Background Sync.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

PWA Manifest and Installability

Next

Offline Support and Background Sync