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.