Android
Seeding a Room Database with a WorkManager Phased Dependency Graph
Naively enqueuing all import workers at once causes foreign-key failures. This post covers a production dependency graph using WorkManager chaining to seed Room in correct order.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 3 of 8WorkManager in Production
- Injecting Dependencies into WorkManager Workers with Hilt
- WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
- Seeding a Room Database with a WorkManager Phased Dependency Graph
- A Base Worker Template for Batched Room Inserts with Retry and Progress
- Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
- Protecting Downloaded Files with a Rename-to-Backup Strategy
- Passing Structured Failure Data Out of a WorkManager Worker
- Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
Seeding a Room database from downloaded JSON files looks simple until you run it and discover that parts fail to insert because their categories don’t exist yet. This post walks through a phased WorkManager dependency graph that enforces insertion order across seven concurrent workers, with linear backoff and Hilt injection throughout.
Prerequisites
Kotlin 2.0, WorkManager 2.11.1, Room 2.7.1, Hilt 2.56, Android minSdk 23.
Familiarity with CoroutineWorker and basic Hilt @Module setup is assumed.
Background
The database has foreign-key relationships: PartsEntity references CategoryEntity
and ColorEntity. CodesEntity references PartsEntity. If all workers start
simultaneously, the parts worker will attempt inserts before categories exist and
either fail silently or throw a constraint violation depending on your onConflict
strategy.
The naive fix is to enqueue workers sequentially one at a time. That works but
leaves parallelism on the table — colors and categories are independent of each
other and can run concurrently. WorkManager’s beginWith().then() chain
expresses exactly this: a directed acyclic graph of work where each phase only
starts when all workers in the previous phase succeed.
Implementation
1. Setup
Workers are constructed by Hilt through HiltWorkerFactory, with the default
WorkManager initializer removed from the manifest. That setup, and why each
piece is required, is covered in
Part 1.
2. Build the dependency graph
fun writeAllToDatabaseWithDependencies() { // Phase 1: Foundation data — independent, run in parallel val colorsWork = buildWorker<WriteColorsToDatabase>(WorkerTags.DATABASE_COLORS_WORKER) val categoryWork = buildWorker<WriteCategoryToDatabase>(WorkerTags.DATABASE_CATEGORY_WORKER)
// Phase 2: Depends on colors + categories being present val partsWork = buildWorker<WritePartsToDatabase>(WorkerTags.DATABASE_PART_WORKER) val gearWork = buildWorker<WriteGearToDatabase>(WorkerTags.DATABASE_GEAR_WORKER) val minifigureWork = buildWorker<WriteMinifigureToDatabase>(WorkerTags.DATABASE_MINIFIGURE_WORKER)
// Phase 3: Depends on parts val codesWork = buildWorker<WriteCodesToDatabase>(WorkerTags.DATABASE_CODE_WORKER)
workManager .beginWith(listOf(colorsWork, categoryWork)) // parallel .then(listOf(partsWork, gearWork, minifigureWork)) // parallel after phase 1 .then(codesWork) // after phase 2 .enqueue()}beginWith(list) starts all workers in the list concurrently. .then(list)
starts its list only after every worker in the previous step reaches
Result.success(). If any worker fails or is cancelled, WorkManager marks every
downstream request FAILED (or CANCELLED) without running it.
3. Worker builder with backoff
private inline fun <reified W : ListenableWorker> buildWorker(tag: String): OneTimeWorkRequest = OneTimeWorkRequestBuilder<W>() .addTag(tag) .setBackoffCriteria(BackoffPolicy.LINEAR, 1, TimeUnit.MINUTES) .build()BackoffPolicy.LINEAR means the first retry waits 1 minute, the second 2, and
so on. BackoffPolicy.EXPONENTIAL grows faster — use it when the failure mode
is likely a server outage rather than a missing local file.
4. A concrete worker
Each phase worker is a @HiltWorker that only needs three things from its
subclass: a filename, a resource key, and a processFile implementation.
@HiltWorkerclass WritePartsToDatabase @AssistedInject constructor( @Assisted context: Context, @Assisted workParameters: WorkerParameters, private val partsDao: PartsDao, @StickyNotification notificationManager: NotificationManagerCompat, @StickyNotification notificationBuilder: NotificationCompat.Builder, progressRepository: ProgressRepository) : BaseWriteToDatabase( context, workParameters, notificationManager, notificationBuilder, progressRepository, notificationId = NotificationIds.PARTS) { override val fileName = "parts.json" override val resourceKey = "parts"
override suspend fun processFile(jsonFile: File): Int { val parts: PartsResponse = jsonFile.convertJsonToDataClass() val total = parts.size var totalInserted = 0
for ((index, batch) in parts.toEntity().chunked(BATCH_SIZE).withIndex()) { if (isStopped) break try { partsDao.insertAll(batch) totalInserted += batch.size } catch (e: Exception) { Timber.w(e, "[$resourceKey] Batch $index failed") } progressRepository.notifyProgressUpdate(totalInserted, total, resourceKey) showProgressNotification(totalInserted, total) } return totalInserted }}5. Periodic download trigger
The data files are refreshed on a 1-day period, seeding the dependency graph after each successful download:
fun downloadUpdate() { val inventory = PeriodicWorkRequestBuilder<DownloadFilesWorker>(1, TimeUnit.DAYS) .addTag(WorkerTags.DOWNLOAD_INVENTORY_WORKER) .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresStorageNotLow(true) .build() ) .build()
workManager.enqueueUniquePeriodicWork( WorkerTags.UNIQUE_WORKER_INVENTORY, ExistingPeriodicWorkPolicy.UPDATE, inventory )}ExistingPeriodicWorkPolicy.UPDATE updates the existing periodic work in place
(new constraints, new interval) without resetting its schedule. KEEP ignores
the new request entirely, and CANCEL_AND_REENQUEUE throws the old work away
and starts the period again from now.
Testing
Observe work state in tests using WorkManager.getWorkInfosByTag() or the
TestListenableWorkerBuilder from work-testing:
./gradlew connectedAndroidTest --tests "*.WorkManagerDependencyTest"
BUILD SUCCESSFUL in 14s3 instrumented tests completedVerify phase ordering deterministically with WorkManagerTestInitHelper and a
SynchronousExecutor: enqueue the chain with a fake Phase 1 worker that
returns Result.failure(), then assert that every Phase 2 and Phase 3 request
ends in FAILED without having run. A second test with a successful Phase 1
asserts that Phase 2 moves from BLOCKED to SUCCEEDED.
Pitfalls
Production considerations
The 1,000-row batch size is a safe default, not a tuned number. On devices with
constrained RAM (minSdk 23 targets go back to 2015 hardware), deserialising a
large JSON file in one shot can cause OOM before chunking even starts. Stream
the JSON with a library like Moshi’s JsonReader if your files exceed ~10MB.
If Phase 2 workers are slow, profile before assuming it is the insert rate. The bottleneck is usually JSON deserialisation, not SQLite. Generated serializers — kotlinx.serialization’s compiler plugin, or Moshi with KSP codegen — are meaningfully faster than Gson’s reflection on large payloads.
Wrapping up
You now have a dependency-ordered WorkManager pipeline that runs foundation data
in parallel, gates dependent imports behind it, and retries gracefully on
transient failures. The full source lives in WorkManagerUtil.kt and
BaseWriteToDatabase.kt.
Part 4 covers the
BaseWriteToDatabase contract in detail: backup file recovery, per-batch
progress notifications, and the isStopped guard that stops an import
cleanly when the work is cancelled.
Going deeper
Data flows between phases. By default a worker’s output Data is passed
as input to its dependents. With several parents, the outputs are merged by an
InputMerger: OverwritingInputMerger (the default, last writer wins per
key) or ArrayCreatingInputMerger, which collects every parent’s value for a
key into an array. Set it on the child with setInputMerger(...). This is how
a Phase 3 worker can receive row counts from all three Phase 2 workers.
Don’t let one failure kill the whole graph. A chain fails closed. If
gear failing should not stop codes from being imported, either have gear
return success() with an error flag in its output, or split independent
branches into separate unique chains. Choose deliberately: failing closed is
right when downstream data would be corrupt without upstream data.
Re-seeding safely. Running the graph again after a fresh download must not
duplicate rows. Use OnConflictStrategy.REPLACE (or @Upsert, Room 2.5+)
keyed on the source’s natural ID, and wrap a full refresh in a single
“generation” marker so the UI never reads a half-old, half-new catalogue.
Note that REPLACE deletes and reinserts the row, which cascades through
ON DELETE CASCADE foreign keys; @Upsert updates in place and does not.
Expedited work for the first launch. On first install the user is waiting
on this import. setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
on the Phase 1 requests asks the system to start them immediately, and falls
back to normal scheduling when the app is out of expedited quota.