/Learn
Mobile systems at scale · Part 3 of 7

Conflict resolution without losing an edit

Offline edits collide, and something must decide the result. Treat that as a product choice first and an algorithm second.

03
SyncCRDTUX

Mobile engineeringAll mobile pages

Op 7f3a comes back refused: Dev changed valve 3 while Priya was underground. This post decides what should happen, field by field. Start from the basics in Day 5 →

Study with AI

If you only read this

  1. Last-write-wins is fine for low-value fields and dangerous for everything else. Use hybrid logical clocks, not device clocks.
  2. 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.
  3. Counters and sets want operations or CRDTs. Collaborative text wants a real CRDT library.
The one ruleChoose a conflict policy per field and per entity, tell the user when you chose for them, and never silently drop an edit.

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

PolicyHow it worksUse forRisk
Last-write-winsHighest timestamp wins per fieldProfile fields, preferences, read marksSilent loss when clocks or intent differ
Reject and merge (409)Client sends base_version; server refuses if stale; client merges and retriesBusiness records with several editorsNeeds a merge UI for true clashes
OperationsSend 'add 2' not 'set 7'; server applies in orderCounters, balances, inventory, tagsNeeds idempotent, ordered operations
CRDTData structure where merges always convergeCollaborative text, lists, shared whiteboardsMetadata growth and learning curve
Principal-level answerName the policy per entity and per field in one table, then say who owns each decision: product for the rule, engineering for the mechanism.

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

hybrid-logical-clock.ktKotlin
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}
20 linesUTF-8Kotlin

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

threeway-merge-field.tsTypeScript
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}
13 linesUTF-8TypeScript
UX ruleSilent auto-merge for fields that changed on one side only. A small banner for clashes: 'Priya also changed Status. Keep yours or theirs?' Never a modal that blocks unrelated work.

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.

FieldMerge.ktKotlin
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}
27 linesUTF-8Kotlin
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.

SyncEngine.ktKotlin
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}
14 linesUTF-8Kotlin
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?
Device clocks drift and can be set by the user. A hybrid logical clock stays close to real time, never goes backwards, and orders events from different devices deterministically.
Two users change different fields of the same record offline. What happens?
Nothing visible. Field-level versions or a three-way merge combine both edits automatically. Only the same field changed to different values is a conflict.
When do you pick a CRDT over a 409 merge?
When many users edit the same content at once and a manual conflict step would be unacceptable, such as shared text. For ordinary business records, version checks with a clear UI are simpler and easier to audit.
How do you handle a delete versus an edit?
Decide per entity. A common default is that the edit wins and the record is restored, with a notification to the deleter. For legal or financial records, deletes may be forbidden and replaced by a status.
How do you test conflict logic?
Property-based tests that apply the same set of operations in random orders and assert convergence, plus recorded two-device scenarios replayed against the real sync service.

Practise it:

SyncCRDTUX
Written by

Rizvan

Builds mobile and AI systems at scale and writes the series he wished existed before his own principal loop: one rule, one analogy, something to break, and the interview kit.

All 7 parts
AI Engineer · written by Rizvan · part 3 of 7