Android Background Work: WorkManager Deep Dive
How WorkManager actually schedules work — constraints, unique work, chains, expedited jobs, and the failure modes that show up in production apps.
By Velloreth
Android has been tightening background execution limits for a decade: Doze, App Standby, background service restrictions, and per-app quotas for expedited jobs. WorkManager is the answer to that whole trajectory — a Jetpack library that schedules work with constraints, survives process death and reboots, and picks the right underlying scheduler for each API level.
This post goes past the getting-started tutorial: how scheduling actually works, the patterns that prevent production bugs, and the failure modes that are easy to ship and hard to debug.
What WorkManager is for
The first decision is whether WorkManager is the right tool at all.
| Use case | Tool |
|---|---|
| Upload a file after the user taps “Send” | Coroutine or WorkManager (expedited if it must survive process death) |
| Sync the inbox every 24 hours | PeriodicWorkRequest |
| Compress a 2 GB video export | Foreground service (WorkManager’s 10-minute deadline will kill it) |
| Retry a failed API call when network returns | WorkManager with a network constraint |
| Refresh a token while the app is open | Plain coroutine in the repository |
The dividing line is persistence and constraints. If the work must run when the app is dead, after a reboot, or only when conditions are met, it belongs in WorkManager. If it only matters while the app is on screen, a coroutine is simpler and has no quota.
Constraints: what gates execution
A Constraints object declares the conditions under which work may start. All constraints must be satisfied simultaneously:
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // Wi-Fi only
.setRequiresCharging(true)
.setRequiresBatteryNotLow(true)
.setRequiresStorageNotLow(true)
.build()
The network types matter more than they look:
| NetworkType | Meaning |
|---|---|
NOT_REQUIRED | Any network, or none — runs regardless |
CONNECTED | Any network is up |
UNMETERED | Wi-Fi or Ethernet — not cellular |
METERED | Cellular specifically (rarely what you want) |
NOT_ROAMING | Any network, but not while roaming |
TEMPORARILY_UNMETERED | Unmetered for now (Android 10+) — useful for large downloads that can wait for Wi-Fi |
One thing that catches people: if a constraint becomes unmet while the worker is running, the system stops it and reschedules. A worker uploading over Wi-Fi that loses Wi-Fi mid-upload is stopped, not allowed to fail gracefully. Design workers to be resumable — checkpoint progress to a database, and let the next run pick up where the last one left off.
One-time and periodic work
One-time work is a OneTimeWorkRequest; periodic work is a PeriodicWorkRequest. The builder takes your worker class, plus optional backoff, constraints, and input data:
val syncRequest = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.setInputData(workDataOf("userId" to userId))
.build()
WorkManager.getInstance(context).enqueue(syncRequest)
Periodic work has a minimum interval of 15 minutes — shorter intervals are clamped. More importantly, periodic work is not a cron job. The system batches and defers: a daily job might run a few hours late, and if constraints are never met within a window, that run is skipped entirely. Build periodic workers to be idempotent and to fetch a full snapshot rather than assuming a delta.
Unique work: the pattern that prevents duplicate jobs
The most common WorkManager bug is enqueuing the same logical job twice — once on app start, once on a pull-to-refresh, plus once more after a process death. Unique work names solve this:
WorkManager.getInstance(context).enqueueUniqueWork(
"sync_inbox",
ExistingWorkPolicy.REPLACE, // or KEEP, APPEND, APPEND_OR_REPLACE
syncRequest
)
The policies, for one-time work:
| Policy | Behavior |
|---|---|
REPLACE | Cancel the existing chain, run the new one |
KEEP | Ignore the new request if the old one is still pending |
APPEND | Run the new work after the existing chain finishes; if the chain fails or is cancelled, the new work is too |
APPEND_OR_REPLACE | Append, but run anyway if the existing chain failed or was cancelled |
For periodic work, ExistingPeriodicWorkPolicy has REPLACE and KEEP (and a newer UPDATE that changes the spec of the running instance without cancelling it). The right default for a recurring sync is KEEP — you do not want a second instance because the user opened the app twice.
The subtle APPEND behavior is worth internalizing: it creates a parent-child dependency. If the first upload fails, the appended second upload will not run. That is usually what you want (“do not start the next batch until this one lands”) and occasionally not (in which case APPEND_OR_REPLACE).
Chains and unique chains
WorkManager can sequence workers: each step runs after the previous one succeeds, and a failure cancels the rest of the chain.
val download = OneTimeWorkRequestBuilder<DownloadWorker>().build()
val unzip = OneTimeWorkRequestBuilder<UnzipWorker>().build()
val index = OneTimeWorkRequestBuilder<IndexWorker>().build()
WorkManager.getInstance(context)
.beginWith(download)
.then(unzip)
.then(index)
.enqueue()
Data flows through the chain: each worker’s output Data becomes the next worker’s input. Combine this with unique chains (beginUniqueWork) when only one chain of a given name should exist at a time — “one export at a time,” for example:
WorkManager.getInstance(context)
.beginUniqueWork(
"export_${exportId}",
ExistingWorkPolicy.APPEND_OR_REPLACE,
download
)
.then(unzip)
.then(index)
.enqueue()
Note the name includes the exportId: two different exports can run concurrently, but retries of the same export do not stack.
Expedited work and the quota
Expedited work (WorkManager 2.7+) is for work that is important to the user and short — a message send, a photo upload started from a foreground action. It runs ahead of normal work and is less affected by Battery Saver and Doze:
val sendRequest = OneTimeWorkRequestBuilder<SendWorker>()
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager.getInstance(context).enqueue(sendRequest)
The catch is the quota. Each app gets a limited amount of expedited execution time per window. When the quota is exhausted, the OutOfQuotaPolicy decides: RUN_AS_NON_EXPEDITED_WORK_REQUEST demotes the job to normal scheduling; DROP_WORK_REQUEST cancels it. Expedited workers on Android 12+ run as expedited jobs in JobScheduler; on older versions WorkManager falls back to a foreground service — which means your worker must implement getForegroundInfo() for that path.
The practical rule: expedited work for things the user is waiting on right now, normal work for everything else. If you expedite every sync, the quota exhausts and your actual user-initiated sends get demoted.
The 10-minute deadline
One-time workers get roughly 10 minutes of execution time per run. If the worker has not returned by then, the system stops it and reschedules with backoff. Periodic workers get one execution window per interval, with the same overall limit.
This forces a design pattern for long tasks: chunk and re-enqueue.
class ExportWorker(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val startOffset = inputData.getInt("offset", 0)
val batch = repository.exportBatch(startOffset, limit = 500)
val nextOffset = startOffset + batch.size
return if (repository.hasMore(nextOffset)) {
val next = OneTimeWorkRequestBuilder<ExportWorker>()
.setInputData(workDataOf("offset" to nextOffset))
.build()
WorkManager.getInstance(applicationContext)
.enqueueUniqueWork(
"export_${exportId()}",
ExistingWorkPolicy.APPEND,
next
)
Result.success()
} else {
Result.success()
}
}
}
Each run does a bounded slice of work, checkpoints the offset in the input Data (or a database row), and appends the next slice to the same unique chain. The user sees continuous progress; the system never has to kill a runaway worker.
Observing and cancelling
Work info is observable — useful for showing upload progress in the UI:
WorkManager.getInstance(context)
.getWorkInfosForUniqueWorkLiveData("sync_inbox")
.observe(lifecycleOwner) { infos ->
val isRunning = infos.any { it.state == WorkInfo.State.RUNNING }
val failed = infos.any { it.state == WorkInfo.State.FAILED }
// update UI
}
You can also attach a Progress to a running worker with setProgressAsync and observe it, or cancel by ID, by name, or by tag. Tags group related work (“all export workers”) and make bulk cancellation possible without tracking individual IDs.
Failure modes that show up in production
A short list of the bugs worth knowing before they find you:
Force-stop. If the user force-stops your app (swipe away from Recents on some OEMs, or via Settings), WorkManager does not run until the user manually launches the app again. There is no API around this; it is a platform behavior. If your app’s core function is background sync, this is a reason to also offer a widget or a launcher shortcut that starts the app.
OEM battery killers. Chinese and some other OEM skins aggressively kill background processes beyond what AOSP does. WorkManager survives more than a raw Service, but a user who has whitelisted your app from battery optimization is still the most reliable fix. The REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission exists, but Play policy restricts its use — read the policy before requesting it.
Uniqueness across processes. If your app has multiple processes, use enableMultiInstanceInvalidation() on the database and be deliberate about which process enqueues work. Two processes calling enqueueUniqueWork with REPLACE can thrash each other.
Backoff misconfiguration. BackoffPolicy.LINEAR with a 10-second minimum is fine for a quick retry; EXPONENTIAL with the default 30 seconds means the fifth retry is 15 minutes out. For work that “must eventually succeed,” exponential backoff with a cap, plus a user-visible “retry now” button that enqueues fresh work, beats waiting passively.
Input Data size. The total size of input and output Data is capped (roughly 10 KB across the chain). Passing a large URI or bitmap through Data fails silently in some versions. Pass identifiers; load payloads inside the worker.
A reference shape
Putting it together, a production sync typically looks like this:
object SyncScheduler {
fun scheduleInboxSync(context: Context, force: Boolean = false) {
val request = OneTimeWorkRequestBuilder<InboxSyncWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
"inbox_sync",
if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,
request
)
}
}
The worker itself loads the last-sync cursor from the database, fetches deltas from the network, writes them in one @Transaction, and returns Result.success() — or Result.retry() when the error is transient, letting backoff handle the rest. The UI observes the Room Flow, not the Worker; the Worker is just another writer.
WorkManager’s value is not that it runs background tasks — Services and JobScheduler did that for years. It is that it gives you one durable, testable abstraction over all of it: constraints you can reason about, uniqueness that prevents duplicate work, chains that encode dependencies, and observability that lets the UI tell the user what is actually happening.