How do you design offline-first Android sync without losing edits?
Question
Field technicians use your Android inspection app inside subways and basements, often losing signal for 20 minutes. Today, tapping Save calls POST /inspections straight from the ViewModel:
- If signal drops mid-request, the edit disappears.
- If a response times out after the server already saved it, tapping Retry creates a duplicate inspection.
- If two technicians edit the same inspection offline, the second sync silently overwrites the first.
- Design the local database, transactional outbox, and background sync pipeline with Room and
WorkManager. - How do you prevent duplicate writes on retry and handle
409 Conflictversion mismatches without dropping edits or blocking the queue?
Show hints (3)
- "MAKE ROOM SSOT"
Treat Room as the single source of truth (SSOT). UI reads Room
Flowqueries, and writes commit both the updated entity and a pending outbox row inside onedb.withTransactionblock (or a single@Dao@Transactionmethod). - "ATTACH IDEMPOTENCY KEYS"
Generate a client UUID
opIdonce when creating the outbox row, and send it as anIdempotency-Keyheader on everyWorkManagerretry. - "ISOLATE 409 CONFLICTS"
Send the last synced
baseVersion. On409 Conflict, park the op and flag the row asCONFLICTfor merge instead of retrying forever or overwriting the server.
Show checked explanation
Make Room the single source of truth (SSOT). Save each edit and an outbox row with a client-generated UUID opId and baseVersion inside db.withTransaction (or one @Dao @Transaction method). Drain the outbox via WorkManager with NetworkType.CONNECTED and exponential backoff, sending Idempotency-Key: <opId>. On 409 Conflict, park the op and mark the record CONFLICT for merge so edits are never overwritten or lost.
Atomic Room multi-DAO db.withTransaction vs un-transacted Repository writes, UUID idempotency deduplication, WorkManager exponential backoff bounds, and 409 Conflict isolation were simulated on CPython 3.12.10 (no Android SDK or Room runtime installed locally); Android Architecture, Room, and WorkManager APIs checked against official Android documentation. Checked by an editor other than the author.
Walkthrough
An offline-first client decouples user writes from the network. Screens observe Room (Flow<InspectionEntity>), so every edit appears immediately and survives app kills and 20-minute subway blackouts.
When the user taps Save, wrap both the local row update (syncState = PENDING) and the outbox_ops insert (holding a stable client UUID opId, entityId, baseVersion, and payload) in db.withTransaction (androidx.room.withTransaction). Multi-DAO writes need db.withTransaction because Room processes @Transaction only on @Dao methods; placing @Transaction on a Repository function is silently ignored.
suspend fun saveLocalAndQueue(note: InspectionEntity, opId: String) {
db.withTransaction {
inspectionDao.upsert(note.copy(syncState = SyncState.PENDING))
outboxDao.insert(
OutboxOp(opId, note.id, note.serverVersion, note.body)
)
}
}
val syncReq = OneTimeWorkRequestBuilder<OutboxSyncWorker>()
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED).build())
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
workManager.enqueueUniqueWork(
"sync_outbox", ExistingWorkPolicy.APPEND_OR_REPLACE, syncReq
)ExistingWorkPolicy.APPEND_OR_REPLACE avoids cancelling an in-flight upload (unlike REPLACE) while chaining a follow-up pass if new edits arrive mid-sync. Inside OutboxSyncWorker, each HTTP request sends Idempotency-Key: <opId> plus baseVersion (or an ETag / If-Match header).
| server outcome | outbox action | local row state |
|---|---|---|
200 OK / 201 Created | delete op | update serverVersion, mark SYNCED |
timeout, IO drop, 503, 429 | keep op, return Result.retry() | stay PENDING (backoff 30 s, 60 s, 120 s) |
409 Conflict (version mismatch) | park op, continue next ops | save server copy, mark CONFLICT for merge |
400 / 422 validation error | park op, stop retrying | mark FAILED and prompt user |
If the server saved the request right before the tunnel dropped the response, WorkManager retries with the exact same opId. The server looks up Idempotency-Key and returns the stored 200 result with zero duplicates. On 409 Conflict, parking the op keeps later unrelated inspections flowing while preserving both versions for merge.
Common mistakes
- Generating a fresh UUID inside the
WorkManagerretry loop instead of storingopIdonce in the outbox row. Every timeout retry then creates duplicate records. - Putting
@Transactionon a Repository method calling two DAOs instead ofdb.withTransaction(or one@Dao). Room ignores it outside@Dao, risking a crash between writes. - Returning
Result.retry()on409 Conflictor400 Bad Request. Non-transient errors poison the queue and waste battery retrying endlessly. - Overwriting the server blindly on
409 Conflict(or letting a background pull overwrite localPENDINGrows), silently destroying field work.
Follow-up questions
- "What happens when a background pull fetches newer server data while an inspection still has local PENDING edits?" Never blindly
REPLACEa local row markedPENDINGorCONFLICTduring a pull. Either stage incoming server data in a separate shadow column or skip overwriting dirty rows until the outbox push reconcilesbaseVersionagainst the server. - "What if a user edits the same inspection three times offline before regaining signal?" You can replay the three ordered ops per entity sequentially and update
baseVersionafter each200. Alternatively, coalesce unsent local updates for the sameentityIdinsidedb.withTransactioninto one latest payload, keeping the originalbaseVersionand reusingopIdonce sent. - "Why does WorkManager clamp exponential backoff delays even if you pass a tiny or huge duration?"
WorkRequestenforces bounds betweenMIN_BACKOFF_MILLIS(10seconds) andMAX_BACKOFF_MILLIS(5hours). Starting at30seconds produces minimum delays of30 s,60 s,120 s, and240 s, protecting both device battery and backend servers during outages.
What a strong answer covers
Makes Room the SSOT and commits the entity plus outbox row in db.withTransaction (or a single @Dao @Transaction) with a stable UUID opId and baseVersion. Drains via WorkManager with NetworkType.CONNECTED and exponential backoff, and parks 409 Conflict rows for merge.
Open in interactive practice deck →