Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Offline and Background Sync

Background Sync

Defer work until the network returns with the Background Sync API: register tags, handle sync events, retry rules, Periodic Sync, browser support and fallbacks.

A user taps "Send" in a tunnel. Without help, your request fails and the message is lost, or the user has to remember to try again. The Background Sync API fixes this: the page asks the browser to run a task "when the connection is back", and the browser wakes your service worker later, even if the tab is closed.

This lesson covers one-off sync, Periodic Background Sync, how retries work, and the honest limits: both APIs are Chromium features today, so a production PWA needs a fallback that works everywhere.

How one-off sync works

sequenceDiagram
  participant P as Page
  participant S as Service worker
  participant B as Browser
  P->>S: save change to IndexedDB
  P->>B: registration.sync.register("send-outbox")
  Note over B: waits for a connection
  B->>S: sync event (tag "send-outbox")
  S->>S: read outbox, POST each item
  S-->>B: promise resolves = success

The page stores the data first. The sync registration is only a signal.

The tag ("send-outbox") is a name you choose. Registering the same tag twice before it fires results in one event, which is why you store the data yourself and let the handler read everything pending.

Registering from the page

JavaScript
// page code (read-only: needs a real service worker)
async function queueAndSync(message) {
  await saveToOutbox(message);               // IndexedDB write first

  const registration = await navigator.serviceWorker.ready;
  if ("sync" in registration) {
    await registration.sync.register("send-outbox");
  } else {
    await trySendNow();                       // fallback: no Background Sync
  }
}

Always write the data before registering. If the registration comes first and the write fails, the handler runs with nothing to send.

Handling the event

JavaScript
// sw.js
self.addEventListener("sync", (event) => {
  if (event.tag === "send-outbox") {
    event.waitUntil(flushOutbox());
  }
});

async function flushOutbox() {
  const items = await readOutbox();
  for (const item of items) {
    const response = await fetch("/api/messages", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(item),
    });
    if (!response.ok) throw new Error("server said " + response.status);
    await removeFromOutbox(item.seq);
  }
}

event.waitUntil receives a promise. If it rejects, the browser treats the sync as failed and retries later. If it resolves, the tag is done. So throwing on a bad response is the retry mechanism. Remove each item only after the server confirmed it, so a failure halfway never loses or duplicates more than one item.

Retry rules

The browser retries a failed tag a small number of times with growing delays (Chromium: three attempts, then it gives up). The handler can read event.lastChance, which is true on the final attempt; use it to tell the user that something could not be sent.

Try it: a sync simulator with retries

The simulator below mimics the browser: it fires the "sync event" when the fake network comes up, retries with backoff when the handler throws, and signals lastChance on the final try.

JS Simulating sync and retries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Change failuresLeft to 5 and run again: the browser gives up after the last attempt, and the data stays in the outbox. That is why the outbox lives in IndexedDB and why you should offer a manual retry too.

Periodic Background Sync

One-off sync reacts to connectivity. Periodic Background Sync asks the browser to wake the worker every so often, for example to refresh news before the user opens the app.

JavaScript
const registration = await navigator.serviceWorker.ready;
const status = await navigator.permissions.query({ name: "periodic-background-sync" });

if (status.state === "granted") {
  await registration.periodicSync.register("refresh-news", {
    minInterval: 12 * 60 * 60 * 1000, // at most every 12 hours
  });
}
JavaScript
// sw.js
self.addEventListener("periodicsync", (event) => {
  if (event.tag === "refresh-news") {
    event.waitUntil(refreshNewsCache());
  }
});

The browser decides when to run it. minInterval is only a lower bound. Chromium grants the permission only to installed PWAs, and the actual frequency depends on how often the user engages with the app. Do not build features that need exact timing.

Browser support and fallbacks

API Chrome / Edge (desktop and Android) Safari Firefox
One-off Background Sync Yes No No
Periodic Background Sync Yes, installed apps only No No

Because of this, treat Background Sync as an enhancement. A robust app does all of these:

  1. Sends immediately when online.
  2. Saves to the outbox when the request fails.
  3. Registers a sync tag if supported.
  4. Flushes the outbox on page load, on the window online event and on a "Retry" button, so Safari and Firefox users still get their data delivered, at least while the app is open.
JS Choosing a send strategy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rules for sync handlers

  • Be idempotent. A handler may run twice for the same data (for example when a request succeeded but the response was lost). Give every queued item a client-generated ID and let the server ignore duplicates.
  • Keep it short. The browser can stop a long-running sync handler. Send small batches.
  • Never rely on it for time-critical delivery. Use push notifications when the server must reach the user.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes the browser retry a failed sync?

    A rejected waitUntil promise marks the sync as failed, and the browser schedules another attempt.
  2. 2. Why write data to IndexedDB before calling sync.register?

    A tag carries no data. The handler must find the pending work in storage.
  3. 3. Which statement about Periodic Background Sync is true?

    minInterval is a lower bound, and Chromium gates the feature behind installation and engagement.
  4. 4. What is a good fallback when Background Sync is unavailable?

    Flushing on load, on online and on a manual retry button gives other browsers a working path.

Summary

  • Store first, then register a sync tag; the tag carries no data.
  • A rejected waitUntil promise means retry; event.lastChance marks the final attempt.
  • Periodic sync is best-effort, installed-app-only and Chromium-only.
  • Handlers must be idempotent and short.
  • Always provide a fallback that flushes the outbox when the page runs.

Next: The Offline Outbox Pattern