Design a large file upload and download manager
The question
Design a large file upload and download manager for an Android app. Files can be several gigabytes. Transfers must survive process death, show live progress, and resume after a network drop. Walk me through the client architecture.
Clarify before you design:
- What is the expected file-size range, and is there a hard upper bound the client must handle?
- Are uploads and downloads symmetric, or does one direction dominate (for example, a photo-backup app uploads but rarely downloads)?
- Does the server support resumable uploads (it can report how many bytes it has) and HTTP
Rangedownloads, or do we need to design the API contract too? - Should transfers run in the background when the app is closed, or only while the user is in the app?
- Does the user start each transfer, or does the app start them on its own (for example, automatic backup)? This decides which Android background APIs are allowed.
- What is the concurrency policy: one transfer at a time, or a small pool of parallel transfers?
- Do we need to support pause and cancel, and what happens to partial data?
- Is the file kept in app-specific storage, or must it end up in shared storage (
MediaStore) where other apps can see it?
Requirements
Functional
- Enqueue an upload or download with a local file and a remote URL. The transfer is saved in Room so it survives process death.
- Uploads are sent in chunks. The server acknowledges each chunk, and a resumed upload continues from the byte offset the server reports.
- Downloads resume with an HTTP
Rangerequest from the number of bytes already on disk. - Show live progress (bytes transferred / total bytes) in the UI and in a notification.
- Pause, resume and cancel a transfer. Partial data is kept or deleted depending on direction and action.
- Verify a finished download against a SHA-256 hash the server provides.
- A failed transfer has a retry action that continues from the saved offset instead of starting from zero.
Non-functional
- Battery: transfers run only when a network constraint is met (unmetered only by default, or the user's choice). No polling loops or wake locks of our own.
- Memory: never load a multi-gigabyte file into a
ByteArray. Stream file data through Okio or a small reused buffer. - Offline: the queue and per-transfer state are readable and writable without a network. Queued transfers show a "waiting for network" label.
- Privacy: file paths and remote URLs live in Room, not in logcat, crash reports or analytics events.
- Progress: the UI should feel live (a few updates per second at most) without one update per network read.
- Storage: app-specific storage by default. Shared storage through
MediaStoreonly when the user wants the file visible to other apps.
Out of scope
- Server-side storage, CDN, or object-store design. We assume the API contract exists and focus on the Android client.
- Encryption at rest for the local file cache. Assume the OS-level file permissions are sufficient.
- Peer-to-peer transfer. This is a client-to-server design.
High-level architecture
The client has three layers: UI, domain, and data.
UI layer. A Compose screen lists active and finished transfers. Each row shows a progress bar, file name, and status. The screen collects a StateFlow<TransfersUiState> from a TransfersViewModel with collectAsStateWithLifecycle.
Domain layer. A TransferManager exposes enqueueUpload, enqueueDownload, pause, resume, cancel, and retry. It owns the per-transfer state machine: QUEUED -> IN_PROGRESS -> COMPLETED, with side exits to PAUSED, FAILED and CANCELLED. WorkManager has no pause, so pause means "cancel the work, keep the partial data, mark the row PAUSED", and resume means "enqueue new work that continues from the saved offset".
Data layer. TransferRepository stores each transfer in Room. Room is the single source of truth for transfer state: the UI observes a Room Flow, and the worker writes to Room. Each transfer becomes unique work named transfer-<id>, enqueued with ExistingWorkPolicy.KEEP so a double tap does not start a second copy. The worker is a CoroutineWorker. It streams the file over OkHttp, saves the committed offset to Room after each chunk, and returns Result.retry() on transient errors so WorkManager reschedules it with exponential backoff.
For downloads, the worker sends Range: bytes=<bytes on disk>- and appends the 206 Partial Content body to the file. For uploads, the worker first asks the server how many bytes it has, then sends chunks from that offset.
State flow. User taps download -> ViewModel calls TransferManager.enqueueDownload -> repository inserts a Room row and enqueues unique work -> WorkManager runs the worker once the network constraint is met -> the worker streams data and updates transferredBytes in Room -> the Room Flow emits -> the ViewModel maps rows to UI state -> Compose redraws.
Foreground work. A worker run normally gets about 10 minutes, and Doze can defer it. For a long transfer the worker calls setForeground() with a ForegroundInfo, and WorkManager runs it inside its own foreground service with our progress notification. This lets the run continue past the normal limit. It does not make the transfer survive process death; WorkManager's persisted request does that. On Android 14+ (target 34) the ForegroundInfo must carry a service type, here FOREGROUND_SERVICE_TYPE_DATA_SYNC, declared on WorkManager's SystemForegroundService in the manifest, with the FOREGROUND_SERVICE_DATA_SYNC permission. On Android 15, dataSync foreground services get 6 hours per 24 hours, so very large transfers must be resumable anyway.
User-initiated data transfer jobs. Android 14 added user-initiated data transfer (UIDT) jobs for exactly this case: long transfers the user starts. They are plain JobScheduler jobs built with JobInfo.Builder.setUserInitiated(true) and a required network, need the RUN_USER_INITIATED_JOBS permission, must be scheduled while the app is visible, and call JobService.setNotification() once running. There is no Jetpack wrapper for them, so the official advice is UIDT on Android 14+ and WorkManager with setForeground() on older versions. Automatic transfers the user did not start (background backup) stay on WorkManager.
| Component | Responsibility |
|---|---|
| TransferManager (domain) | Owns the transfer state machine. Exposes enqueue, pause, resume, cancel, retry. Writes rows through the repository and schedules work. |
| TransferRepository (data) | Persists transfers in Room, the single source of truth. Exposes a Flow of rows. Enqueues and cancels unique work per transfer. |
| UploadWorker / DownloadWorker | CoroutineWorker subclasses. Stream chunks, save the committed offset to Room, update the foreground notification, and return Result.success(), Result.retry() or Result.failure(). |
| TransferApi (network) | Retrofit interface: upload status (bytes the server has), chunk upload with Content-Range, and ranged download with Range and @Streaming. Upload bodies are streaming RequestBody instances. |
| TransferNotifications | Creates the IMPORTANCE_LOW channel at app start, builds the progress notification with a cancel action, and posts a separate "done" or "failed" notification when a transfer ends. |
| TransfersViewModel | Maps Room rows to TransfersUiState. Calls TransferManager. One-off results (such as "download failed, tap to retry") are fields in the UI state that the screen clears after showing them. |
| IntegrityChecker | Computes SHA-256 of a finished download in streaming blocks and compares it with the server's hash. A mismatch deletes the file and marks the transfer FAILED. |
Data model and API
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Streaming
@Entity(
tableName = "transfers",
indices = [Index(value = ["status", "createdAt"])]
)
data class TransferEntity(
@PrimaryKey val id: String,
val direction: Direction,
val localPath: String,
val remoteId: String,
val totalBytes: Long,
val transferredBytes: Long,
val status: TransferStatus,
val sha256: String?, // expected hash for downloads, from the server
val etag: String?, // for If-Range on resumed downloads
val createdAt: Long,
val updatedAt: Long
)
enum class Direction { UPLOAD, DOWNLOAD }
enum class TransferStatus {
QUEUED, IN_PROGRESS, PAUSED, COMPLETED, FAILED, CANCELLED
}
interface TransferApi {
// How many bytes of this upload the server has committed
@GET("uploads/{id}")
suspend fun uploadStatus(@Path("id") id: String): UploadStatus
@POST("uploads/{id}/chunks")
suspend fun uploadChunk(
@Path("id") id: String,
@Header("Content-Range") range: String, // "bytes 0-5242879/1073741824"
@Body chunk: RequestBody
): UploadStatus
// @Streaming stops Retrofit from reading the whole body into memory
@Streaming
@GET("downloads/{id}")
suspend fun download(
@Path("id") id: String,
@Header("Range") range: String, // "bytes=5242880-"
@Header("If-Range") ifRange: String? // the ETag; a changed file returns 200
): Response<ResponseBody>
}
data class UploadStatus(val committedOffset: Long, val done: Boolean)A streaming upload body for one chunk. OkHttp may call writeTo more than once (for example when it retries a request), so it reopens the file each time instead of holding a stream:
import java.io.File
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.buffer
import okio.source
class FileSliceBody(
private val file: File,
private val offset: Long,
private val length: Long
) : RequestBody() {
override fun contentType(): MediaType = "application/octet-stream".toMediaType()
override fun contentLength(): Long = length
override fun writeTo(sink: BufferedSink) {
file.source().buffer().use { source ->
source.skip(offset)
sink.write(source, length)
}
}
}Deep dives
Resumable chunked transfers
Neither side holds the whole file in memory. For uploads, the worker starts every run by asking the server for its committed offset (uploadStatus). It does not trust its own count, because a chunk can reach the server even when the response is lost. Then it sends chunks from that offset: each one a POST with Content-Range: bytes start-end/total and a FileSliceBody. The server stores the chunk and returns the new committed offset. The worker saves that offset to Room so the UI and a later run can see it. If you can choose the protocol, prefer an existing one (tus, or your storage provider's resumable or multipart upload) over a custom one.
For downloads, the bytes already on disk are the offset. The worker sends Range: bytes=<file length>- with If-Range: <etag>. The responses it must handle:
206 Partial Content: append the body to the file.200 OK: the server ignored the range or the file changed (the ETag no longer matches). Truncate the local file and start again from zero.416 Range Not Satisfiable: the local file is already complete or larger than the remote one. Check the size and hash.
If the connection drops, OkHttp throws an IOException. The worker catches only IOException and HttpException, saves the offset, and returns Result.retry(). CancellationException is never caught, so pause, cancel and WorkManager's own stops work. The next run reads the offset again and continues.
Chunk size is a trade-off. With a streaming body, memory stays small whatever the chunk size. Small chunks mean more requests and more per-request overhead. Large chunks mean fewer requests, but a failure throws away more work. Something in the low megabytes is a common starting point, but storage providers set their own rules (S3 multipart parts must be at least 5 MiB except the last; Google Cloud Storage chunks must be multiples of 256 KiB), so follow the server's contract.
The client depends on two server guarantees: a chunk is committed atomically (never half-visible), and the server reports its committed offset exactly. With those, re-sending from the reported offset is always safe.
WorkManager scheduling and foreground work
Each transfer is a OneTimeWorkRequest for a CoroutineWorker, enqueued with enqueueUniqueWork("transfer-" + id, ExistingWorkPolicy.KEEP, request). The constraints use setRequiredNetworkType(NetworkType.UNMETERED) for the Wi-Fi-only default, or NetworkType.CONNECTED when the user allows mobile data. setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) sets the retry delay. WorkManager has no retry cap, so the worker checks runAttemptCount and returns Result.failure() after its own limit.
The worker calls setForeground() early in doWork(), while the user has just started the transfer, because on Android 12+ starting a foreground service from the background is mostly blocked and the call can fail. It calls setForeground() again with an updated notification as progress changes.
setExpedited() is not the tool here. Expedited work is for short, important tasks that finish within a few minutes, and it runs on a limited quota based on the app's standby bucket. A multi-gigabyte transfer is long-running work: setForeground() with WorkManager, or a UIDT job on Android 14+.
On a transient failure (IOException, 5xx, 429) the worker returns Result.retry(). On a permanent failure (404, 403, an expired upload session) it returns Result.failure(), and the row becomes FAILED with a retry button.
Concurrency: WorkManager can run several unique works at the same time. For a hard cap of N parallel transfers, keep extra transfers QUEUED in Room and enqueue work only for the first N. When a worker finishes, the repository enqueues work for the next queued row.
Progress, notifications, and UI updates
The worker writes transferredBytes to Room after each chunk. That one write serves resume, the UI and the reconciliation after a crash. The screen observes the Room Flow, and the ViewModel applies sample(500) so the UI gets at most two updates per second. Use sample, not debounce: debounce only emits after the flow has been quiet for the timeout, so a steady stream of progress would show nothing until the transfer stopped.
setProgress() with Data is the other option, observed through getWorkInfosForUniqueWorkFlow("transfer-" + id) or getWorkInfoByIdFlow(workId). It is fine for a screen that watches one transfer while it runs. But progress Data is not saved for the next attempt, and it is empty once the work has finished, so it cannot be the source of truth. WorkInfo is still useful for state: a row whose work is ENQUEUED but not running is "waiting for network".
The notification channel is created at app start with IMPORTANCE_LOW, and the builder uses setOnlyAlertOnce(true), so progress updates make no sound. A cancel action comes from WorkManager.createCancelPendingIntent(id). Update the notification only when the whole percentage changes: the system drops notification updates posted too often, and each one costs battery. The foreground notification disappears when the work ends, so post a separate "done" or "failed" notification. On Android 13+ notifications need POST_NOTIFICATIONS; if it is denied, the work still runs but the notification is hidden from the drawer.
Pause and cancel: the ViewModel calls TransferManager.pause(id) or cancel(id), which calls cancelUniqueWork("transfer-" + id). The worker's coroutine is cancelled, use blocks close the file and the stream, and the repository sets PAUSED or CANCELLED. A paused download keeps its partial file. A cancelled download deletes it. A cancelled upload leaves the partial server-side data for the server to expire.
Integrity, storage, and cleanup
After a download completes, the IntegrityChecker reads the file in 64 KiB blocks through a FileInputStream, feeds each block to a MessageDigest for SHA-256 on Dispatchers.IO (an injected dispatcher, so tests can replace it), and compares the result with the hash the server gave (for example in a metadata call before the download). A mismatch deletes the file and marks the transfer FAILED. This catches corruption that a size check cannot.
Storage options:
context.filesDir(internal) orcontext.getExternalFilesDir(null)(app-specific external). Neither needs a permission, other apps cannot see them, and both are deleted when the app is uninstalled.getExternalFilesDircan returnnullwhen that storage is unavailable.- Shared storage through
MediaStore(for example a video the user wants in the gallery, or a file in Downloads). On Android 10+ an app can add files toMediaStorecollections without a storage permission. Insert withIS_PENDING = 1, write through the returned URI, then setIS_PENDING = 0so other apps never see a half-written file. On Android 11+WRITE_EXTERNAL_STORAGEgives no extra write access. - To hand one file to one app (for example "open with"), share a
FileProviderURI withFLAG_GRANT_READ_URI_PERMISSION. That is a different thing fromMediaStore.
A simple flow: download into app-specific storage, verify the hash, then copy into MediaStore if the user wants it shared.
Uploads usually start from a content:// URI the user picked. A temporary URI grant may be gone when the worker retries hours later, so copy the file into app storage first, or take a persistable URI permission where the provider supports it.
Cleanup: completed transfers keep the file until the user deletes it. A periodic worker removes old FAILED rows and their partial files after a retention period you choose. Paused downloads keep the partial file so the user can resume. The index on status and createdAt keeps the cleanup query fast, and the same worker can trim old COMPLETED rows so the table does not grow forever.
Trade-offs
| Decision | Options | What to pick and why |
|---|---|---|
| Scheduling mechanism | A coroutine in viewModelScope; WorkManager with setForeground(); a UIDT job (Android 14+); a foreground service you manage yourself. | WorkManager as the base: it persists work, handles constraints and backoff, and survives process death. A ViewModel coroutine dies with the screen or the process. For transfers the user starts, add UIDT jobs on Android 14+, which the docs recommend with WorkManager as the fallback on older versions. A hand-made foreground service repeats what WorkManager gives you and is still subject to the same foreground service rules. |
Downloads: own code or system DownloadManager | Our own worker with OkHttp; the platform DownloadManager. | DownloadManager is a good choice for plain HTTP downloads to a file: the system runs it outside your process, retries, and shows its own notification, and you can add headers with addRequestHeader. It does not upload, gives little control over retries, chunking or your notification, and progress comes from querying it. Use your own worker when you need uploads, custom auth refresh, integrity checks or one queue for both directions. |
| Chunk size | Small chunks; a few MiB; large chunks. | Follow the server's rules first. With a streaming body memory is not the issue; the trade-off is request overhead against work lost per failure. A few MiB is a common starting point. |
| Storage location | Internal filesDir; app-specific external (getExternalFilesDir); MediaStore. | App-specific storage by default: no permission, private to the app. Copy to MediaStore only when the user wants the file visible to other apps. Remember app-specific files are deleted on uninstall. |
| Progress updates | Every network read; sampled every 500 ms; on whole-percent changes. | Write to Room per chunk, sample(500) for the UI, and update the notification only on whole-percent changes. This keeps the UI live without flooding recomposition or the notification system. |
| Concurrency | One transfer at a time; a small fixed pool; unbounded. | A small cap (for example 2 or 3), held by keeping extra rows QUEUED. One at a time is simplest and uses a slow link fully. A small pool lets a small file finish while a large one runs. Unbounded parallelism splits bandwidth, keeps the radio busy and makes every transfer slow. |
What breaks in production
- Users saw a large download sit at 99 percent; the notification then disappeared, and the row never showed "done".
- The list screen read progress from
WorkInfo.progress. When the work finished, thatDatabecame empty, so the row kept the last sampled value. - The row's status changed only when the screen saw a
SUCCEEDEDstate. If the app was not running at that moment, nothing updated the row.
- The worker now writes the final byte count and
COMPLETEDto Room before returningResult.success(). The UI reads Room only. - A separate "download complete" notification is posted when the transfer ends, because the foreground notification goes away with the work.
- On app start, a reconciliation step looks for rows still
IN_PROGRESSwhose work is finished or missing, and corrects them (completed if the file size and hash match, otherwise queued again).
- After a process kill mid-download, some finished files were larger than the server's file and failed the hash check.
- The worker resumed from the offset saved in Room, but Room was written only every few chunks, so the file on disk held more bytes than Room said. The worker requested a range that started too early and appended bytes the file already had.
- Some CDN responses also ignored the
Rangeheader and returned200with the whole file, which the worker appended as well.
- The resume offset now comes from the partial file's length on disk, the only value that cannot be out of date. Room's count is for display.
- The worker appends only on
206. On200it truncates the file and starts from zero. It sendsIf-Rangewith the saved ETag, so a changed remote file also comes back as200. - Added a test with a fake server that drops the connection mid-body, including a run that returns
200to a range request, and asserts the final file matches the expected hash.
Common mistakes in this round
- Running the transfer in a ViewModel coroutine scope. The coroutine stops when the screen is gone or the process dies, and a long transfer is lost. Instead: use WorkManager (and UIDT jobs on Android 14+ for user-started transfers) so the work is persisted and rescheduled.
- Loading the entire file into a ByteArray. A multi-gigabyte file does not fit in the heap and the app crashes with
OutOfMemoryError. Instead: stream with aRequestBodythat writes from the file, and mark download calls@Streaming. - Resuming from a local counter. For uploads, a chunk can arrive even though its response was lost. For downloads, the saved count can lag the file on disk. Instead: ask the server for its upload offset, and use the partial file's length for downloads.
- Using setExpedited() for a long transfer. Expedited work is for short tasks and has a limited quota. Instead:
setForeground()with adataSyncForegroundInfo, or a UIDT job. - Forgetting the foreground service type on Android 14+.
setForeground()without a type, or without the manifest entry onSystemForegroundService, throws when the app targets 34 or higher. Instead: passFOREGROUND_SERVICE_TYPE_DATA_SYNC, declare it, and add theFOREGROUND_SERVICE_DATA_SYNCpermission. - Ignoring the network type. Large transfers on mobile data cost the user money. Instead: default to
NetworkType.UNMETEREDand let the user allowNetworkType.CONNECTEDin settings. - Logging file paths and URLs. Paths can contain user names and URLs can carry tokens. Instead: log only the transfer ID and status.
- Updating the notification on every read. The system drops updates posted too often, and each one costs battery. Instead: update when the whole percentage changes, with
setOnlyAlertOnce(true).
Follow-up questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you handle a transfer that has been running for 30 minutes and the user swipes the app away or the process is killed?”
“How do you show progress in the UI without flooding it?”
“What happens when the user switches from Wi-Fi to mobile data mid-transfer?”
“How do you verify file integrity after a large download?”
Self-review checklist
- The design uses WorkManager (unique work per transfer,
KEEP, network constraint, exponential backoff), with UIDT jobs on Android 14+ for transfers the user starts. Not a bare coroutine and notsetExpedited(). - Long transfers call
setForeground()with adataSyncForegroundInfo, the manifest declares the type onSystemForegroundService, and the Android 15dataSynctime limit is covered by resumability. - Uploads stream from the file with a
RequestBody; downloads are@Streaming. No full-fileByteArray. - Upload resume starts from the server's committed offset. Download resume starts from the partial file's length, appends only on
206, and usesIf-Range. - Room is the single source of truth for transfer state and progress. The UI samples the Room
Flow;setProgress()is never used to resume. - Only
IOExceptionand HTTP errors are caught;CancellationExceptionpropagates so pause and cancel work. - Notifications use an
IMPORTANCE_LOWchannel,setOnlyAlertOnce(true), whole-percent updates, a cancel action, and a separate result notification. - Downloads are verified with SHA-256 in streaming blocks. Files go to app-specific storage and are copied to
MediaStoreonly when the user wants them shared.