download

How do you design offline-first Android sync without losing edits?

Mobile~10 minReviewed 3 Dec 2026Free · No sign-in

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.
  1. Design the local database, transactional outbox, and background sync pipeline with Room and WorkManager.
  2. How do you prevent duplicate writes on retry and handle 409 Conflict version mismatches without dropping edits or blocking the queue?
Show hints (3)
  1. "MAKE ROOM SSOT"

    Treat Room as the single source of truth (SSOT). UI reads Room Flow queries, and writes commit both the updated entity and a pending outbox row inside one db.withTransaction block (or a single @Dao @Transaction method).

  2. "ATTACH IDEMPOTENCY KEYS"

    Generate a client UUID opId once when creating the outbox row, and send it as an Idempotency-Key header on every WorkManager retry.

  3. "ISOLATE 409 CONFLICTS"

    Send the last synced baseVersion. On 409 Conflict, park the op and flag the row as CONFLICT for 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.

"KOTLIN"
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 outcomeoutbox actionlocal row state
200 OK / 201 Createddelete opupdate serverVersion, mark SYNCED
timeout, IO drop, 503, 429keep op, return Result.retry()stay PENDING (backoff 30 s, 60 s, 120 s)
409 Conflict (version mismatch)park op, continue next opssave server copy, mark CONFLICT for merge
400 / 422 validation errorpark op, stop retryingmark 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 WorkManager retry loop instead of storing opId once in the outbox row. Every timeout retry then creates duplicate records.
  • Putting @Transaction on a Repository method calling two DAOs instead of db.withTransaction (or one @Dao). Room ignores it outside @Dao, risking a crash between writes.
  • Returning Result.retry() on 409 Conflict or 400 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 local PENDING rows), 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 REPLACE a local row marked PENDING or CONFLICT during a pull. Either stage incoming server data in a separate shadow column or skip overwriting dirty rows until the outbox push reconciles baseVersion against 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 baseVersion after each 200. Alternatively, coalesce unsent local updates for the same entityId inside db.withTransaction into one latest payload, keeping the original baseVersion and reusing opId once sent.
  • "Why does WorkManager clamp exponential backoff delays even if you pass a tiny or huge duration?" WorkRequest enforces bounds between MIN_BACKOFF_MILLIS (10 seconds) and MAX_BACKOFF_MILLIS (5 hours). Starting at 30 seconds produces minimum delays of 30 s, 60 s, 120 s, and 240 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 →

Original OfferVibe question. Build an offline-first app · Save data in a local database using Room · Define WorkManager requests · WorkRequest reference.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.