Offline-first web apps: caching, storage and sync conflict patterns
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
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:
| API | Chrome | Edge | Firefox | Safari / iOS |
|---|---|---|---|---|
SyncManager (Background Sync) | 49 | 79 | No | No |
PeriodicSyncManager (experimental) | 80 | 80 | No | No |
StorageManager.persist() | 55 | 79 | 57 | 15.2 |
StorageManager.estimate() | 61 | 79 | 57 | 17 |
ServiceWorker | 40 | 17 | 44 | 11.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:
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".
localStorageis limited to 5 MiB per origin. Writes over quota throwQuotaExceededError, so wrap them intry…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
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
| Strategy | Detects concurrent edits? | Can lose data? | Metadata per record | Effort | Fits |
|---|---|---|---|---|---|
| LWW | No | Yes, silently | One timestamp | Low | Settings, single-user records |
| LWW + conflicted copy | Partly (dirty-on-both-sides check) | No, but the user merges by hand | Timestamp + dirty flag | Low to medium | Notes, documents with one main editor |
| Version vectors | Yes | Only if your merge rule drops data | One counter per replica | Medium | Multi-device records with custom merge |
| CRDTs | Merged automatically | No, but the merged result may not be what users meant | Operation or state history; can grow large | High, unless you use a library | Real-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:
- Cache the app shell at install; serve it cache-first.
- Write every change to IndexedDB, with an outbox record, before touching the network.
- Flush the outbox on start,
online, visibility change and a timer; add Background Sync where it exists. - Use deletion tombstones, not hard deletes, or deleted records come back from other devices.
- Call
persist()after a meaningful save, and showestimate()in settings. - 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
- Service Workers, W3C Candidate Recommendation Draft. https://www.w3.org/TR/service-workers/
- Indexed Database API 3.0, W3C Working Draft. https://www.w3.org/TR/IndexedDB/
- Storage Standard, WHATWG (Living Standard). https://storage.spec.whatwg.org/
- Web Background Synchronization, WICG Draft Community Group Report. https://wicg.github.io/background-sync/spec/
- Background Synchronization API, MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API
- Storage quotas and eviction criteria, MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria
- StorageManager: persist() method, MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist
- MDN browser-compat-data 8.1.11, MDN. https://github.com/mdn/browser-compat-data
- Jake Archibald, The Offline Cookbook, web.dev. https://web.dev/articles/offline-cookbook
- Persistent storage, web.dev. https://web.dev/articles/persistent-storage
- 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
- M. Shapiro et al., Conflict-free Replicated Data Types, INRIA Research Report RR-7687 (2011). https://inria.hal.science/inria-00609399
- 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)
- 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
Himal Dahal
CTO at Daleema Group. Backend developer in Kathmandu.