Skip to content

Lesson 5 of 9 · 25m

Offline Data Sync: Queues, Conflicts, and Cache Strategy

Offline-first is a data design problem — mutation queues, idempotency, cache invalidation, and user-visible sync state matter more than a catch handler.

Every team says "we support offline" right up until the first conflict. Offline support is not caching GET responses; it is deciding what the user is allowed to do while disconnected, how those actions are represented, and what happens when two devices disagree. The browser gives you storage and network interception. The consistency model is your job.

Cache reads by intent, not habit

The three common strategies are different products:

  • Cache-first for immutable hashed assets: fast and safe because the URL changes with content.
  • Network-first for HTML and fresh operational data: correctness when online, fallback when offline.
  • Stale-while-revalidate for data that may be briefly stale: instant render, silent refresh.
async function networkFirst(request) {
  try {
    const fresh = await fetch(request);
    const cache = await caches.open("pages-v1");
    cache.put(request, fresh.clone());
    return fresh;
  } catch {
    return (await caches.match(request)) || Response.error();
  }
}

Do not apply one policy globally because a blog post did. An account balance and a logo are not the same object.

Writes need a mutation queue

If the user creates or edits while offline, store an intent, not just the final document shape:

{
  "id": "op_01JZQ0...",
  "type": "report.update",
  "entity": "rep_1842",
  "baseRevision": 17,
  "patch": {"status": "ready"},
  "createdAt": "2026-11-29T21:15:00Z"
}

Replay operations in order when connectivity returns. Operations need idempotency keys because retries happen after uncertain failures: the server may have accepted a write whose response never arrived. "At least once" replay plus idempotent server endpoints is boring and survivable.

Conflicts need policy before UI

Last-write-wins is a legitimate choice for a preference toggle and a terrible one for medical notes. Common policies are server-wins with local backup, field-level merge, operational transform/CRDT for collaborative text, or explicit user resolution. Pick per entity. Then surface state honestly: saved locally is not synced, and users deserve to know the difference.

Field notes

  • Use the Background Sync API where available as a hint, not a guarantee; browsers may throttle or omit it.
  • A service worker can cache responses, but application-owned mutation queues belong in IndexedDB where transactions are explicit.
  • Test offline by toggling DevTools offline after the app loads, then edit, reload, and come back online. Most bugs hide across restarts.
  • Cache invalidation is part of deployment. Version cache names and clean old caches during activation.

Was this lesson helpful?

Sign in to rate