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
64

Frontend System Design · Lesson 64 of 86 · 4 min

Offline Support and Background Sync

This is where you show you can design for unreliable networks, not just happy paths. It separates senior-level thinking from just knowing an API.

The Core Offline Data Submission Pattern

When a user submits a form and their connection drops, the app shouldn't just fail. The standard, expected pattern for handling this is to queue the work to be done later.

First, you update the UI optimistically. The app should immediately look and feel as if the submission succeeded. Add the new comment to the list, show the "message sent" confirmation, etc. This provides immediate feedback and improves perceived performance.

Second, you persist the request data in local storage. The right tool for this is IndexedDB. It's an asynchronous, transactional, client-side database. It's designed to hold structured data and won't block the main thread.

The trap: Saying you'd use localStorage. Don't. localStorage is a synchronous, blocking API with a small storage limit (around 5MB). It's fine for a user token, but not for queueing structured data. Using it for this purpose signals a lack of knowledge about modern browser APIs.

Third, you tell the browser to process this queue when the connection returns. This is done by registering a sync event with the Service Worker's SyncManager.

Implementing the Background Sync Flow

The BackgroundSync API connects the main thread (your app) to the Service Worker. Your app registers a "tag," and the Service Worker listens for a sync event with that tag. The browser handles the "when the network is back" part.

Here’s the flow: the user submits a form, you save the data to IndexedDB, and then register the sync.

// In your application code (e.g., component event handler)
async function handleFormSubmit(postData) {
  // 1. Store the data for the service worker to find later.
  await db.addOutboxItem({
    url: '/api/posts',
    method: 'POST',
    body: postData,
  });

  // 2. Register the sync task with the service worker.
  // The 'send-posts' tag is just a string identifier.
  if ('serviceWorker' in navigator && 'SyncManager' in window) {
    const registration = await navigator.serviceWorker.ready;
    try {
      await registration.sync.register('send-posts');
      console.log('Background sync registered for "send-posts".');
    } catch (error) {
      // This can fail if the user has disabled it.
      console.error('Background sync registration failed:', error);
    }
  }

  // 3. Update the UI optimistically.
  showPendingPostInUI(postData);
}

The Service Worker then listens for the sync event. When the browser detects a stable connection, it wakes up the Service Worker (even if the tab is closed) and fires the event.

// In your service-worker.js
import { getAllOutboxItems, deleteOutboxItem } from './db.js';

self.addEventListener('sync', (event) => {
  if (event.tag === 'send-posts') {
    // waitUntil() tells the browser not to terminate the
    // service worker until the promise resolves. This is critical.
    event.waitUntil(syncPendingPosts());
  }
});

async function syncPendingPosts() {
  const items = await getAllOutboxItems();
  for (const item of items) {
    try {
      const response = await fetch(item.url, {
        method: item.method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(item.body),
      });

      if (!response.ok) {
        // If the server returns a 4xx or 5xx, we throw.
        // This tells the SyncManager the sync failed and it should retry.
        throw new Error(`Server error: ${response.status}`);
      }

      // On success, remove the item from our local queue.
      await deleteOutboxItem(item.id);

    } catch (error) {
      console.error(`Failed to send post ${item.id}. Will retry later.`);
      // Re-throwing the error is crucial. It signals to the browser
      // that the sync failed and should be retried with exponential backoff.
      // If you catch and don't re-throw, the browser assumes success.
      throw error;
    }
  }
}

This entire workflow is what interviewers want to see.

Handling Data Conflicts

The simple sync implementation works fine for creating new, independent data. The senior-level follow-up question is always about conflicts.

"Design an offline-first comment section for a blog. What happens if a user edits their comment while offline, but a moderator deletes it before the user's edit can be synced?"

This is a product question disguised as a technical one. There is no single "right" answer; the goal is to discuss trade-offs.

  • Last Write Wins (LWW): This is the simplest strategy. Whichever request hits the server last is the final state. In the example, the offline edit would fail because the target resource (the comment) is gone, and you would need to inform the user. It's simple to implement but can lead to lost data.
  • Application-Specific Merging: For collaborative apps like Google Docs, the server needs logic to merge incoming changes with the current state. This is complex and requires careful data modeling.
  • Conflict-free Replicated Data Types (CRDTs): This is the advanced, formal computer science solution for building collaborative systems. You won't be asked to implement one, but knowing the term shows you're aware of the problem space at a deeper level.

In an interview, state the simplest approach (LWW), explain its risks (data loss), and then mention that more complex scenarios require dedicated merging logic on the backend, possibly using CRDTs if collaboration is a core feature.

Background Sync vs. Periodic Background Sync

Don't confuse BackgroundSync with PeriodicBackgroundSync. They solve different problems.

BackgroundSync is reactive. It's for retrying a failed network request initiated by the user. Use it for sending data (POST, PUT, DELETE). It has good browser support.

PeriodicBackgroundSync is proactive. It lets a Service Worker fetch data on a regular interval (e.g., every few hours) so content is fresh when the user next opens the app. Use it for pre-caching data (GET), like top news articles or weather forecasts. Its browser support is very limited and experimental.

Knowing the difference, and the support status, shows you're a practical engineer who checks caniuse.com.

Try it

Modify the form submission code. Instead of creating a new post, make it handle editing an existing one. Store the edit request in the outbox. Think about how you'd represent a 'create' vs. an 'update' operation in your IndexedDB store and how the server would process them. This takes about 20 minutes.

Next: We'll cover how to proactively engage users even when the app is closed in Push Notifications for Web Apps.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Service Workers: Lifecycle and Caching Strategies

Next

Push Notifications for Web Apps