What you'll learn: By the end of this lesson you will be able to explain what makes an app offline-first rather than merely cached, name the parts of a sync design (local copy, outbox, revision, change feed, tombstone), say what a conflict is and how a server detects one, compare four resolution policies (overwrite, last-writer-wins, reject, field merge) and the loss each can cause, and decide when a user, a rule or a merge-friendly data type should settle a conflict.
Two people share a paper recipe book. One takes it on a train, crosses out the sugar and writes "150 g". The other, at home, changes the same line to "200 g" and adds a note in the margin. When the book comes back together, someone has to decide what the page says. If nobody checks, the last person to copy their version over the master wins and the other change is simply gone. That is a conflict, and offline-first design is the work of deciding, in advance, how the page is allowed to end up.
The running example is a packing tablet in a grocery warehouse: a packer ticks lines and adjusts quantities while Wi-Fi drops in the cold store, and a supervisor edits the same lines from a desk. The lab uses one made-up line, "Oat milk", with a title, a quantity and a note.
The core idea
- Offline-first means the screen reads and writes local data, and the network only synchronizes it. The app never waits for a request to show a result. Going offline is an ordinary state, not an error page.
- Every offline change is a queued, identified operation, not an overwritten value. It records what the user saw (its base) and what they changed, so that later someone can tell a safe change from a conflicting one.
- A conflict is two changes made without seeing each other, and a policy decides the outcome. Some policies discard one change silently, some refuse it and ask, and some merge. Choosing one is a product decision with data-loss consequences, not a library setting.
Three illustrations run through the lesson: a minimal example (two people edit one line, in different fields and then in the same field), a realistic example (the packing tablet and its supervisor) and a failure example (a device whose clock is wrong, and a client that comes back after the server has forgotten a delete).
Offline-first is more than a cache
A cache keeps copies of responses so a page loads without the network. An offline-first app treats the local store as the source the interface reads and writes. The Ink & Switch essay on local-first software lists, among its ideals, that there is never a need for the user to wait for a request to a server to complete, and that the user can read and write data at any time, even while offline. The same essay adds that data must also be synchronized across devices, which is where this lesson starts.
| Level | Reads offline | Writes offline | What it needs |
|---|---|---|---|
| Online-only | No | No | Nothing; an error page when the network is gone |
| Cached shell and reads | Yes, possibly stale | No | A service worker and a cache (the course's service worker lessons) |
| Offline-first | Yes | Yes, queued | A local database, an outbox, a sync protocol and a conflict policy |
Do not decide that you are offline by asking the browser: MDN describes navigator.onLine as inherently unreliable: browsers and operating systems use different heuristics, a connection to a local network counts as online even without internet access, and MDN says not to disable features based on it, only to provide hints. The online event carries a matching note: it should not be used to decide whether a particular website is reachable. An offline-first app therefore does not branch on "online or offline". It always writes locally, and it tries to sync whenever it has a reason to.
Where the local copy lives
For anything beyond a few settings, the local copy belongs in IndexedDB, which MDN describes as a low-level API for client-side storage of significant amounts of structured data, transactional, asynchronous and bound by the same-origin policy. This lesson uses it as the home of two things: the records and the outbox. The full treatment of the store is in IndexedDB and Storage Quotas and Browser Storage Options, and the saving rules in State Persistence and Synchronization.
One property changes the design. By default, MDN says, data is stored best-effort: it persists while the origin is below its quota, the device has space and the user does not delete it, and under storage pressure the browser may evict it. Eviction is all or nothing per origin: all of an origin's data is deleted together, because deleting only part could cause inconsistency. An origin can ask for persistent storage with navigator.storage.persist(). For an offline-first app the consequence is plain: an unsent change that lives only in local storage is at risk, so the server is the record, the outbox should be sent soon after a connection returns, and the app should be able to start from nothing and pull everything back.
Figure 1. The parts of an offline-first client
How to read this: the left half never touches the network. The engine runs whenever there is a reason to (start-up, a return to the page, a timer, a connectivity hint) and is the only part that talks to the server.
The moving parts
The lab models each of these. None is a standard: they are the smallest set that shows every conflict kind.
| Part | What it is | Why it exists |
|---|---|---|
| Record | A flat set of fields with an id made on the device | The id can be created offline, so no round trip is needed to create something |
rev |
A number the server adds to on every accepted change | Tells whether two changes saw the same version |
| Mutation | One queued change: an id, the record, the base rev, the base fields, the changed fields (a patch), the device clock | Carries enough to detect and explain a conflict |
| Outbox | The queue of mutations not yet answered | Survives a reload and is replayed in order |
| View | The last known server copy with the outbox replayed on top | What the user sees; the same idea as the pending list of Optimistic Updates and Rollback |
| Change feed and cursor | The server numbers changes (seq); the client remembers the last one it pulled |
Lets the client ask only for what changed |
| Tombstone | A deleted record kept as a marker with deleted: true |
Lets other clients learn of the delete |
| Mutation id | A key the server uses to answer a repeated push with its first answer | Makes a retry safe |
Coalescing matters too: two queued edits of one record become one mutation that keeps the first base, otherwise the second would look stale against the first.
What is a conflict, and how is one detected
Two writers conflict when each changed the record without seeing the other's change. The clean way to detect that is a version number the server controls, not a timestamp. A client sends the version it was looking at (baseRev); the server compares it with the current one. Equal means no one got in between; different means someone did.
HTTP has this pattern built in. RFC 9110 defines the If-Match precondition, which makes a request conditional on the server's current entity tag matching, mainly to prevent the "lost update" problem when clients act in parallel; when the condition is false the server must not perform the method and may answer 412 Precondition Failed. RFC 6585 adds 428 Precondition Required, for a server that insists requests be conditional, again to prevent a client from overwriting changes made from stale data. CouchDB uses the same idea with a _rev field: updating a document requires the previous _rev, and a stale one is rejected with 409 Conflict on a single node. A sync design does not have to use HTTP preconditions, but whatever the mechanism, the principle is the same: the writer says what it saw.
Figure 2. Two devices edit the same line while offline
How to read this: nothing is wrong with either edit. The problem appears only when the second push arrives with an older base than the record now has, and what happens next is entirely the policy's choice.
Four policies, and what each one loses
The lab runs the same two scenarios through four server policies. They are this lab's simplified designs, shown to compare outcomes.
| Policy | Rule | Strength | What it loses |
|---|---|---|---|
overwrite |
Apply the client's whole record, no check | Simplest; always succeeds | Any change made by someone else in between, silently, even in a different field |
lww (last writer wins) |
Apply the whole record only if the device clock is not older than the last accepted change | Converges without asking anyone | The older change, silently; and a wrong clock decides who is "older" |
reject |
Apply only if the base rev equals the current rev, else hold a conflict | Never loses data without a decision | Convenience: even edits to different fields are held |
merge |
Three-way merge per field using the base the user saw; hold a conflict only when both changed the same field differently | Keeps both changes when they do not overlap | Needs the base fields in every mutation; overlapping fields still need a decision |
CouchDB's documentation shows a fifth, middle way for peer-to-peer replication: when conflicting edits meet, both revisions are kept, a deterministic algorithm picks one as the "winner" so every peer agrees, and the other stays as a conflicting revision until the application resolves it. CouchDB does not merge for you; the application must present the versions to the user or merge them and write a new revision. A deterministic winner makes replicas agree, but agreement is not the same as keeping everyone's work.
Figure 3. Choosing a policy
concurrent changes OK?"} -->|"yes"| L["Last writer wins,
for this data only"] Q1 -->|"no"| Q2{"Do edits usually
touch different fields?"} Q2 -->|"yes"| M["Per-field three-way merge,
hold same-field clashes"] Q2 -->|"no"| Q3{"Can the data type merge
by construction?"} Q3 -->|"yes"| C["Conflict-free data type
(counter, set, list)"] Q3 -->|"no"| R["Reject the stale write,
ask the user or a rule"]
How to read this: start from what you can afford to lose. Last writer wins is a fine answer for a "last seen" timestamp and a poor one for a quantity or a document.
Minimal example: different fields, then the same field
The first two scenarios of the lab's demo (output in the Build it section) start with the same line, {"title":"Oat milk","qty":2,"note":""}.
- A sets
qtyto 5, B setsnoteto "fridge", A syncs first. Withoverwriteandlwwthe server ends withqty2: B's whole-record write put the old quantity back, and nobody was told. Withreject, B's change is held although the fields differ. Withmerge, the server ends withqty5 and the note "fridge". - A and B both set
qty(5 and 3).overwriteandlwwend at 3 and A's change is gone.rejectandmergeboth hold B's change, namingqtyas the clash.
Failure example: the wrong clock, and the forgotten delete
Last writer wins compares device clocks, and a device clock can be wrong. In the lab's third scenario B's clock runs 3600 ahead; B edits first, A edits later by real time, and the server drops A's later edit as older than B's. CouchDB handles the same problem by choosing the winner with a deterministic algorithm, so every peer picks the same one. Either way the loser is still lost unless something keeps it.
Deletes need their own care. A deleted record is kept as a tombstone so that a client that was offline learns of the delete on its next pull. The server cannot keep tombstones forever, so the lab lets it purge them; a client whose cursor is older than the purge cannot be told what was deleted, and the server answers "resync": replace your copy with the full set. A client that edits a record the server has already forgotten gets a "deleted remotely" conflict and can choose to re-create it.
Figure 4. The life of one queued change
How to read this: Dropped loses a change without anyone being told, and so does an overwrite that is recorded as Applied. A design review should ask which policies can reach either.
Merge by construction
A conflict-free replicated data type (CRDT) is described by crdt.tech as a data structure that simplifies distributed data storage systems and multi-user applications; it ensures that however changes are made on different replicas, they can always be merged into a consistent state. The Ink & Switch essay is candid about the limit: concurrent edits to the same property of the same object still need resolution by the app or the user. A counter that only adds merges cleanly; a quantity that two people set to different values does not. The course's crdt-basics example lab shows counters, a last-writer-wins register and an observed-remove set, and the real-time part of the course returns to them.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Local database as the source for the UI | Instant, works anywhere | A second copy of the data to migrate, evict-proof and secure |
| Outbox of operations | Replayable, explainable, retry-safe | Storage, ordering rules, and a queue that can get stuck |
Server-assigned rev |
A trustworthy way to see "who saw what" | Every write path must carry and check it |
| Last writer wins | No user interruption | Silent loss; dependence on clocks |
| Reject and ask | No silent loss | Users see conflict screens; someone must design them |
| Field-level merge | Fewer conflicts | Mutations carry more data; same-field cases remain |
Build it: four policies, one record
Goal. Run a model of an offline-first client and a sync server through seven situations: different-field edits, same-field edits, a wrong device clock, an edit against a delete, settling a held conflict, tombstones and a purged cursor, and a repeated push.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no React, no DOM, no network, no timers.
cd examples/frontend/labs/offline-first-sync
pnpm test # 22 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In section 1, compare the four policies. Under
overwriteandlwwthe server ends withqty2 even though A changed it to 5, and neither device was told. - In section 3, change nothing and read it: the same later edit is applied when B's clock is correct and dropped when it runs 3600 ahead.
- In section 5, see that "keep mine" does not replay the old mutation: it re-bases the patch on the server's current rev so the next push is no longer stale.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01):
Offline-first sync: one record, two offline editors, four conflict policies
=== 1. A edits qty, B edits note, both offline; A syncs first, then B
overwrite A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=1 merged=0 dropped=0 conflicts=0
server {"title":"Oat milk","qty":2,"note":"fridge"} (rev 3); A sees {"title":"Oat milk","qty":2,"note":"fridge"}
lww A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=1 merged=0 dropped=0 conflicts=0
server {"title":"Oat milk","qty":2,"note":"fridge"} (rev 3); A sees {"title":"Oat milk","qty":2,"note":"fridge"}
reject A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=0 merged=0 dropped=0 conflicts=1
server {"title":"Oat milk","qty":5,"note":""} (rev 2); A sees {"title":"Oat milk","qty":5,"note":""}
merge A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=1 merged=1 dropped=0 conflicts=0
server {"title":"Oat milk","qty":5,"note":"fridge"} (rev 3); A sees {"title":"Oat milk","qty":5,"note":"fridge"}
=== 2. A and B both set qty (5 and 3); A syncs first, then B
overwrite A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=1 merged=0 dropped=0 conflicts=0
server {"title":"Oat milk","qty":3,"note":""} (rev 3); B sees {"title":"Oat milk","qty":3,"note":""}
lww A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=1 merged=0 dropped=0 conflicts=0
server {"title":"Oat milk","qty":3,"note":""} (rev 3); B sees {"title":"Oat milk","qty":3,"note":""}
reject A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=0 merged=0 dropped=0 conflicts=1
server {"title":"Oat milk","qty":5,"note":""} (rev 2); B sees {"title":"Oat milk","qty":5,"note":""}; held: stale-rev on qty
merge A: applied=1 merged=0 dropped=0 conflicts=0 | B: applied=0 merged=0 dropped=0 conflicts=1
server {"title":"Oat milk","qty":5,"note":""} (rev 2); B sees {"title":"Oat milk","qty":5,"note":""}; held: same-field on qty
=== 3. A wrong clock under lww: B's clock is 3600 ahead, B edits first, A edits later
B clock +0 A (the later edit): applied=1 merged=0 dropped=0 conflicts=0; server {"title":"Oat milk","qty":4,"note":""} (rev 3)
B clock +3600 A (the later edit): applied=0 merged=0 dropped=1 conflicts=0; server {"title":"Oat milk","qty":9,"note":""} (rev 2)
=== 4. A deletes the line, B edits its note, both offline; A syncs first
overwrite B: applied=1 merged=0 dropped=0 conflicts=0; server {"title":"Oat milk","qty":2,"note":"fridge"} (rev 3)
lww B: applied=1 merged=0 dropped=0 conflicts=0; server {"title":"Oat milk","qty":2,"note":"fridge"} (rev 3)
reject B: applied=0 merged=0 dropped=0 conflicts=1; server deleted (rev 2); held: stale-rev
merge B: applied=0 merged=0 dropped=0 conflicts=1; server deleted (rev 2); held: deleted-remotely
=== 5. Settling a held conflict (policy reject, both set qty, B holds the conflict)
keep-theirs: B holds stale-rev; base rev 1, server rev 2
after resolve and sync: B applied=0 merged=0 dropped=0 conflicts=0; server {"title":"Oat milk","qty":5,"note":""} (rev 2); B sees {"title":"Oat milk","qty":5,"note":""}
keep-mine: B holds stale-rev; base rev 1, server rev 2
after resolve and sync: B applied=1 merged=0 dropped=0 conflicts=0; server {"title":"Oat milk","qty":3,"note":""} (rev 3); B sees {"title":"Oat milk","qty":3,"note":""}
=== 6. Tombstones: B deletes the line; A has been offline and the server then purges tombstones
no purge A pulled 1 record(s), resync=false; A sees (gone)
server purged 1 tombstone(s)
after purge A pulled 0 record(s), resync=true; A sees (gone)
A edits a purged line: applied=0 merged=0 dropped=0 conflicts=1; held: deleted-remotely
keep-mine re-creates it: applied=1 merged=0 dropped=0 conflicts=0; server {"title":"Oat milk","qty":7,"note":""} (rev 1)
=== 7. The same change pushed twice (a retry after a lost answer)
first answer: {"status":"applied"}; second answer is the same object: true
server processed 1 mutation(s) for 2 pushes; record {"title":"Oat milk","qty":5,"note":""} (rev 2)
What the lab does not show. No IndexedDB, no browser, no real network, and no real device clock: the "clock" is a number the demo sets. The four policies are this lab's own simplified designs, not how any product behaves, and the server's rev, seq and tombstone rules are this lab's choices. There is no per-field timestamp, no version vector and no conflict-free data type in this lab (the crdt-basics lab covers those). Ordering of messages on a real network, partial failures during a push, and a client crashing mid-sync are not modelled; the outbox lesson covers delivery.
Break it. In src/server.ts, in the merge case, replace the clash line with const clash: string[] = [];. The test "merge reports a conflict on that field and changes nothing" fails, because the server now accepts a same-field edit. Restore the line.
In practice: a packing tablet that lost quantities
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A warehouse team packs grocery orders on shared tablets. Wi-Fi is patchy in the cold store, so a tablet can be offline for several minutes at a time. The packing screen saves each line with a whole-record PUT of the line as the tablet last saw it. Supervisors edit the same lines from desks. After a bad afternoon of dropouts, packers report that quantities they had corrected "went back" to the original value.
Starting architecture
Figure 5. Starting point: whole-record writes with no version
How to read this: the API cannot tell a write made from an old copy from a write made from the current one, so the last arrival simply wins.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Keep whole-record PUT, trust the last write |
Nothing | Nothing | Lost updates continue, silently |
| Send only the changed fields, with a base rev; merge on the server; hold same-field clashes | Different-field edits both survive; same-field clashes are visible | Mutations carry a base; the app needs a "needs attention" list | Users must be shown clashes in plain words |
| Reject every stale write | No silent loss at all | Packers hit conflict screens in the cold store | Workflow slows down |
The decision
| Field | Decision record |
|---|---|
| Context | Tablets queue whole-record writes while offline and the server applies them in arrival order, so quantities revert. |
| Decision | Add a server rev per line. Send patches with the base rev and base fields. Merge per field on the server. Hold a same-field clash on the tablet with both values shown, and let a supervisor's value win on request. |
| Consequences, good | A note added at a desk no longer reverts a quantity ticked in the cold store. Clashes are visible and counted. |
| Consequences, bad | A conflict list to build and test, and a larger mutation payload. |
| Revisit when | Several people edit one line at once routinely (consider a merge-friendly data type), or conflicts exceed what staff can resolve. |
Rollout and verification
- Add
revand the change feed first, without changing behaviour, and log how often an incoming write has a stale base (the lost-update rate you are living with now). - Switch writes to patches for one site, behind a flag, and compare the stale-write count with and without a merge.
- Show held conflicts on the tablet and in an admin list, and review the first week of them by hand.
The 2 a.m. failure
A tablet whose clock is an hour ahead (illustrative) was set up before the move to server rev, and a leftover lww rule is still in place for one field, the "packed" flag. After a night shift, the "packed" flag of several lines is stuck at the value that tablet set, and later correct taps are dropped as older. Nothing is reported, because a dropped change is not an error.
First three checks: (1) look for mutations answered as dropped, and for which device; (2) compare that device's clock with the server's; (3) check which fields still use a clock to decide. Mitigation: remove the clock rule for that field, correct the lines from the audit log, and fix the device's time source. Follow-up: count dropped, merged and held outcomes per day in monitoring, treat a non-zero dropped count as a defect, and never decide order from a clock the device controls.
Architect's notes
- Say which fields may lose a write. A "last viewed" field can use last writer wins; a quantity, a status or a document body cannot.
- Detect with a server version, not a timestamp. A device's clock is an opinion.
- Make every outcome visible. Applied, merged, held and dropped should each be counted; a silent outcome is a bug waiting to be found by a user. Plain overwrite cannot even be counted, which is one more reason to avoid it.
- Design the purge. Decide how long tombstones live and what a client does when its cursor is too old.
Common mistakes
- Whole-record writes with no version, so any stale write silently wins.
- Using the device clock as the judge without knowing devices disagree.
- Merging patches without a base, so the server cannot tell a real clash from a coincidence.
- Assuming local data is safe, when the browser may evict best-effort storage.
Key takeaways
- Offline-first means the interface reads and writes a local store and the network only synchronizes it;
navigator.onLineis a hint, not a fact. - A change is a queued operation with a base, and a conflict is two changes made without seeing each other.
- A server-assigned revision detects conflicts reliably; HTTP's
If-Matchand 412 express the same idea. - Four policies, four losses: overwrite and last writer wins drop changes silently, reject drops none but asks often, merge keeps non-overlapping fields.
- Tombstones carry deletes; a purge needs a resync path.
- A CRDT merges by construction but cannot decide what two different values for one property should mean.
- Count dropped and merged outcomes, and remember that an overwrite loses changes while looking like success.
Practice exercises
Exercise 1 — Starter (45 min): Run the demo, then write down for each of the four policies what the user at device B is told in scenarios 1 and 2. Which policies tell nobody anything?
Exercise 2 — Intermediate (2 hours): Add a per-field timestamp to the lww policy so it decides field by field. Which scenario now keeps both edits, and which still loses one? Add one test of each.
Exercise 3 — Advanced (half day): Extend the lab so the server keeps both versions of a same-field clash (as CouchDB does) and the client shows them. Decide what the merged revision is when the user picks neither, and write the test that proves no data is lost.
Related reading
In this course:
- State Persistence and Synchronization, saving state safely and the "ordering is not merging" point that this lesson builds on.
- Optimistic Updates and Rollback, the confirmed-plus-pending view used by the outbox.
- IndexedDB and Storage Quotas and Browser Storage Options, where the local copy lives.
- Cross-Tab Sync with BroadcastChannel, several tabs of one app sharing one local copy.
- Server State: Caching and Revalidation, the read side that offline-first extends with writes.
- Error, Loading and Empty States, how to show "not sent yet" and "needs attention" without a spinner.
The course's service worker lessons (service worker caching strategies) and the following lesson, offline queues and background sync, cover caching the app shell and delivering the outbox. The back-end side of this topic is the sync endpoint's version check and tombstone retention, covered with the API design lessons.
Official documentation
- Ink & Switch: Local-first software, the ideals and the honest limits of CRDTs.
- RFC 9110: HTTP Semantics,
If-Matchand 412, and RFC 6585, 428 Precondition Required. - Apache CouchDB: Replication and conflict model, revisions, a deterministic winner and application-level resolution.
- crdt.tech, what a CRDT is.
- MDN: Navigator.onLine and Storage quotas and eviction criteria.