← All posts

Offline-first web apps: caching, storage and sync conflict patterns

28 Nov 2026 · 8 min read

Offline-first web apps: Service Worker caching, IndexedDB, Background Sync, storage persistence and sync conflict strategies

An offline-first web app treats the device as the place where work happens and the server as somewhere to sync to later. The browser gives you the parts: Service Workers, IndexedDB, Background Sync and the Storage API. It doesn't tell you what happens when two devices edit the same thing offline. This post covers those offline-first patterns, which browsers support which pieces, and the trade-offs between sync conflict strategies.

Every limit and support claim below links to the spec, MDN or paper it came from. Browser support data is from MDN browser-compat-data version 8.1.11, which I queried in November 2026.

The offline-first architecture

Offline-first architecture: the page writes to IndexedDB first, including an outbox of unsynced changes. The Service Worker serves the app shell from the Cache API and replays the outbox to the server when online, via a sync event or on page triggers.

There are three layers, and each has its own spec:

  • The app shell: HTML, JS and CSS, served by a Service Worker from the Cache API, so the app opens with no network. The spec is a W3C Candidate Recommendation Draft.
  • The data: in IndexedDB, a transactional object store (the current version, 3.0, is a W3C Working Draft). Every user action writes here first, and the UI reads from here.
  • The outbox: unsynced changes, also kept in IndexedDB so they survive reloads and crashes. A sync loop pushes them when the network is back.

The order matters: the UI never waits for the network. Kleppmann and his co-authors call this "no spinners" and list it as the first of seven ideals for local-first software.

Service Worker caching strategies

Jake Archibald's Offline Cookbook on web.dev names the strategies most libraries now implement. The ones that matter for offline-first:

  • Cache, falling back to network. The cookbook calls it the default "for building offline-first". Use it for versioned app-shell files cached at install.
  • Stale-while-revalidate. Serve from the cache, fetch an update for next time. Good when "having the very latest version is non-essential", such as avatars.
  • Network falling back to cache. The freshest data when online. The cookbook warns that on a slow connection the user waits for the network to fail first.
  • Cache then network. The page shows cached data straight away, then updates when the network responds.
  • Network only. For things with no offline equivalent, such as analytics and non-GET requests.

The last point is the important one. You can't put a POST in the Cache API, so writes don't belong in the Service Worker cache at all. They belong in IndexedDB, as data you own.

Background Sync: useful, but Chromium-only

The Background Synchronization API lets a page register a tag, and the browser fires a sync event in the Service Worker once it's online. The Offline Cookbook notes this works even when no tab of the site is open. Following the MDN pattern:

// page: after writing the change to the IndexedDB outbox
const reg = await navigator.serviceWorker.ready;
if ("sync" in reg) await reg.sync.register("flush-outbox");

// service worker
self.addEventListener("sync", (event) => {
  if (event.tag === "flush-outbox") event.waitUntil(flushOutbox());
});

The spec is a WICG Draft Community Group Report, not a W3C standard. It says a failed sync "may" be retried "at a time of its choosing", and that user agents "SHOULD limit tracking by capping the number of retries and duration of sync events". The lastChance flag tells you when no more attempts are coming. Support, from browser-compat-data:

APIChromeEdgeFirefoxSafari / iOS
SyncManager (Background Sync)4979NoNo
PeriodicSyncManager (experimental)8080NoNo
StorageManager.persist()55795715.2
StorageManager.estimate()61795717
ServiceWorker40174411.1 / 11.3

Treat Background Sync as an extra, never the only path. Flush the outbox when the app starts, on the online event, when the tab becomes visible, and on a timer. A Firefox or Safari user should never lose a change because a sync event never fired.

Storage quotas, persistence and eviction

The WHATWG Storage Standard gives every origin's local storage bucket a mode, "best-effort" or "persistent", and it starts as best-effort. Under storage pressure, a browser "should clear" best-effort buckets. MDN's quota and eviction guide documents how much each engine allows:

Bar chart of per-origin storage quota as a share of total disk, per MDN: Firefox best-effort 10% capped at 10 GiB, Firefox persistent 50%, Chromium 60%, Safari browser app about 60%, WebKit embedded web view about 15%, with the computed values for a 128 GiB device

The other rules from that guide:

  • Under storage pressure, browsers evict the least recently used origins first and skip origins granted persistence.
  • Eviction removes all of an origin's data at once, so IndexedDB and Cache go together.
  • Safari, with cross-site tracking prevention on, deletes script-created data for origins with no user interaction "in the last seven days of browser use".
  • localStorage is limited to 5 MiB per origin. Writes over quota throw QuotaExceededError, so wrap them in try…catch.

To ask for persistence, call navigator.storage.persist(). It resolves true only if the bucket became persistent (MDN). Firefox asks the user. Chromium decides from heuristics such as engagement, whether the site is installed or bookmarked, and notification permission (web.dev, Persistent storage). The same article advises against asking on page load. Ask after the user saves something they'd hate to lose. And note that Chrome's own research, cited there, found that automatic clearing is rare.

Sync conflict strategies

Conflict timeline: phone and laptop both start at version {phone:1, laptop:1}. Each edits offline. On sync, last-write-wins keeps the later timestamp and drops the other edit; version vectors detect the two edits as concurrent; a CRDT merges both.

Sync is easy until two replicas change the same record without seeing each other's change. There are four common answers.

Last-write-wins (LWW)

Each record carries a timestamp, and the higher one wins. It's simple and it always converges, but it throws away the losing edit without telling anyone, and it relies on device clocks. A common softening is to keep the loser as a "conflicted copy" so a person can merge.

Version vectors

Each replica keeps a counter per replica. Comparing two vectors tells you whether one change happened after the other or whether they're concurrent. That's the "mutual inconsistency" detection described by Parker et al. (1983). Detection isn't resolution: you still need a merge rule or a person to choose.

CRDTs

Shapiro, Preguiça, Baquero and Zawirski defined Conflict-free Replicated Data Types (SSS 2011; long version INRIA RR-7687). These are data types whose replicas are guaranteed to converge under Strong Eventual Consistency, in state-based or operation-based form. The local-first essay names CRDTs as the most promising foundation and introduces Automerge, while noting that more work is still needed.

Here's a small, runnable comparison in standard-library Python (3.14):

def compare(a, b):
    keys = a.keys() | b.keys()
    a_le_b = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
    b_le_a = all(b.get(k, 0) <= a.get(k, 0) for k in keys)
    if a_le_b and b_le_a: return "equal"
    if a_le_b: return "b is newer"
    if b_le_a: return "a is newer"
    return "concurrent: real conflict"

def merge_gcounter(a, b):  # grow-only counter CRDT
    return {k: max(a.get(k, 0), b.get(k, 0)) for k in a.keys() | b.keys()}

base, phone, laptop = {"phone": 1, "laptop": 1}, {"phone": 2, "laptop": 1}, {"phone": 1, "laptop": 2}
print(compare(base, phone))
print(compare(phone, laptop))
edits = [("phone", 1700000005, "title = 'Exam plan'"), ("laptop", 1700000003, "title = 'Exam notes'")]
print("LWW keeps:", max(edits, key=lambda e: e[1]))
x, y = {"phone": 3, "laptop": 1}, {"phone": 2, "laptop": 4}
print(merge_gcounter(x, y) == merge_gcounter(y, x), sum(merge_gcounter(x, y).values()))
b is newer
concurrent: real conflict
LWW keeps: ('phone', 1700000005, "title = 'Exam plan'")
True 7

Version vectors flag the phone and laptop edits as a real conflict. LWW keeps the phone's title and drops the laptop's without a word. The counter CRDT gives the same result whichever side merges first.

An honest comparison

StrategyDetects concurrent edits?Can lose data?Metadata per recordEffortFits
LWWNoYes, silentlyOne timestampLowSettings, single-user records
LWW + conflicted copyPartly (dirty-on-both-sides check)No, but the user merges by handTimestamp + dirty flagLow to mediumNotes, documents with one main editor
Version vectorsYesOnly if your merge rule drops dataOne counter per replicaMediumMulti-device records with custom merge
CRDTsMerged automaticallyNo, but the merged result may not be what users meantOperation or state history; can grow largeHigh, unless you use a libraryReal-time collaborative text, lists, counters

The CRDT row deserves an honest note. Convergence means every replica ends up in the same state. It doesn't mean that state makes sense to a person. Two users renaming the same title still produce one winner. What a CRDT changes is that the outcome is deterministic and nothing goes missing in the history.

What I'd do in practice

In Inkwell, my open-source offline-first notes PWA, every write goes to IndexedDB first, and a "dirty" flag doubles as the persistent outbox. Sync uses last-write-wins by updatedAt with tombstones for deletes, and can keep a conflicted copy when both sides edited a note. For a mostly single-user app, that combination has served me well. I'd only move to CRDTs for real-time co-editing of the same text.

The checklist I'd give anyone starting out:

  1. Cache the app shell at install; serve it cache-first.
  2. Write every change to IndexedDB, with an outbox record, before touching the network.
  3. Flush the outbox on start, online, visibility change and a timer; add Background Sync where it exists.
  4. Use deletion tombstones, not hard deletes, or deleted records come back from other devices.
  5. Call persist() after a meaningful save, and show estimate() in settings.
  6. Pick a conflict strategy per record type, not one for the whole app.

For more of what I build, see my work. If you're designing sync for a web app and want a second opinion, email me.

References

  1. Service Workers, W3C Candidate Recommendation Draft. https://www.w3.org/TR/service-workers/
  2. Indexed Database API 3.0, W3C Working Draft. https://www.w3.org/TR/IndexedDB/
  3. Storage Standard, WHATWG (Living Standard). https://storage.spec.whatwg.org/
  4. Web Background Synchronization, WICG Draft Community Group Report. https://wicg.github.io/background-sync/spec/
  5. Background Synchronization API, MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API
  6. Storage quotas and eviction criteria, MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria
  7. StorageManager: persist() method, MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist
  8. MDN browser-compat-data 8.1.11, MDN. https://github.com/mdn/browser-compat-data
  9. Jake Archibald, The Offline Cookbook, web.dev. https://web.dev/articles/offline-cookbook
  10. Persistent storage, web.dev. https://web.dev/articles/persistent-storage
  11. M. Shapiro, N. Preguiça, C. Baquero, M. Zawirski, Conflict-Free Replicated Data Types, SSS 2011, LNCS 6976, pp. 386–400, Springer. https://doi.org/10.1007/978-3-642-24550-3_29
  12. M. Shapiro et al., Conflict-free Replicated Data Types, INRIA Research Report RR-7687 (2011). https://inria.hal.science/inria-00609399
  13. M. Kleppmann, A. Wiggins, P. van Hardenberg, M. McGranaghan, Local-first software: you own your data, in spite of the cloud, Onward! 2019, ACM, pp. 154–178; essay at Ink & Switch. https://www.inkandswitch.com/essay/local-first/ (doi:10.1145/3359591.3359737)
  14. D. S. Parker et al., Detection of Mutual Inconsistency in Distributed Systems, IEEE Transactions on Software Engineering SE-9, 1983, pp. 240–247. https://doi.org/10.1109/TSE.1983.236733
← How TOTP works: HOTP, RFC 6238 and the …
Building an offline-first note-taking P… →
Written by

Himal Dahal

CTO at Daleema Group. Backend developer in Kathmandu.

Get in touch