Imagine a user filling out a form in a Progressive Web App while travelling. The user completes the form, presses Submit, and suddenly the internet connection disappears. The application cannot send the data to the server, but the user has already spent time entering it.
A poorly designed application may display an error and lose the submitted information. A better application saves the request locally and sends it when a network connection becomes available again.
This is an important feature of an offline-capable Progressive Web App. It lets users keep working even when the network is unreliable.
Service workers and the Background Synchronization API make this possible. However, registering a background sync request does not guarantee that the server will receive the data. The browser may delay the operation, the request may fail, the service worker may be stopped, or the server may reject the submitted information.
The application must therefore handle failures as part of its normal synchronization process.
In this article, we will build a practical approach for saving failed requests, retrying them through a service worker, handling server errors, and preventing duplicate submissions.
Why Background Synchronization Can Fail
Background synchronization is useful when an application needs to send data after the user loses network connectivity. Instead of asking the user to keep the page open, the application can save the work and ask the browser to run the synchronization task later.
Consider a task management application. A user creates a new task while offline. The application saves the task locally and registers a background sync request. When connectivity becomes available, the service worker attempts to send the task to the backend API.
Several things can happen during this process.
The device may regain connectivity, but the backend server may still be unavailable. The request may reach the server, but the connection may close before the application receives the response. The server may return an error because the submitted data is invalid. The browser may also stop the service worker before the synchronization operation finishes.
These situations require different handling.
For example, a temporary network failure should usually result in another attempt. An invalid request should not be retried continuously because sending the same invalid data again will not fix the problem.
A reliable implementation must understand the difference between temporary failures and permanent failures.
How Background Sync Works in a PWA
A typical background synchronization process involves three parts:
The application saves pending data in browser storage.
The application registers a synchronization request with the service worker.
The service worker sends the saved data to the backend when the browser runs the synchronization event.
The Background Synchronization API uses a tag to identify a synchronization task.
For example, an application can register a task called sync-pending-tasks. When the browser runs the task, the service worker receives a sync event with the same tag.
The important detail is that the service worker must keep the synchronization operation alive by passing its promise to event.waitUntil(). If the promise rejects, the browser may schedule another attempt.
However, the browser controls when background synchronization runs and how many retry attempts are made. Applications should not assume that the browser will retry forever or execute the task at an exact time.
The API also has limited browser availability. It is not supported in every major browser, so a production application should check for support and provide another synchronization path.
Save Failed Requests in IndexedDB
The first requirement is to store data locally before attempting to synchronize it.
Do not keep pending requests only in JavaScript variables. A page can be closed, refreshed, or discarded by the browser. Data stored only in memory will disappear.
IndexedDB is a better choice for storing structured information that needs to remain available after the page is closed.
For this example, assume that the application allows users to create tasks. Each task contains an identifier, title, creation time, and synchronization status.
A pending record could look like this:
{
id: "task-1001",
title: "Review project requirements",
createdAt: Date.now(),
status: "pending",
retryCount: 0
}
The id identifies the local record. The status indicates that the task still needs to reach the server, and retryCount helps the application track previous attempts.
The following code creates an IndexedDB database and an object store for pending tasks.
const DB_NAME = "TaskApplication";
const STORE_NAME = "pendingTasks";
function openDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME, {
keyPath: "id"
});
}
};
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
reject(request.error);
};
});
}
The database is created the first time the application opens it. The object store uses id as its key, which makes it possible to identify and update individual pending tasks.
Next, add a function to save a task.
async function savePendingTask(task) {
const database = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = database.transaction(
STORE_NAME,
"readwrite"
);
const store = transaction.objectStore(STORE_NAME);
store.put(task);
transaction.oncomplete = () => {
database.close();
resolve();
};
transaction.onerror = () => {
database.close();
reject(transaction.error);
};
transaction.onabort = () => {
database.close();
reject(transaction.error);
};
});
}
The important part is that the task is saved before the application considers it safely queued for synchronization.
If the browser cannot store the task, the application should tell the user that it could not save the work. It should not show a successful offline submission message when the data was never stored.
For applications that handle important information, also consider storage limits, browser storage eviction, and what should happen if IndexedDB becomes unavailable.
Register a Background Sync Request
Once the task has been saved, the application can ask the browser to run a background synchronization task.
The following function checks whether the required browser features are available before registering the request.
async function registerTaskSync() {
if (!("serviceWorker" in navigator)) {
return false;
}
const registration = await navigator.serviceWorker.ready;
if (!("sync" in registration)) {
return false;
}
try {
await registration.sync.register("sync-pending-tasks");
return true;
} catch (error) {
console.error("Unable to register background sync:", error);
return false;
}
}
The sync property is not available in every browser. That is why the function checks for it before calling register().
If registration succeeds, the browser has accepted the synchronization request. This does not mean the task has already reached the server.
The application should continue showing the task as pending until the server confirms that it has been processed.
If background sync is unavailable or registration fails, the application can keep the record in IndexedDB and try again when the page is open and connectivity is available.
Handle the Sync Event in the Service Worker
The service worker is responsible for processing the pending records.
First, register a listener for the sync event:
self.addEventListener("sync", (event) => {
if (event.tag === "sync-pending-tasks") {
event.waitUntil(syncPendingTasks());
}
});
The event.waitUntil() call is important. It tells the browser that the synchronization operation is still running and that the service worker needs time to complete its promise.
If the promise rejects, the browser may schedule another synchronization attempt according to its own retry rules.
The next step is to implement syncPendingTasks(). This function should read the pending records from IndexedDB and send them to the backend.
The service worker can access IndexedDB, so the same database can be used by both the application page and the service worker.
Send Pending Records to the Backend
A common mistake is to send every pending record in one large request. If one record contains invalid data, the entire batch may fail, making it difficult to identify which records were successfully processed.
For a small application, processing records individually is easier to understand and recover from. Larger applications can use batches, provided the backend supports clear per-record results.
The service worker needs a function to read pending records:
async function getPendingTasks() {
const database = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = database.transaction(
STORE_NAME,
"readonly"
);
const request = transaction
.objectStore(STORE_NAME)
.getAll();
request.onsuccess = () => {
database.close();
resolve(request.result);
};
request.onerror = () => {
database.close();
reject(request.error);
};
});
}
The service worker can now use this function to retrieve the tasks waiting for synchronization.
Next, create a function that sends one task to the backend:
async function sendTaskToServer(task) {
const response = await fetch("/api/tasks", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": task.id
},
body: JSON.stringify(task)
});
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
return response.json();
}
The Idempotency-Key header is important for preventing duplicate records. It gives the backend a way to recognize that two requests represent the same logical operation.
The backend must actually implement idempotency for this protection to work. Sending the header alone does not prevent duplicate records.
Remove Records Only After Successful Synchronization
After the backend confirms that a task has been processed, the application can remove the corresponding local record.
However, never remove a record before receiving a successful response.
Imagine that the service worker sends a task to the server. The server creates the task successfully, but the network connection closes before the service worker receives the response.
From the browser's point of view, the request failed. If the application deletes the local record anyway, the user may lose track of an operation that was never confirmed.
If the application keeps the record and sends it again, the server may receive a duplicate request.
This is why local storage and backend idempotency need to work together.
The following function removes a completed task:
async function removePendingTask(taskId) {
const database = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = database.transaction(
STORE_NAME,
"readwrite"
);
transaction.objectStore(STORE_NAME).delete(taskId);
transaction.oncomplete = () => {
database.close();
resolve();
};
transaction.onerror = () => {
database.close();
reject(transaction.error);
};
transaction.onabort = () => {
database.close();
reject(transaction.error);
};
});
}
The synchronization process can now send a task and remove it only after the server confirms success.
Handle Temporary and Permanent Failures Differently
Not every failed request should be retried.
Consider these examples:
Failure | Typical handling |
|---|
Network unavailable | Retry later |
Request timeout | Retry with care |
Server returns 500 | Usually retry later |
Server returns 503 | Retry later |
Server returns 400 | Mark for correction |
Server returns 401 | Refresh authentication or request sign-in |
Server returns 403 | Check permissions; do not retry continuously |
Server returns 409 | Resolve the conflict or apply the server's response |
The exact response depends on the backend API contract. For example, a 409 response may represent a duplicate operation that the server has already processed, in which case the client may be able to treat it as completed.
A temporary server error should not cause the application to discard the record. On the other hand, repeatedly sending invalid data will not solve a validation problem.
The following example distinguishes retryable failures from other HTTP errors:
function isRetryableStatus(status) {
return status === 408 ||
status === 429 ||
status >= 500;
}
A network failure usually causes fetch to reject before an HTTP response is received. That should also be treated as a temporary failure unless the application has evidence that the operation cannot succeed.
For a 401 response, the application may need a valid authentication session before retrying. A background service worker should not assume that it can silently refresh every user's credentials.
For a 400 response, keep the record available for inspection or correction, but do not allow it to block every other pending task.
Build the Synchronization Process
The following example connects the previous functions into one synchronization process.
It processes tasks individually, removes successful records, and rejects the synchronization promise when a temporary failure occurs.
async function syncPendingTasks() {
const tasks = await getPendingTasks();
for (const task of tasks) {
try {
await sendTaskToServer(task);
await removePendingTask(task.id);
} catch (error) {
console.error(
`Unable to synchronize task ${task.id}:`,
error
);
throw error;
}
}
}
This is a useful starting point, but a production implementation needs more careful error handling.
For example, the current function stops when the first task fails. That may be appropriate if the application wants the browser to retry the whole operation. However, one invalid task could prevent other valid tasks from being processed.
A better design records the result of each task separately.
The following example continues processing other tasks when the server returns a permanent client error, but rejects the overall operation when a temporary failure occurs.
async function syncPendingTasks() {
const tasks = await getPendingTasks();
let temporaryFailure = false;
for (const task of tasks) {
try {
await sendTaskToServer(task);
await removePendingTask(task.id);
} catch (error) {
const status = error.status;
if (status && !isRetryableStatus(status)) {
await markTaskForReview(task.id, error.message);
continue;
}
temporaryFailure = true;
}
}
if (temporaryFailure) {
throw new Error("Some tasks could not be synchronized.");
}
}
This example assumes that sendTaskToServer attaches the HTTP status to errors and that markTaskForReview updates the IndexedDB record. Those functions should be implemented as part of the application's storage layer.
The important design decision is that a permanent failure does not need to block unrelated records, while a temporary failure should remain available for another attempt.
Use Retry Counts and Backoff for Repeated Failures
A service worker should not continuously send the same request without tracking previous attempts.
Repeated requests can waste battery, network data, and server resources. They can also create unnecessary load when the backend is experiencing an outage.
A useful approach is to store a retry count and calculate a delay before the next application-controlled attempt.
For example, the application can use exponential backoff:
function getRetryDelay(retryCount) {
const baseDelay = 5000;
const maximumDelay = 5 * 60 * 1000;
const delay = baseDelay * Math.pow(2, retryCount);
return Math.min(delay, maximumDelay);
}
The delay increases after each failed attempt until it reaches the maximum value.
A production implementation should also add random variation, often called jitter. This prevents many clients from retrying at exactly the same time after a server outage.
For HTTP 429 and some 503 responses, the server may provide a Retry-After header. When present, the application should consider that guidance instead of immediately applying its own retry schedule.
Remember that Background Sync does not provide a guaranteed execution time. The application can record the next eligible retry time, but the browser still decides when to run a registered background task.
Retry counts should also have a sensible limit. If a task keeps failing, the application should eventually mark it for user attention rather than retrying forever.
Provide a Fallback When Background Sync Is Not Supported
Background Sync is not available in every major browser. A PWA should not depend on it as the only way to send pending data.
The application can use the online event as one fallback when the page is open.
window.addEventListener("online", async () => {
try {
await syncPendingTasksFromPage();
} catch (error) {
console.error("Page synchronization failed:", error);
}
});
The page-side synchronization function should use the same pending records and server rules as the service worker.
Another useful fallback is to check for pending work when the application starts or returns to the foreground.
For example, when the user opens the application, it can read IndexedDB and attempt to synchronize eligible records.
Do not rely only on navigator.onLine to decide whether the server is reachable. It provides a useful indication of the browser's network connection, but it does not prove that a particular API endpoint is available.
The actual request result should determine whether synchronization succeeded.
Prevent Duplicate Submissions on the Backend
One of the most important parts of reliable background synchronization is handling duplicate requests.
Consider this sequence:
The service worker sends a task to the backend.
The backend creates the task.
The response is lost because the network connection closes.
The service worker does not know whether the task was created.
The next synchronization attempt sends the same task again.
Without protection, the backend may create two records.
A reliable solution is to use an idempotency key.
The client creates a unique identifier when the task is first saved. It sends the same identifier with every retry.
The backend stores the identifier and checks whether it has already processed the operation. If the same request arrives again, the backend returns the previous result instead of creating another record.
The key must remain unchanged across retries. Generating a new identifier for every request defeats the purpose.
This is especially important for payments, orders, messages, bookings, and other operations where duplicate processing can cause real problems.
The backend should also define how long idempotency records are retained and how conflicting requests using the same key are handled.
Testing Background Synchronization Failures
Testing only the successful online path is not enough. A PWA needs to be tested under the conditions that cause synchronization problems.
Start by submitting data while the device is offline. Confirm that the application stores the record in IndexedDB and displays it as pending.
Next, restore connectivity and verify that the service worker can send the request to the backend.
Then test a temporary server failure. For example, make the API return a 503 response and confirm that the local record is not removed.
You should also test what happens when the connection closes after the server has processed the request but before the client receives the response. This is a useful way to verify that the backend's idempotency handling works.
Other important test cases include:
The user closes the application while data is pending.
The service worker is stopped during synchronization.
The browser does not support Background Sync.
The authentication token has expired.
The server rejects a record because its data is invalid.
Several pending records exist, and one of them fails.
The user submits the same operation more than once.
Use browser developer tools to inspect service worker registration, IndexedDB records, network requests, and service worker errors. Also test on the actual browsers and devices supported by the application. Background execution behavior can differ between browser implementations.
Production Practices for Reliable Background Sync
The most important part of background synchronization is not registering a sync event. It is making sure that pending data remains safe until the server has processed it.
For production applications, keep the following principles in mind:
Save pending data in IndexedDB before reporting that it has been queued.
Keep synchronization records until the backend confirms successful processing.
Use stable identifiers and backend idempotency to prevent duplicate operations.
Separate temporary failures from validation and permission errors.
Track retry attempts and avoid sending requests continuously.
Use server-provided retry guidance when available.
Provide a page-based fallback for browsers without Background Sync.
Show users which records are pending, completed, or need attention.
Keep synchronization operations small enough to finish within the browser's background execution limits.
Test network failures and service worker interruptions, not just successful requests.
For applications that handle important business operations, also consider how records are protected on the device, how long they remain stored, and what happens when a user signs out or changes accounts.
Offline storage should not become a place where one user's pending data is accidentally sent using another user's account.
Conclusion
Background synchronization helps Progressive Web Apps work when network connectivity is unreliable. It allows users to save information locally and send it later through a service worker.
However, the browser does not guarantee that every synchronization request will succeed. Network failures, server errors, authentication problems, and service worker interruptions are normal conditions that an application must handle.
A reliable implementation saves pending data in IndexedDB, keeps records until the server confirms success, separates temporary failures from permanent ones, and uses retry logic that does not overload the backend. It should also provide a fallback for browsers that do not support Background Sync.
Most importantly, the backend must be prepared to receive the same operation more than once. With stable request identifiers and idempotency handling, an application can recover from uncertain network failures without creating duplicate records.
The goal is simple: users should not lose their work just because the internet connection disappeared at the wrong time.
Join the conversation! Your thoughts help the community grow.