Sync strategies and conflict resolution
Why it matters
- Every offline-first app that lets users edit data offline eventually has two devices change the same record. The rule you choose decides whether an edit is silently lost.
- Google's "Build an offline-first app" guide describes pull-based, push-based and hybrid sync, and last write wins as a common conflict strategy. Interviewers expect you to know the trade-offs, not just the names.
- Device clocks can be wrong by minutes or hours, and users can change them. Ordering edits by
System.currentTimeMillis()from different phones can pick the wrong winner. - This lesson sits between Single source of truth (Room is what the UI reads) and Queued writes with WorkManager (how pending writes reach the server). Conflict resolution decides what happens when a pending write meets newer server data.
The simple explanation
- You and a coworker both edit the same shared spreadsheet row while offline.
- Last write wins: whichever save the server accepts last overwrites the other. Simple, but one change vanishes.
- Field-level merge: you changed the "status" column, they changed the "amount" column, so both changes survive.
- Server decides: the server applies a business rule (for example "only a manager can change status") and returns the result.
- Version number or ETag: like a document revision number. If you edited revision 3 and the server is at revision 5, your save is rejected until you merge.
What is sync in an offline-first app? Synchronization is reconciling the local database with the server once the device is online again. Google's guide describes two main approaches:
- Pull-based sync: the app fetches data on demand, often just before a screen shows it. It is simple and never fetches unneeded data, but it can refetch unchanged data and works poorly after long offline periods. Paging's
RemoteMediatoris this pattern. - Push-based sync: the local database tries to mirror the server. The app fetches a baseline once, then the server notifies the app (for example with an FCM message) that data is stale, and the app fetches only what changed. The app can stay offline for long periods, but the backend has to support sync and versioning.
- Hybrid: pull for fast-changing feeds, push for things like the signed-in user's data.
Where conflicts come from. When the app writes to Room first and syncs later, the server copy may have changed in the meantime. The guide's advice: conflict resolution usually needs versioning, the app records metadata about when or on which version each change was made, and the server is the final source of truth.
| Strategy | Good for | Risk |
|---|---|---|
| Last write wins | Low-value, single-owner data (preferences, read markers) | The other edit is silently dropped |
| Field-level merge | Records whose fields are edited independently (title vs. body) | Same-field edits still need a rule |
| Server decides | Money, stock, permissions, workflow states | Needs a round trip; the client cannot finish alone |
| Ask the user | Documents and notes where both edits matter | Extra UI, and the user may not be present |
Last write wins with server timestamps. In the guide's version, each write carries timestamp metadata and the server discards anything older than its current state. Because phone clocks can be wrong, many backends order writes by a time or sequence number the server assigns, not by the device clock alone.
Versioning (optimistic concurrency). Each row stores the version (or ETag) the server last gave it. A write sends the version it was based on, for example in an If-Match header. If the server has moved on, it rejects the write, typically with 412 Precondition Failed for If-Match or 409 Conflict in APIs that use a version field. The client fetches the current row, merges, and retries with the new version as its base. The server assigns new versions; the client never invents them.
Field-level merge. A three-way merge compares both sides to the base (the version the local edit started from). A field changed on only one side takes that side's value. A field changed on both sides is a real conflict and needs a rule: server wins, local wins, or ask the user. Sending only the changed fields (PATCH) instead of the whole row avoids many conflicts in the first place.
Pulls and deletes. A pull must not overwrite rows that still have unsynced local changes. Deletes are synced as tombstones (a deleted flag or a change log entry), otherwise a later pull brings the deleted row back. Incremental pulls ask for "changes since" a cursor or change token issued by the server, not a device timestamp.
Notes
- Store the server's
versionorETagon every synced Room row, and send it with each write so the server can detect stale edits. - Never order edits from different devices by
System.currentTimeMillis()alone. Use server-assigned versions or timestamps. - On 412 or 409, fetch the current server row, merge against the base, and retry with the server's new version. Retrying the same request unchanged fails forever.
- Keep the base copy (or the original values of changed fields) with each pending edit; a three-way merge is impossible without it.
- Send only changed fields with
PATCHwhere the API allows it. A full-rowPUTcan overwrite fields this device never touched. - For money, stock and permission changes, send the intent ("add 2 items", "approve request") and let the server apply its rules.
- Every pending write carries an idempotency key, a client-generated UUID created when the write is made. If a request times out after the server processed it, the retry is recognised instead of applied twice.
- Write the merged result to Room. The UI observes Room through
Flow, and a Room-backedPagingSourceinvalidates itself when the table changes, so lists update without extra work. - Pulls skip or merge rows that are still pending; deletes travel as tombstones so a pull cannot resurrect them.
- Run the push in a
CoroutineWorkerenqueued as unique work with aNetworkType.CONNECTEDconstraint, and returnResult.retry()for transient failures so WorkManager applies backoff.
Code example
A three-way merge for a note, plus the Retrofit interface that sends the base version in If-Match. A sync worker calls threeWayMerge after the server rejects a write as stale.
import kotlinx.serialization.Serializable
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.PATCH
import retrofit2.http.Path
data class Note(
val id: String,
val title: String,
val body: String,
val version: Long, // assigned by the server on every accepted write
)
sealed interface MergeResult {
data class Merged(val note: Note) : MergeResult
data class Conflict(val fields: List<String>) : MergeResult
}
// base = the server copy the local edit started from
fun threeWayMerge(base: Note, local: Note, remote: Note): MergeResult {
val conflicts = mutableListOf<String>()
fun <T> pick(field: String, b: T, l: T, r: T): T = when {
l == r -> l
l == b -> r // only the server changed it
r == b -> l // only this device changed it
else -> { conflicts += field; r } // both changed it
}
val title = pick("title", base.title, local.title, remote.title)
val body = pick("body", base.body, local.body, remote.body)
return if (conflicts.isEmpty()) {
// Keep the server's version: it is the base for the retried write
MergeResult.Merged(remote.copy(title = title, body = body))
} else {
MergeResult.Conflict(conflicts)
}
}
@Serializable
data class NetworkNote(val id: String, val title: String, val body: String, val version: Long)
@Serializable
data class NoteChanges(val title: String? = null, val body: String? = null)
interface NotesApi {
// Server answers 412 Precondition Failed if ifMatch is not its current ETag
@PATCH("notes/{id}")
suspend fun update(
@Path("id") id: String,
@Header("If-Match") ifMatch: String,
@Header("Idempotency-Key") idempotencyKey: String,
@Body changes: NoteChanges,
): Response<NetworkNote>
@GET("notes/{id}")
suspend fun fetch(@Path("id") id: String): NetworkNote
}Response<NetworkNote>lets the worker readresponse.code()and handle 412 or 409 without exceptions; on success it writes the returned row and new version to Room.- On
Merged, the worker saves the merged note as still pending with the server copy as its new base, and the next push sends it with the new version. OnConflict, it applies the field's rule or flags the note for the user. Idempotency-Keyis a common header name, not a standard; use whatever your backend expects.
Run the idea in plain Kotlin
data class Note(val id: String, val title: String, val body: String, val version: Long)
sealed interface MergeResult {
data class Merged(val note: Note) : MergeResult
data class Conflict(val fields: List<String>) : MergeResult
}
fun threeWayMerge(base: Note, local: Note, remote: Note): MergeResult {
val conflicts = mutableListOf<String>()
fun <T> pick(field: String, b: T, l: T, r: T): T = when {
l == r -> l
l == b -> r
r == b -> l
else -> { conflicts += field; r }
}
val title = pick("title", base.title, local.title, remote.title)
val body = pick("body", base.body, local.body, remote.body)
return if (conflicts.isEmpty()) MergeResult.Merged(remote.copy(title = title, body = body))
else MergeResult.Conflict(conflicts)
}
// Accepts a write only if it was based on the current version (otherwise 412)
class FakeServer(var current: Note) {
fun update(baseVersion: Long, title: String, body: String): Note? {
if (baseVersion != current.version) return null
current = current.copy(title = title, body = body, version = current.version + 1)
return current
}
}
fun main() {
val base = Note("n1", "Groceries", "milk", version = 1)
val server = FakeServer(base)
// Device B changes the body and syncs first
server.update(1, "Groceries", "milk, eggs")
println("Server after device B: " + server.current)
// Device A changed the title offline, starting from version 1
val local = base.copy(title = "Weekend groceries")
val first = server.update(local.version, local.title, local.body)
println("Device A push on v1: " + if (first == null) "412, stale version" else "accepted")
when (val result = threeWayMerge(base, local, server.current)) {
is MergeResult.Merged -> {
val saved = server.update(result.note.version, result.note.title, result.note.body)
println("Merged and pushed: " + saved)
}
is MergeResult.Conflict -> println("Needs a rule or the user: " + result.fields)
}
// Both devices change the title: a real conflict
val base2 = server.current
server.update(base2.version, "Shopping", base2.body)
val local2 = base2.copy(title = "Food")
println("Same field on both sides: " + threeWayMerge(base2, local2, server.current))
}Expected output:
Server after device B: Note(id=n1, title=Groceries, body=milk, eggs, version=2)
Device A push on v1: 412, stale version
Merged and pushed: Note(id=n1, title=Weekend groceries, body=milk, eggs, version=3)
Same field on both sides: Conflict(fields=[title])
In production
- In a notes app, users who edited on a phone and a tablet found that text added on one device disappeared after the other synced.
- The sync sent the whole note with
PUT. The phone changed only the title offline, but its request also carried the old body, which overwrote the body the tablet had already synced. - The server accepted every write, so there were no errors in the logs.
- The client now sends only changed fields with
PATCH, plus the base version inIf-Match. - The server rejects stale writes with 412; the worker fetches the current note, runs a three-way merge, and retries with the new version.
- Same-field conflicts on the body are shown to the user instead of resolved silently.
- A test simulates two devices editing different fields from the same base and asserts both edits survive.
- A to-do app used last write wins with the device's
System.currentTimeMillis()as the write time. - One user's phone clock was set hours ahead. Its edits always looked newest, so the server discarded later edits from their other devices.
- Users reported "my changes keep reverting", and nothing failed in the logs.
- The server now orders writes by a version it assigns, and clients send the version their edit was based on.
- Stale writes are rejected and merged on the device instead of being compared by wall-clock time.
- A unit test runs two clients with clocks hours apart and asserts the result depends only on versions.
Common mistakes
- Ordering edits by device time. Clocks drift or are set by hand, so the "newer" edit may be older. Use server-assigned versions or timestamps.
- Sending the whole row on every update. A full
PUToverwrites fields this device never changed. Send changed fields with the base version. - Retrying a rejected write unchanged. A 412 or 409 will fail again forever. Fetch, merge, then retry with the new version, and stop after a bounded number of attempts.
- Throwing away the base copy. Without it you cannot tell which side changed a field, so a merge turns into last write wins.
- Field merging fields that depend on each other. A start date and an end date edited separately can merge into an invalid range. Treat related fields as one unit or let the server validate.
- Pulls overwriting pending edits, or resurrecting deleted rows. Skip rows with pending changes during a pull, and sync deletes as tombstones.
- Letting the client resolve business rules. Permissions, payments and stock limits must be enforced on the server; the client merge is only for user-editable content.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you handle a write that the server rejects because the data changed in the meantime?”
“What is an idempotency key and when is it generated?”
“When would you use last write wins, field-level merge or server-decides?”
“What is the difference between pull-based and push-based sync?”
Quiz
A user's offline edit keeps getting overwritten by older edits from another device. The app uses last write wins with System.currentTimeMillis() from each device. What is the most likely cause?
The server rejects a write with 412 Precondition Failed because the If-Match version is stale. What should the client do?
Two offline clients change the approval status of the same expense report. Which strategy is safest?
Which describes push-based sync in Google's offline-first guide?
0 of 4 answered
Mini task
15-minute exercise: handle a stale write in your sync worker
- Add a
version: Longcolumn to a synced Room entity, filled from the server on every pull and successful write. - When the user edits a row offline, store the pending change together with the base copy (the row as it was before the edit) and a client-generated UUID idempotency key.
- In your sync worker, send the change with the base version in
If-Match(or your API's version field) and readresponse.code(). - On 412 or 409, fetch the current server row and call a
threeWayMerge(base, local, remote)function like the one above. OnMerged, save the result as pending with the server row as its new base; onConflict, mark the row as needing user review. - Write unit tests: (a) local changed the title, remote changed the body, both survive; (b) both changed the title, the result is
Conflict(["title"]); (c) the merged note keeps the server's version.
Done condition: all three tests pass, and no System.currentTimeMillis() call appears anywhere in the merge or ordering logic.