How to Coordinate Background Sync in a Service Worker
Coordinate background sync in a service worker: queue writes in IndexedDB, register a sync tag, retry on failure, use Web Locks and fall back where unsupported.

A user submits a form on a train, the tunnel starts and the request fails. A well-built web app keeps the submission and sends it when the connection returns, even if the tab has been closed by then. The Background Synchronization API exists for this: the page asks the service worker to run a sync event when the browser decides connectivity is back, and the worker sends the queued data. Coordinating that flow has several moving parts: where the data waits, how the page and worker agree on a tag, what happens when a retry fails, and how to avoid sending the same item twice from two contexts. This post builds the pattern for background sync in a service worker with IndexedDB as the queue, covers retries and locking and gives a fallback for browsers without the API. It assumes a service worker is already registered, and its locking ideas come from coordinating tabs with Web Locks.
What the API gives you, and what it does not
SyncManager.register(tag) tells the browser: fire a sync event with this tag when the device has connectivity. The event fires in the service worker, which may be woken up for it even though no page is open. The event handler receives event.waitUntil(promise), which keeps the worker alive until the promise settles. If the promise rejects, the browser schedules a retry with backoff, and after a number of failures it gives up. The API carries no data. It is only a signal, so the data must be stored somewhere the worker can read, and IndexedDB is the place, since the service worker cannot read the page's memory.
Support is limited. The API works in Chromium-based browsers and is not available in Firefox or Safari, so a fallback is part of the design. Check the MDN page for the Background Synchronization API for current status before you rely on it.
Step 1: queue the write
The page saves the item into IndexedDB first, then registers a sync. Saving first means nothing is lost if registration fails. A tiny helper using the raw API keeps the sample self-contained.
export function openQueue() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("outbox", 1);
request.onupgradeneeded = () => {
request.result.createObjectStore("messages", { keyPath: "id" });
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function run(db, mode, fn) {
return new Promise((resolve, reject) => {
const tx = db.transaction("messages", mode);
const result = fn(tx.objectStore("messages"));
tx.oncomplete = () => resolve(result?.result);
tx.onerror = () => reject(tx.error);
});
}
export const addMessage = (db, message) => run(db, "readwrite", (s) => s.put(message));
export const allMessages = (db) => run(db, "readonly", (s) => s.getAll());
export const removeMessage = (db, id) => run(db, "readwrite", (s) => s.delete(id));Each message needs a stable id, generated on the client with crypto.randomUUID(). The id serves two purposes: it is the key in the store, and it is the idempotency key sent to the server, so a retry cannot create a duplicate.
Step 2: register the sync from the page
After saving, ask the worker's registration for a sync, and fall back to a direct attempt when the API is missing.
import { openQueue, addMessage } from "./queue.js";
export async function sendMessage(text) {
const db = await openQueue();
const message = { id: crypto.randomUUID(), text, createdAt: Date.now() };
await addMessage(db, message);
const registration = await navigator.serviceWorker.ready;
if ("sync" in registration) {
await registration.sync.register("flush-outbox");
return "queued for background sync";
}
registration.active?.postMessage({ type: "flush" }); // fallback path
return "queued, flushing now";
}queued for background syncThe output shown is for a Chromium browser. Elsewhere the function returns queued, flushing now and relies on a message to the worker. Registering the same tag twice is safe: the browser coalesces registrations with an identical tag into one pending sync.
Step 3: flush in the worker
The worker listens for the sync event, checks the tag and sends every queued message. The handler passes a promise to event.waitUntil, and rejects if any send fails, so the browser retries later.
import { openQueue, allMessages, removeMessage } from "./queue.js";
async function flushOutbox() {
const db = await openQueue();
const messages = await allMessages(db);
for (const message of messages) {
const response = await fetch("/api/messages", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": message.id },
body: JSON.stringify(message),
});
if (!response.ok) throw new Error(`server answered ${response.status}`);
await removeMessage(db, message.id); // remove only after success
}
}
self.addEventListener("sync", (event) => {
if (event.tag === "flush-outbox") event.waitUntil(flushOutbox());
});
self.addEventListener("message", (event) => {
if (event.data?.type === "flush") event.waitUntil(flushOutbox());
});Removing each message only after the server accepted it means a failure part way through leaves the unsent messages in the queue, and the retry picks up where the last attempt stopped. A rejected waitUntil promise signals failure to the browser, which schedules another sync event. The Idempotency-Key header lets the server recognize a message it already stored, for example when the response was lost after the server saved it.
Step 4: avoid double sending
Two flushes can overlap: a sync event fires while a flush message from the page is running. Without protection, both read the same queue and send the same messages. Wrap the flush in a Web Lock, which the service worker supports, so only one runs at a time.
export function flushExclusive(flush) {
return navigator.locks.request("flush-outbox", { ifAvailable: true }, async (lock) => {
if (!lock) return; // another flush is already running
await flush();
});
}With ifAvailable: true, the second caller finds the lock held, receives null and returns without doing anything. The first flush is already reading the queue, and any messages added meanwhile will be picked up by a later sync, so no work is lost. Combined with the idempotency key on the server, this makes double delivery harmless even if the locking has a gap.
Handle permanent failures
A retry loop that never ends is wrong for items the server will never accept. If the server answers with a 4xx status other than 408 or 429, the item is invalid, and retrying will not change that. Move it to a "failed" store, or mark it with the error, and continue with the next message. Otherwise one bad item at the head of the queue blocks everything behind it. Treat 5xx statuses and network failures as transient, in line with the rules in retrying only on specific errors.
Tell the user
Queued does not mean sent. Show the state in the interface: "waiting to send" for queued items and "sent" after success. The page can read the queue from IndexedDB to render the list, and the worker can notify open pages through clients.matchAll() and postMessage when a flush completes, so the interface updates without polling. A user who closes the tab and later opens the app should see the leftover queue and its state.
A fallback for browsers without the API
Where registration.sync does not exist, the worker is not woken up for you, so flush at moments the page controls. Listen for the online event on window and send the worker a flush message when it fires. Flush once when the app starts, to send items left over from a previous session, and again when the page becomes visible after being hidden, using the visibilitychange event. These triggers cover most cases, with one limit: nothing runs while the app is closed, so a message queued just before the user closes the tab waits until the next visit. State that limit in the interface, with a line such as "will send when you reopen the app", so users are not misled.
Testing the flow
Most of the logic is ordinary promise code that can be tested outside a browser. Extract flushOutbox so it takes the queue and a fetch function as parameters, and test it with an in-memory queue and a fake fetch: all messages succeed, the second message fails with a 503 and the first is removed while the rest remain, a message fails with a 400 and is moved to the failed list without blocking the others. For the browser parts, use an end-to-end tool that can switch the page offline, submit the form, switch back online, trigger the sync from the developer tools and assert on what the server received. Chrome's developer tools can fire a sync event by tag from the Application panel, which makes the manual check quick.
Limits and expectations
Background sync is a best-effort service. The browser decides when to fire the event, based on connectivity, battery and its own heuristics, and the work in the handler is limited in time, so a flush with thousands of items may be cut off and finished on a later event. Keep each flush short and resumable, as the queue design here does. Do not use it for time-critical work, since the delay between connectivity returning and the event firing is not under your control. And do not assume the data is safe once queued: storage can be cleared by the user or evicted under pressure, so for important data, ask the browser for persistent storage with navigator.storage.persist() and keep the server as the source of truth.


