← All notes

Android

Protecting Downloaded Files with a Rename-to-Backup Strategy

An interrupted download leaves a corrupt or missing file. Renaming the previous version to .bak before the new download starts gives the database seeding worker a fallback — without any network retry.

Published
Reading
5 min
Author
Fidelis Uwem Joseph
Series · Part 6 of 8WorkManager in Production
  1. Injecting Dependencies into WorkManager Workers with Hilt
  2. WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
  3. Seeding a Room Database with a WorkManager Phased Dependency Graph
  4. A Base Worker Template for Batched Room Inserts with Retry and Progress
  5. Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
  6. Protecting Downloaded Files with a Rename-to-Backup Strategy
  7. Passing Structured Failure Data Out of a WorkManager Worker
  8. Bridging WorkManager and Compose UI via a Listener-based ProgressRepository

← Part 5Series overviewPart 7 →

When a download is interrupted midway, the destination file is either truncated or absent. The next app launch triggers a retry, but WorkManager with linear backoff means that retry may not happen for minutes. A simpler recovery path: rename the existing file to .bak before the download starts. If the new download fails, the worker finds the backup and uses it. The user sees stale data instead of an error screen.

Prerequisites

WorkManager 2.11.1. Familiarity with the DownloadFilesWorker from Part 5 and BaseWriteToDatabase from Part 4.

Background

The file pipeline has two independent processes: Downloader (called from DownloadFilesWorker) writes new files to getExternalFilesDir("brickwork"), and BaseWriteToDatabase subclasses read from the same directory. If the download is interrupted, the base worker’s doWork() finds a missing main file and either retries or fails.

The backup strategy closes that gap: before a new download starts, the existing file is renamed to filename.json.bak. If the main file is present when the worker runs, it is used. If it is absent but the backup exists, the backup is copied back and processing continues. Only if both are absent does the worker retry or fail.

This is an implicit contract between Downloader and BaseWriteToDatabase. This post makes it explicit.

Implementation

1. Downloader — rename before download

data/downloadmanager/Downloader.kt
override fun downloadFile(url: String): Long {
val dm = downloadManager ?: run {
Timber.e("DownloadManager unavailable")
return DOWNLOAD_FAILED
}
val dest = destFile // e.g. categories.json
if (dest.exists()) {
val backup = File(dest.parent, "$fileName.bak") // categories.json.bak
val renamed = dest.renameTo(backup)
if (!renamed) Timber.w("Failed to backup: $fileName")
}
val request = DownloadManager.Request(url.toUri())
.setMimeType(mimeTypeString)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setTitle(title)
.setDestinationUri(dest.toUri())
return try {
dm.enqueue(request)
} catch (e: IllegalArgumentException) {
// Download Manager system app disabled by the user
Timber.e(e, "DownloadManager disabled")
DOWNLOAD_FAILED
}
}

renameTo() is atomic on most filesystems when source and destination are on the same volume — which they are here, since both dest and backup are in the same getExternalFilesDir() directory. The rename either succeeds fully or not at all. No partial state.

2. BaseWriteToDatabase — check main, fall back to backup

data/workmanager/BaseWriteToDatabase.kt
override suspend fun doWork(): Result {
val mainFile = brickworkFile(fileName) // categories.json
val backupFile = brickworkFile("$fileName.bak") // categories.json.bak
return try {
when {
mainFile.exists() -> processAndSucceed(mainFile)
backupFile.exists() -> restoreFromBackup(backupFile, mainFile)
else -> handleMissingFile()
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Timber.e(e, "[$resourceKey] Unhandled error")
Result.failure()
}
}

The three branches map to three states of the file system:

StateBranchOutcome
Download succeededmainFile.exists()Process normally
Download failed or interruptedbackupFile.exists()Restore and process
First install, no data yetelseRetry up to 3 times

3. Backup restoration

data/workmanager/BaseWriteToDatabase.kt
private suspend fun restoreFromBackup(backup: File, main: File): Result {
Timber.i("[$resourceKey] Main missing — restoring from backup")
return try {
backup.copyTo(main, overwrite = true)
Timber.i("[$resourceKey] Backup restored")
processAndSucceed(main)
} catch (e: Exception) {
Timber.e(e, "[$resourceKey] Backup restore failed")
Result.failure()
}
}

copyTo() is used here (not renameTo()) because the backup should remain intact after restoration. If processAndSucceed(main) throws after the copy, the backup is still available for a subsequent worker run. The backup is only removed the next time Downloader.downloadFile() renames it for the next successful download cycle.

4. The full file lifecycle

First install:
[no files]
→ DownloadFilesWorker runs → downloads categories.json
→ BaseWriteToDatabase: mainFile.exists() → process
Next sync:
categories.json exists
→ Downloader renames categories.json → categories.json.bak
→ DownloadManager downloads new categories.json
→ BaseWriteToDatabase: mainFile.exists() → process
Interrupted sync:
categories.json.bak exists, categories.json missing
→ BaseWriteToDatabase: backupFile.exists() → restore + process
First install, download fails:
[no files]
→ handleMissingFile() → Result.retry() x3 → Result.failure()

5. File path helper

Both Downloader and BaseWriteToDatabase use the same directory constant:

data/downloadmanager/Downloader.kt
private const val BRICKWORK_DIR = "brickwork"
private val destFile: File
get() = File(context.getExternalFilesDir(BRICKWORK_DIR), fileName)
data/workmanager/BaseWriteToDatabase.kt
private const val BRICKWORK_DIR = "brickwork"
private fun brickworkFile(name: String): File =
File(applicationContext.getExternalFilesDir(BRICKWORK_DIR), name)

Testing

Terminal window
./gradlew connectedAndroidTest --tests "*.BackupRestoreTest"
BUILD SUCCESSFUL in 9s
3 instrumented tests completed

Simulate an interrupted download in tests by creating a .bak file without a corresponding main file and asserting that doWork() returns Result.success() and that the main file exists after the worker completes.

Pitfalls

Production considerations

Backup files accumulate if downloads fail repeatedly. On a first install with no network, there are no backups to accumulate. On a sync cycle, there is exactly one backup per file (the previous version). The storage overhead is one extra copy of each JSON file — acceptable for inventory data that is typically a few megabytes per file.

If storage is a concern, delete the .bak file explicitly after a successful processAndSucceed(). This requires adding a cleanup step to BaseWriteToDatabase after processing, but eliminates the redundant copy for the normal-path case.

Wrapping up

You now have a two-stage resilience strategy: Downloader renames before downloading, BaseWriteToDatabase falls back to the renamed copy if the main file is absent. The user sees stale data after a failed sync rather than an empty or broken state. No network retry required for the recovery path.

Going deeper

Existence is not validity. Every branch above asks “does the file exist?”, but the real question is “is this a complete, parseable file?”. DownloadManager writes into the destination path as bytes arrive, so a file can exist and still be truncated, for example if the device rebooted mid-download. In this pipeline seeding only starts after every download reports STATUS_SUCCESSFUL, which protects the normal path. But a manual re-seed, or a retry after a crash, can still meet a half-written file. The robust version treats a parse failure on the main file exactly like a missing file: log it, delete the bad file, and fall through to the backup.

The inverse pattern is safer: write to a temp file, then rename. Backup-then-download leaves a window where the main path holds a partial file. The textbook alternative never touches the good file until the new one is proven:

  1. Download to categories.json.part.
  2. Verify it: expected size or SHA-256 from the backend, and that it parses.
  3. renameTo("categories.json"), an atomic replace on the same filesystem.

At every moment categories.json is either the complete old version or the complete new one. No restore step is needed, and readers never see a partial file. Backup-first is still useful as a quick retrofit when you can’t change the downloader’s destination, which is the situation this post started from.

Cleaning up. If you adopt the temp-file approach, delete stale .part files at the start of each sync. They are the remains of downloads that were interrupted before verification.