If you only read this
- Last-write-wins is fine for low-value fields and dangerous for everything else. Use hybrid logical clocks, not device clocks.
- For important records, send the version you edited from and let the server answer 409 with the current state. Merge by field, ask the user only when the same field clashes.
- Counters and sets want operations or CRDTs. Collaborative text wants a real CRDT library.
01Why conflicts exist at all
A conflict is two edits made from the same starting point that both want to become the next version. Online apps avoid them by making one person wait. Offline-first apps cannot wait, so they accept both edits and reconcile later.
The honest question is not which algorithm is best. It is: what would a reasonable user expect to happen? If two technicians change the same job's status, one of them is wrong. If a supervisor edits the title while a technician adds a photo, nothing is wrong and nothing should be lost.
02Four policies and when to use each
| Policy | How it works | Use for | Risk |
|---|---|---|---|
| Last-write-wins | Highest timestamp wins per field | Profile fields, preferences, read marks | Silent loss when clocks or intent differ |
| Reject and merge (409) | Client sends base_version; server refuses if stale; client merges and retries | Business records with several editors | Needs a merge UI for true clashes |
| Operations | Send 'add 2' not 'set 7'; server applies in order | Counters, balances, inventory, tags | Needs idempotent, ordered operations |
| CRDT | Data structure where merges always converge | Collaborative text, lists, shared whiteboards | Metadata growth and learning curve |
03Last-write-wins done properly
Phone clocks are wrong. People change them, batteries die, time zones shift. If you compare device timestamps, a phone set a day ahead wins every conflict forever.
A hybrid logical clock (HLC) fixes this. It combines the wall clock with a counter and moves forward whenever it sees a larger timestamp from the server. Two properties matter: it never goes backwards, and it stays close to real time. Store one HLC per field, so edits to different fields never conflict.
A hybrid logical clock
1class Hlc(private var wall: Long = 0, private var counter: Int = 0, val node: String) {2 @Synchronized fun now(physical: Long): String {3 if (physical > wall) { wall = physical; counter = 0 } else counter++4 return format()5 }6 @Synchronized fun observe(remote: String, physical: Long): String {7 val (rw, rc) = parse(remote)8 val newWall = maxOf(wall, rw, physical)9 counter = when {10 newWall == wall && newWall == rw -> maxOf(counter, rc) + 111 newWall == wall -> counter + 112 newWall == rw -> rc + 113 else -> 014 }15 wall = newWall16 return format()17 }18 // fixed-width so strings sort correctly: wall(13) - counter(4) - node19 private fun format() = wall.toString().padStart(13, '0') + "-" + counter.toString().padStart(4, '0') + "-" + node20}04Optimistic concurrency with a 409
For records people care about, the client sends the version it edited from. The server compares it with the current version. If they match, it applies the change. If not, it answers 409 with the current record, and the client decides.
The client does a three-way merge: the base version it started from, its own edit and the server's current record. For each field, if only one side changed it, take that change. If both changed it to the same value, fine. If both changed it differently, that field is a true conflict.
Three-way merge, field by field
1type Merge<T> = { merged: T; clashes: (keyof T)[] };2 3function threeWay<T extends Record<string, unknown>>(base: T, mine: T, theirs: T): Merge<T> {4 const merged = { ...theirs };5 const clashes: (keyof T)[] = [];6 for (const k of Object.keys(mine) as (keyof T)[]) {7 const mineChanged = mine[k] !== base[k];8 const theirsChanged = theirs[k] !== base[k];9 if (mineChanged && !theirsChanged) merged[k] = mine[k];10 else if (mineChanged && theirsChanged && mine[k] !== theirs[k]) clashes.push(k);11 }12 return { merged, clashes }; // no clashes: retry silently. Clashes: show the user both values.13}05Operations and CRDTs
A counter edited as 'set stock to 7' loses updates. Edited as 'subtract 1', it never does. Sending intent instead of results is the simplest way to avoid conflicts, and it fits inventory, balances, likes and tags. The requirement is that operations are idempotent (op_id) and the server applies them in a defined order.
CRDTs go further: the data structure itself guarantees that replicas converge regardless of the order operations arrive in. An OR-Set handles add and remove of items. A sequence CRDT handles text. In practice you do not write these yourself. Yjs and Automerge are mature libraries, and on mobile you usually embed one for the collaborative field only, keeping the rest of the record on simpler rules.
The costs are real: metadata grows with edit history, so you need garbage collection or periodic snapshots, and debugging a merged document is harder than debugging a row. Use a CRDT where users genuinely edit the same text at once, not as a default.
06What the user sees
- Every row shows its sync state: saved on this phone, syncing, synced, needs attention.
- Conflicts are visible and recoverable: a history of both versions for a few weeks, with a one-tap restore.
- Deletes are tombstones. If one person deletes and another edits, the edit wins by default and the record comes back with a note, because resurrecting is cheaper than losing work.
- Server-authoritative fields (price, status after approval) are read-only on the client once locked, so the conflict cannot arise.
07Tested code, explained
The decision for each field
This small function decides what happens when two people edit offline. The product team's table becomes code you can test.
1enum class Policy { LAST_WRITE_WINS, ADD_ONLY, ASK_USER }2 3/** A field on the server, and the job version at which it last changed. */4data class Stored(val value: String, val version: Int, val by: String)5 6sealed interface Merge {7 data class Apply(val value: String) : Merge8 data class Refuse(val current: Stored) : Merge9}10 11/** The product team's table, written down as code. */12fun policyFor(field: String): Policy = when {13 field.startsWith("photos") -> Policy.ADD_ONLY14 field == "instructions" || field == "read_marker" -> Policy.LAST_WRITE_WINS15 else -> Policy.ASK_USER // the safe default for anything new16}17 18fun merge(field: String, incoming: String, baseVersion: Int, current: Stored?): Merge {19 // Nobody touched this field since the user read it: j-81 takes this path.20 if (current == null || current.version <= baseVersion) return Merge.Apply(incoming)21 22 return when (policyFor(field)) {23 Policy.LAST_WRITE_WINS -> Merge.Apply(incoming)24 Policy.ADD_ONLY -> Merge.Apply("${current.value},$incoming")25 Policy.ASK_USER -> Merge.Refuse(current) // j-84 takes this path26 }27}policyFor(field)- The policy table. Anything not listed asks the user, the safe choice for a new field.
current.version <= baseVersion- Nobody changed this field since the user read it, so apply it. That's why j-81 merged with no conflict.
Policy.ADD_ONLY- Photos: both people's additions are kept, because they never disagree.
Merge.Refuse(current)- Valve 3 on j-84 lands here. The server applies nothing, and returns what it holds.
Compiled and tested by npm run test:mobile.
Applying a pulled page
Changes and the new cursor commit together. That one choice removes a whole family of sync bugs.
1/** One transaction: the data and the cursor can never disagree. */2private fun applyPage(page: PullPage) = db.transaction {3 for (c in page.changes) {4 val job = jobs[c.jobId] ?: Job(c.jobId)5 val unsent = outbox.any { it.jobId == c.jobId && it.field == c.field }6 val inConflict = job.theirs?.field == c.field7 jobs = jobs + (c.jobId to job.copy(8 // Never overwrite something the user changed and the server has not settled.9 answers = if (unsent || inConflict) job.answers else job.answers + (c.field to c.value),10 version = maxOf(job.version, c.version),11 ))12 }13 cursor = page.next14}unsent || inConflict- Never overwrite something the user changed and the server hasn't settled. This is what keeps leaking on Priya's screen.
maxOf(job.version, c.version)- The version still moves forward, so her eventual choice is based on version 5.
cursor = page.next- Saved in the same transaction. If the phone dies, both the changes and the bookmark roll back, and the pull simply repeats.
Compiled and tested by npm run test:mobile.
08Interview questions
Why not just use the latest device timestamp?
Two users change different fields of the same record offline. What happens?
When do you pick a CRDT over a 409 merge?
How do you handle a delete versus an edit?
How do you test conflict logic?
Practise it: