Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Fundamentals
  1. 1.Introduction to Frontend System Design
  2. 2.Core Frontend Architecture Concepts
  3. 3.Client-Server Interaction Fundamentals
  4. 4.Basic Performance & Accessibility Considerations
  5. 5.State Management Basics & Data Flow
  6. 6.Advanced State Management & Global Stores
  7. 7.Component Libraries & Design Systems
  8. 8.Frontend Build Tools & Development Workflows
  9. 9.Advanced Performance Optimization Techniques
  10. 10.Data Fetching Strategies & Caching
  11. 11.Frontend Security Essentials
  12. 12.Micro-Frontend Architectures
  13. 13.Real-time Communication & WebSockets
  14. 14.Observability, Monitoring, & Logging
  15. 15.Offline-First & Progressive Web Apps (PWAs)
Frontend System Design Fundamentals
15

Frontend System Design · Lesson 15 of 15 · 5 min

Offline-First & Progressive Web Apps (PWAs)

This topic is a classic differentiator. Your answer here can be the one that separates a senior offer from a mid-level one.

After this lesson, you'll be able to answer "How would you make this app work offline?" without just saying "service workers." You'll be able to detail the specific caching strategies for different assets, explain how to handle data mutations made offline, and articulate the trade-offs involved. This isn't just a feature; it's a core architectural decision about reliability.

Why "Offline-First" is a System Design Question

Offline-first isn't about just surviving a lost connection. It's an architecture that prioritizes loading assets from a local cache, treating the network as an enhancement for synchronization, not a dependency for basic operation.

The core trade-off is simple: you gain resilience and perceived performance at the cost of increased complexity and potential data staleness.

In an interview, framing your discussion around this trade-off shows you're thinking at a system level. You're not just implementing an API; you're making a deliberate choice about user experience and engineering overhead.

The Service Worker: Your Programmable Proxy

The heart of any offline-first strategy is the service worker. It's a JavaScript file that your browser runs in the background, separate from your web page. It acts as a network proxy, intercepting any outgoing HTTP request from your app.

This lets you decide what to do with each request: serve it from a cache, fetch it from the network, construct a response from scratch, or queue it for later.

The service worker has a distinct lifecycle. The key events to mention are:

  • install: Triggered once when the worker is first registered. This is your chance to "pre-cache" your core assets—the app shell.
  • activate: Triggered after install succeeds. This is where you clean up old, outdated caches. Forgetting this step is a common bug that leaves users with stale assets.
  • fetch: Triggered for every single network request made by your app. This is where you implement your caching logic.

Here is the essential code to register a worker and implement a basic cache-first strategy.

First, register the worker from your main application code.

// In your main app.js or an inline script
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}

Then, the service worker itself implements the caching logic.

// In /sw.js
const CACHE_NAME = 'static-cache-v1';
const urlsToCache = [
  '/',
  '/styles.css',
  '/app.js',
  '/images/logo.png'
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});

Choosing the Right Caching Strategy

"Use a service worker" is not an answer. The real discussion is about which caching strategy to use for which resource. A real application uses a mix.

The trap: Describing only one strategy. Show you can apply the right tool for the job by discussing several.

  • Cache First: Check the cache. If a response is found, serve it. If not, go to the network. This is ideal for your "app shell"—the static assets that rarely change, like your global CSS, fonts, and core JS bundles. It prioritizes speed above all else.

  • Network First: Try the network. If it succeeds, serve the response and update the cache. If it fails, serve the last-known good version from the cache. Use this for critical information that must be as fresh as possible, but where showing something is better than showing an error (e.g., a user's account balance).

  • Stale-While-Revalidate (SWR): Serve from the cache immediately for a fast response. Simultaneously, send a request to the network. If the network request returns new data, update the cache for the next time the user requests it. This is the best choice for non-critical content that updates frequently, like a social media feed, a news article list, or user avatars. It provides an excellent balance of speed and freshness.

The Cache-First flow is the most fundamental pattern.

Handling Offline Mutations

Caching GET requests is the easy half. The senior-level problem is handling POST, PUT, or DELETE requests made while offline.

The interview question: "Design an offline 'like' button for our social media feed. A user on a spotty train connection should be able to like a post, close the app, and have the like sync when they get back online. How do you build it?"

This is a test of your knowledge beyond simple caching. The correct pattern involves optimistic UI, a local data store, and background synchronization.

  1. Optimistic UI: When the user clicks "like," update the UI immediately. Don't wait for a network response. The button should look liked.
  2. Queue the Mutation: Store the action (e.g., { postId: 123, action: 'like' }) in a queue. The right tool for this is IndexedDB, not localStorage. IndexedDB is asynchronous, can store large amounts of structured data, and is accessible from within a service worker. localStorage is synchronous and will block the main thread.
  3. Register a Sync Event: Use the Background Sync API (registration.sync.register('like-sync')) to tell the service worker to fire a sync event when connectivity is restored.
  4. Process the Queue: In the service worker's sync event listener, read the queued mutations from IndexedDB. Send the actual fetch requests to your server. If a request succeeds, remove it from the queue. If it fails, it stays in the queue for the next sync attempt.

This approach ensures data is never lost and provides a seamless user experience, regardless of network state.

The PWA Checklist for Interviews

To make your web app a full-fledged PWA, you need a few more pieces. Mentioning them shows you understand the complete picture.

  • Web App Manifest: A simple manifest.json file. It provides metadata like the app's name, icons, start URL, and theme colors. This is what enables the "Add to Home Screen" prompt, giving your app a native-like presence on the device.
  • HTTPS: A non-negotiable prerequisite. Service workers can only be registered on secure origins. It's a security measure to prevent man-in-the-middle attacks on your now very powerful network proxy.
  • App Shell Architecture: This is the design pattern of caching the minimal HTML, CSS, and JavaScript required to power the user interface. The app shell loads instantly from the cache, providing a static frame while dynamic content loads from the network or cache.

Try it

Write a basic service worker for your personal portfolio site or a simple side project. In the install event, cache your main CSS file and a logo image. Use your browser's developer tools (Application -> Service Workers -> Offline) to test it. Reload the page while offline and confirm the styles and image still load.

Next: Put these concepts to the test in a full mock system design interview.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Observability, Monitoring, & Logging