Queued writes with WorkManager

Learn queued offline writes in Android with WorkManager: pending rows in Room, unique work, network constraints, Result.retry() backoff and idempotent sync. About 25 minutes.

Why it matters

  • Users expect a save to work instantly, online or not. Writing to Room first and syncing later means the UI never waits on the server.
  • Work enqueued with WorkManager is persisted and survives process death and device reboots; a coroutine in viewModelScope or applicationScope does not. Interviewers probe this difference.
  • Retried uploads are a classic source of duplicate records. Client-generated IDs, idempotent requests and the right ExistingWorkPolicy prevent them.
  • Google's offline-first guide recommends WorkManager for draining write queues: it waits for a network constraint, applies exponential backoff on Result.retry(), and runs one sync at a time as unique work.

The simple explanation

  • A restaurant kitchen: every order is written on a ticket and pinned to a rail (pending rows in Room).
  • The cook (WorkManager) works the rail only when the supplier is reachable (network constraint).
  • If a delivery fails, the ticket stays on the rail and the cook waits longer before each new try (backoff).
  • Each ticket has a number written by the waiter (a client-generated ID), so cooking the same ticket twice still produces one dish.
  • There is one cook for the rail (unique work), so two cooks never send the same ticket at once.

How do you queue offline writes on Android? Write the change to Room first and mark it pending, then enqueue a WorkManager CoroutineWorker that uploads pending rows when the network is available. The UI observes Room through Flow, so the change appears immediately. Google's offline-first guide calls this a lazy write (local first, then queued to the network) and contrasts it with online-only writes (for things like a bank transfer) and fire-and-forget queued writes (for analytics and logs).

The pending marker. Either add a syncState column (PENDING, SYNCED, FAILED) to the entity, or keep a separate outbox table with one row per operation (create, update, delete). An outbox table keeps the order of operations and works well for deletes; a status column is simpler when you only upload the latest state of each row.

Client-generated IDs. Create the row's ID on the device (UUID.randomUUID().toString()) and use it on the server too. Then the upload can be an idempotent PUT /notes/{id}: if a request times out after the server saved it, the retry updates the same note instead of creating a second one. For non-idempotent endpoints, send a client-generated idempotency key that the server deduplicates on.

The worker. A CoroutineWorker reads a bounded batch of pending rows, uploads them, and marks each one synced. It returns:

  • Result.success() when the queue is empty.
  • Result.retry() for transient errors (IOException, HTTP 5xx, 429). WorkManager runs it again after the backoff delay, and the rows stay pending.
  • For permanent errors on one row (most 4xx), mark that row FAILED and continue, so one bad row does not block the rest.

Enqueueing. After every local write, enqueue the worker as unique work:

SettingEffect
setRequiredNetworkType(NetworkType.CONNECTED)The worker only starts when a network connection is available
setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)Retries after about 30 s, 60 s, 120 s...; minimum 10 s, capped at 5 hours
enqueueUniqueWork(name, policy, request)At most one chain of sync work with that name
ExistingWorkPolicy.APPEND_OR_REPLACEA write made during a running sync gets its own run afterwards; a failed chain is replaced

Choosing the policy. REPLACE cancels the existing work even while it runs, which can stop an upload mid-request. KEEP ignores the new request while work is unfinished; Google's Now in Android sample uses it for its start-up sync, and it works for a write queue if the worker keeps reading until no pending rows are left. APPEND runs the new work after the existing work, but if that work failed, the new work fails too; APPEND_OR_REPLACE starts a fresh chain in that case.

Data. Work input and output (Data) is limited to 10 KB, so pass IDs at most and read the payloads from Room inside the worker. A sync worker that drains "all pending rows" needs no input at all.

Notes

  • Write to Room first with a pending state, then enqueue the sync. The UI reads from Room via Flow and never waits for the server.
  • Generate IDs on the device (UUID.randomUUID().toString()) so creating or updating a record by ID is idempotent and retries cannot make duplicates.
  • Enqueue with enqueueUniqueWork. Prefer APPEND_OR_REPLACE, or KEEP with a worker that loops until the queue is empty. REPLACE can cancel an upload that is already running.
  • setRequiredNetworkType(NetworkType.CONNECTED) makes the worker wait for a connection; NetworkType.UNMETERED waits for an unmetered network such as most Wi-Fi.
  • Exponential backoff with a 30 second initial delay is WorkManager's default; the minimum is 10 seconds and the delay is capped at 5 hours. Use runAttemptCount if you want to give up after a number of tries.
  • Return Result.retry() only for transient errors. A 400 or 422 will fail every time, so mark that row FAILED and surface it in the UI.
  • Keep a row pending until the server confirms it. Marking it failed on a timeout drops it from the next run's query.
  • If the user edits a row while its upload is in flight, do not mark the newer edit as synced. A local revision counter checked in the UPDATE ... WHERE handles this.
  • Data is limited to 10 KB per input or output; pass IDs, not payloads.
  • Show sync status from Room (pending rows) or from getWorkInfosForUniqueWorkFlow(name), which emits a list of WorkInfo with states such as ENQUEUED, RUNNING, SUCCEEDED, FAILED, BLOCKED and CANCELLED.

Code example

A note entity with a client-generated ID and a sync state, a DAO for pending rows, an idempotent PUT, and a @HiltWorker that drains the queue with network constraints, exponential backoff and unique work.

import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.io.IOException
import java.util.UUID
import java.util.concurrent.TimeUnit
import kotlinx.serialization.Serializable
import retrofit2.HttpException
import retrofit2.http.Body
import retrofit2.http.PUT
import retrofit2.http.Path
 
enum class SyncState { PENDING, SYNCED, FAILED }
 
@Entity(tableName = "notes")
data class NoteEntity(
    @PrimaryKey val id: String = UUID.randomUUID().toString(), // created on the device
    val text: String,
    val localRevision: Int = 0, // bumped on every local edit
    val syncState: SyncState = SyncState.PENDING,
)
 
@Dao
interface NoteDao {
    @Upsert
    suspend fun upsert(note: NoteEntity)
 
    @Query("SELECT * FROM notes WHERE syncState = 'PENDING' LIMIT :limit")
    suspend fun pending(limit: Int): List<NoteEntity>
 
    // Only marks the row if it was not edited again while uploading
    @Query("UPDATE notes SET syncState = :state WHERE id = :id AND localRevision = :revision")
    suspend fun setState(id: String, revision: Int, state: SyncState)
}
 
@Serializable
data class NoteBody(val text: String)
 
interface NotesApi {
    // PUT to a client-chosen id is idempotent: sending it twice still leaves one note
    @PUT("notes/{id}")
    suspend fun putNote(@Path("id") id: String, @Body body: NoteBody)
}
 
@HiltWorker
class NoteSyncWorker @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    private val dao: NoteDao,
    private val api: NotesApi,
) : CoroutineWorker(appContext, params) {
 
    override suspend fun doWork(): Result {
        while (true) {
            val batch = dao.pending(limit = 50)
            if (batch.isEmpty()) return Result.success()
            for (note in batch) {
                try {
                    api.putNote(note.id, NoteBody(note.text))
                    dao.setState(note.id, note.localRevision, SyncState.SYNCED)
                } catch (e: IOException) {
                    return Result.retry() // offline or timeout: rows stay PENDING
                } catch (e: HttpException) {
                    when {
                        e.code() >= 500 || e.code() == 429 -> return Result.retry()
                        e.code() == 401 -> return Result.failure() // enqueue again after sign-in
                        else -> dao.setState(note.id, note.localRevision, SyncState.FAILED)
                    }
                }
            }
        }
    }
 
    companion object {
        private const val UNIQUE_NAME = "note-sync"
 
        fun enqueue(workManager: WorkManager) {
            val request = OneTimeWorkRequestBuilder<NoteSyncWorker>()
                .setConstraints(
                    Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build()
                )
                .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
                .build()
            workManager.enqueueUniqueWork(UNIQUE_NAME, ExistingWorkPolicy.APPEND_OR_REPLACE, request)
        }
    }
}
 
class NoteRepository(
    private val dao: NoteDao,
    private val workManager: WorkManager,
) {
    suspend fun save(note: NoteEntity) {
        dao.upsert(note.copy(localRevision = note.localRevision + 1, syncState = SyncState.PENDING))
        NoteSyncWorker.enqueue(workManager)
    }
}
  • The worker loops until no pending rows are left, so rows saved while it runs are picked up; APPEND_OR_REPLACE covers the gap after its last query.
  • On IOException the rows stay PENDING and Result.retry() hands the waiting to WorkManager's backoff.
  • setState checks localRevision, so an edit made during the upload stays pending and is sent on the next pass.
  • @HiltWorker needs the Hilt WorkManager setup from the WorkManager lesson (HiltWorkerFactory in the Configuration.Provider).

Run the idea in plain Kotlin

import java.io.IOException

enum class SyncState { PENDING, SYNCED }
data class Note(val id: String, val text: String, var state: SyncState = SyncState.PENDING)

class FakeServer {
  val notes = linkedMapOf<String, String>()
  var failuresLeft = 0          // simulates being offline
  var loseNextResponse = false  // the server saves, but the response never arrives
  fun put(id: String, text: String) {
      if (failuresLeft > 0) { failuresLeft--; throw IOException("network down") }
      notes[id] = text          // keyed by the client's id, so a repeat is harmless
      if (loseNextResponse) { loseNextResponse = false; throw IOException("timeout after save") }
  }
}

// Mirrors doWork(): upload pending rows, retry on IOException
fun doWork(outbox: List<Note>, server: FakeServer): String {
  for (note in outbox.filter { it.state == SyncState.PENDING }) {
      try {
          server.put(note.id, note.text)
          note.state = SyncState.SYNCED
          println("  " + note.id + ": synced")
      } catch (e: IOException) {
          println("  " + note.id + ": " + e.message)
          return "retry"
      }
  }
  return "success"
}

// WorkManager's exponential backoff: initial * 2^(attempt - 1), capped at 5 hours
fun backoffSeconds(initial: Long, attempt: Int): Long = minOf(initial shl (attempt - 1), 5 * 3600L)

fun main() {
  val outbox = listOf(Note("note-a1", "Buy milk"), Note("note-b2", "Call Sam"), Note("note-c3", "Book flight"))
  val server = FakeServer()
  server.failuresLeft = 1
  var attempt = 1
  while (true) {
      println("Run " + attempt + ":")
      if (attempt == 2) server.loseNextResponse = true
      if (doWork(outbox, server) == "success") {
          println("  Result.success()")
          break
      }
      println("  Result.retry(), next run in " + backoffSeconds(30, attempt) + " s")
      attempt++
  }
  println("Server has " + server.notes.size + " notes: " + server.notes.keys)
}

Expected output:

Run 1:
  note-a1: network down
  Result.retry(), next run in 30 s
Run 2:
  note-a1: timeout after save
  Result.retry(), next run in 60 s
Run 3:
  note-a1: synced
  note-b2: synced
  note-c3: synced
  Result.success()
Server has 3 notes: [note-a1, note-b2, note-c3]

In production

Duplicate orders after a timeout
  • Customers of a shopping app reported being charged twice for one order, mostly on poor mobile connections.
  • The server had two order records per affected purchase, each with its own server-generated ID.
  • The upload POST sometimes timed out after the server had already created the order. The worker returned Result.retry() and the retry created a second order.
The fix
  • The app now creates an order ID (a UUID) when the user taps "Buy" and stores it in the pending row.
  • The server treats that ID as an idempotency key: a repeat with the same ID returns the original order instead of creating a new one.
  • A test with a fake server that saves and then drops the response asserts that exactly one order exists after the retry.
Rows stuck as failed after a long offline period
  • Field workers were offline for days and built up hundreds of pending writes.
  • On reconnect, the worker sent them back to back. The server rate-limited the app with 429 responses.
  • The worker treated every non-2xx response as permanent and marked those rows FAILED, so they never synced.
The fix
  • 429 and 5xx responses now return Result.retry(), leaving the rows pending so WorkManager's backoff spaces out the next attempt.
  • The worker uploads in batches of 50 through a batch endpoint instead of one request per row.
  • Only 4xx validation errors mark a row FAILED, and the UI shows those rows with a "tap to fix" state.

Common mistakes

  • Server-generated IDs for offline-created records. A retry after a timeout creates a duplicate. Generate the ID on the device and make the upload idempotent.
  • Using ExistingWorkPolicy.REPLACE for the sync. Every new write cancels a running sync, possibly mid-upload. Use APPEND_OR_REPLACE, or KEEP with a worker that drains until empty.
  • Using plain APPEND. If the existing work failed, every appended request fails too, and nothing syncs until the chain is cleared. APPEND_OR_REPLACE starts a new chain instead.
  • Marking rows failed on transient errors. A timeout or 503 is temporary; keep the row pending and return Result.retry().
  • Returning Result.retry() for permanent errors. A 400 will never succeed, so the worker backs off forever and blocks the rows behind it. Mark that row failed and move on.
  • Forgetting the network constraint. Without setRequiredNetworkType(NetworkType.CONNECTED) the worker runs offline, fails at once, and burns retries.
  • Putting payloads in Data. It is limited to 10 KB and building a larger one throws. Read the pending rows from Room in the worker.
  • Syncing from a plain coroutine. A coroutine launched from the app is gone after process death; WorkManager work is persisted and resumes later.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How would you implement offline writes in an Android app?”

“Which ExistingWorkPolicy would you use for a write-sync worker, and why?”

“How do you prevent duplicate writes when WorkManager retries?”

“What happens to WorkManager work when the app process is killed or the device reboots?”

Quiz

What does ExistingWorkPolicy.REPLACE do when you call enqueueUniqueWork and work with that name is already running?

What is the size limit of a WorkManager Data object?

A sync worker's upload throws an IOException because the connection dropped. What should doWork return?

Which constraint makes a WorkManager job wait for a network connection?

0 of 4 answered

Mini task

15-minute exercise: add a queued write to your app

  1. Add sync columns. In a Room entity, use a client-generated id: String = UUID.randomUUID().toString(), add localRevision: Int and syncState: SyncState (PENDING, SYNCED, FAILED). Add a migration, or fallbackToDestructiveMigration in a debug build only.
  2. Create the worker. Add a CoroutineWorker whose doWork() loops over batches of up to 50 PENDING rows, uploads each with an idempotent call keyed by its id, and marks it SYNCED only if localRevision is unchanged. Return Result.retry() on IOException, 5xx or 429, mark the row FAILED on other 4xx, and return Result.success() when no pending rows are left.
  3. Enqueue after every write. In the repository, after each insert or update, enqueue a OneTimeWorkRequestBuilder request with setRequiredNetworkType(NetworkType.CONNECTED) and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) using enqueueUniqueWork("note-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request).
  4. Test offline. Turn on airplane mode and create three records. They appear in the list immediately and are PENDING in the database (check with Android Studio's App Inspection).
  5. Test sync. Turn airplane mode off. WorkManager starts the worker once the network constraint is met; watch the rows change to SYNCED.

Done condition: the three records created offline end up SYNCED, the server has exactly three records, and killing the app before reconnecting does not stop them from syncing later.

Next: Storing secrets and the Keystore