Offline-first cheat sheet

Revise offline-first Android architecture with Room Flow, WorkManager sync, three-way merge, and idempotent writes for senior interviews.

Key ideas

  1. The UI and domain layers never call the network; only the repository talks to the network data source and updates Room.
  2. DAO reads return Flow so Room re-emits to every collector when any writer—repository, WorkManager worker, or another screen—changes the table.
  3. Writes are suspend functions; Room and Retrofit suspend functions are main-safe, so no withContext(Dispatchers.IO) is needed in the repository.
  4. A failed refresh leaves the database unchanged; report the failure as a separate UI state (an offline banner), not by clearing the list.
  5. Store the server version or ETag on every synced Room row and send it with each write so the server can detect stale edits.
  6. On 412 or 409, fetch the current server row, three-way merge against the base copy, and retry with the server's new version.
  7. Generate IDs on the device with UUID.randomUUID().toString() so creating or updating by ID is idempotent and retries cannot create duplicates.
  8. Enqueue sync as unique WorkManager work with NetworkType.CONNECTED; return Result.retry() only for transient errors.
  9. Keep network models, Room entities, and external models separate with mappers; a backend field rename then breaks only one layer.
  10. Catch IOException and HttpException in refresh coroutines, not Exception, so CancellationException is not swallowed.

APIs at a glance

API or termUse it for
Flow<List<UserEntity>>DAO read that re-emits whenever any writer changes the underlying table
stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue)Convert a cold repository Flow into a hot StateFlow scoped to the ViewModel
collectAsStateWithLifecycle()Collect a StateFlow in Compose with lifecycle-aware resumption
@UpsertInsert new rows and update existing ones in one call; pair with explicit deletes inside @Transaction to match the server
@TransactionGroup an upsert and a delete so the local list matches the server atomically
@HiltWorkerAnnotate a CoroutineWorker so Hilt injects DAO and API dependencies
enqueueUniqueWorkEnqueue a named WorkManager job; prefer APPEND_OR_REPLACE over REPLACE to avoid cancelling a running upload
NetworkType.CONNECTEDConstraint that makes a worker wait for any network before running
Result.retry()Tell WorkManager to retry with exponential backoff (30 s initial, 10 s min, 5 h cap) for transient errors only
@PATCH with If-Match headerSend only changed fields with optimistic concurrency; server returns 412 if the version is stale
Idempotency-Key headerClient-generated UUID per write so a retry after a timeout is recognised, not applied twice
getWorkInfosForUniqueWorkFlow(name)Observe WorkInfo states (ENQUEUED, RUNNING, SUCCEEDED, FAILED, BLOCKED, CANCELLED) for UI sync status

Snippets

Repository: read from Room, write through network

data class User(val id: String, val name: String)
 
@Entity(tableName = "users")
data class UserEntity(@PrimaryKey val id: String, val name: String)
 
data class NetworkUser(val id: String, val name: String)
 
fun UserEntity.asExternalModel() = User(id, name)
fun NetworkUser.asEntity() = UserEntity(id, name)
 
@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun observeUsers(): Flow<List<UserEntity>>
 
    @Upsert
    suspend fun upsertAll(users: List<UserEntity>)
}
 
interface UserApi {
    @GET("users")
    suspend fun fetchUsers(): List<NetworkUser>
}
 
class UserRepository @Inject constructor(
    private val userDao: UserDao,
    private val api: UserApi,
) {
    fun observeUsers(): Flow<List<User>> =
        userDao.observeUsers().map { rows -> rows.map { it.asExternalModel() } }
 
    suspend fun refresh() {
        val remote = api.fetchUsers()
        userDao.upsertAll(remote.map { it.asEntity() })
    }
}

Three-way merge against the base copy

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)
}

Enqueue unique sync work with network constraint

class NoteSyncWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params) {
    override suspend fun doWork(): Result = Result.success() // push PENDING rows from Room
}
 
fun enqueue(workManager: WorkManager) {
    val request = OneTimeWorkRequestBuilder<NoteSyncWorker>()
        .setConstraints(
            Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()
        )
        .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
        .build()
    workManager.enqueueUniqueWork(
        "note-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request
    )
}

Rules of thumb

  • Prefer Room Flow over one-shot suspend DAO reads for any data the UI displays.
  • Never call the network from the UI or domain layer; only the repository talks to the server.
  • Never clear cached data on a failed refresh; keep the cache and show the error alongside it.
  • Prefer APPEND_OR_REPLACE over REPLACE when enqueuing unique WorkManager work to avoid cancelling a running upload.
  • Never order edits by System.currentTimeMillis(); use server-assigned versions or timestamps.
  • Prefer PATCH with changed fields over a full-row PUT to avoid overwriting fields this device never touched.

Gotchas

  • Showing the network response directly in the UI. The screen is empty offline and can disagree with other screens that read Room. Fix: write the response to Room and observe Room via Flow.
  • Using ExistingWorkPolicy.REPLACE for sync work. Every new write cancels a running upload mid-flight. Fix: use APPEND_OR_REPLACE, or KEEP with a worker that loops until the queue is empty.
  • Marking rows FAILED on transient errors (503, timeout). The row drops from the next pending query and is never retried. Fix: keep the row PENDING and return Result.retry() so WorkManager applies backoff.
  • Retrying a 412 or 409 response unchanged. The same stale request fails forever. Fix: fetch the current server row, three-way merge against the base, and retry with the server's new version.
  • Putting payloads in WorkManager Data. Data is limited to 10 KB per input or output; building a larger one throws. Fix: pass IDs and read the pending rows from Room inside the worker.
  • Catching Exception in a refresh coroutine. CancellationException is swallowed and the coroutine cannot be cancelled. Fix: catch IOException and HttpException specifically.

Quick interview answers

Why should DAO reads return Flow instead of a suspend List?

A Flow re-emits whenever any writer changes the table, so every screen stays in sync automatically. A one-shot suspend fun getUsers(): List<UserEntity> returns a snapshot that never updates when a worker or another screen writes to the same table.

What happens when a refresh fails in an offline-first architecture?

The database is left unchanged, so the screen keeps showing the cached data. The failure is reported as a separate piece of UI state, such as an offline banner, rather than by clearing the list.

How do you resolve a 412 Precondition Failed response?

Fetch the current server row, perform a three-way merge against the base copy the local edit started from, and retry with the server's new version. Retrying the same request unchanged will fail forever because the version is still stale.

Why generate IDs on the device instead of the server?

A client-generated UUID makes creating or updating a record by ID idempotent, so a retry after a timeout cannot create a duplicate. Server-generated IDs break this guarantee because each retry receives a new ID and the server sees two distinct records.

What is the difference between APPEND_OR_REPLACE and REPLACE for unique work?

REPLACE cancels any running work and starts a new one, which can kill an upload mid-flight. APPEND_OR_REPLACE queues the new request after any unfinished work, so a running upload completes first; if the existing chain has failed or been cancelled, it starts a fresh chain instead of inheriting that failure as plain APPEND would.

Why use a three-way merge instead of last-write-wins?

A three-way merge compares local and remote changes against the base copy, so only fields changed by one side are taken from that side. Without the base copy you cannot tell which side changed a field, and the merge degrades to last-write-wins, silently losing the other side's edits.

Go deeper