Design a file upload service
Why it matters
- Uploads of photos, video, or documents fail in the field all the time: the network drops, the user leaves the app, the process is killed. If the upload lives in an
Activityor a plain coroutine, it dies with them. WorkManager persists the request and runs it again, and interviewers expect you to name it. - Foreground service rules changed in Android 12, 14, and 15: background starts are mostly blocked, a service type is required, and
dataSyncnow has a daily time limit. Knowing how WorkManager'ssetForeground()fits these rules separates a mid answer from a senior one. - A resumable upload turns one large request into many smaller ones that the server can acknowledge by byte offset. That changes retry logic, idempotency, progress reporting, and memory use, and interviewers probe each of those.
- This topic connects to other module lessons: the offline-first notes app uses the same WorkManager pattern for sync, and the chat app's media attachments reuse the same upload path.
The simple explanation
- You are mailing a 200-page manuscript.
- You send it in 20-page bundles, and the publisher tells you after each one how many pages it now has.
- If you get stuck in traffic, you call the publisher, ask "how many pages do you have?", and continue from there, not from page 1.
- Because you always ask first, a bundle that arrived while you were not listening is never sent twice.
- A small sign in your window (the progress notification) shows how far along you are.
How do you design a resumable file upload on Android? Run the upload in a WorkManager worker, which survives process death and retries with backoff. Use a resumable protocol where the server tracks how many bytes it has: before sending, the worker asks the server for the current offset, then streams the file from that offset in chunks. For long uploads the worker calls setForeground() so it runs as a foreground service of type dataSync with a progress notification.
Resumable protocols. You rarely invent your own. Common choices:
| Protocol | How resume works |
|---|---|
| tus (open protocol) | POST creates the upload, HEAD returns Upload-Offset, each PATCH sends bytes starting at that offset |
| Google Cloud Storage resumable upload | A session URI; chunks are multiples of 256 KiB (except the last); a status query returns the bytes received |
| Amazon S3 multipart upload | Parts of at least 5 MiB (except the last) uploaded by part number, then a complete call with the part ETags |
| Custom chunk API | PUT /uploads/{id}/chunks/{index}; the server lists which chunks it has |
Client components. The repository saves an upload row in Room (file, upload URL or session id, state) and enqueues unique work per file. The worker reads the file from app storage, asks the server for its offset, sends chunks, updates progress, and finishes the upload. Files picked by the user arrive as content:// URIs; copy them into app storage (or take a persistable URI permission where the provider supports it), because a temporary grant may not survive until a retry hours later.
Long-running work. A worker normally gets about 10 minutes per run. For a large upload it calls setForeground(ForegroundInfo(...)), and WorkManager runs it inside its own foreground service with your notification. From Android 14 (target 34) the ForegroundInfo must name a type such as FOREGROUND_SERVICE_TYPE_DATA_SYNC, the manifest must declare that type on WorkManager's SystemForegroundService, and the app needs the FOREGROUND_SERVICE_DATA_SYNC permission. On Android 15, dataSync gets 6 hours per 24 hours, so the upload must be resumable anyway. On Android 14+, user-initiated data transfer jobs (JobInfo.Builder.setUserInitiated(true)) are another option for transfers the user explicitly starts.
| Concern | Mechanism |
|---|---|
| Survive process death | WorkManager persists the request and reruns it |
| Survive network loss | Network constraint, Result.retry(), exponential backoff |
| Resume without resending | Server-reported byte offset (tus HEAD, GCS status query) |
| User visibility | setForeground() notification with progress and a cancel action |
| Duplicates | Offsets make chunk writes repeatable; idempotency key on create and complete calls |
| Memory | Stream one chunk at a time from the file |
Notes
- WorkManager stores the request and its input
Datain its own database and reruns the worker after process death orResult.retry(). The input stays the same on every run. setProgress()is for observers while the worker runs; it is not saved for the next attempt. Resume from the offset the server reports, or from a value you store in Room yourself, never from progressData.- Ask the server for its offset at the start of each run. A chunk can reach the server even though the response was lost, and only the server knows.
- Retry policy:
setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS). WorkManager's default is already exponential from 30 seconds, and the minimum is 10 seconds. There is no built-in retry cap; checkrunAttemptCountand returnResult.failure()after your limit. - Retry on
IOException, 5xx and 429; fail on other 4xx errors such as an expired session, after which the app can start a new upload. - Use unique work per file, for example
enqueueUniqueWork("upload-" + uploadId, ExistingWorkPolicy.KEEP, request), so tapping upload twice does not start two uploads.REPLACEwould cancel a running upload. - For a long upload, call
setForeground()early indoWork(). From Android 14 pass aForegroundInfowithServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNCand declareandroid:foregroundServiceType="dataSync"onSystemForegroundServicein your manifest. On Android 12+ it can fail if the app is in the background at that moment, which is why the user-visible start of the upload is the best time. - On Android 15,
dataSyncforeground services get 6 hours per 24 hours. Very large uploads must be resumable so a stop at the limit costs little. - Read the file with
RandomAccessFile.seek()andreadFully()into one reused buffer.File.readBytes()on a 200 MB video allocates 200 MB at once. - Progress notifications: a channel with
IMPORTANCE_LOW,setOnlyAlertOnce(true), and updates only when the percentage changes, since the system drops updates posted too often. On Android 13+ the notification needsPOST_NOTIFICATIONS; if it is denied, the foreground work still runs but the notification is hidden from the drawer. - Add a cancel action with
WorkManager.createCancelPendingIntent(id). - For small files (under a few MB on typical connections), a single multipart
POSTis simpler; the size where chunking pays off is a judgement based on your users' file sizes and networks.
Code example
A tus-style upload worker. The upload URL comes from the creation request (POST with Upload-Length), made once and stored in Room; here it is passed as input to keep the example short.
import android.content.Context
import android.content.pm.ServiceInfo
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.HEAD
import retrofit2.http.Header
import retrofit2.http.Headers
import retrofit2.http.PATCH
import retrofit2.http.Url
interface TusApi {
@HEAD
@Headers("Tus-Resumable: 1.0.0")
suspend fun offset(@Url uploadUrl: String): Response<Void>
@PATCH
@Headers("Tus-Resumable: 1.0.0")
suspend fun patch(
@Url uploadUrl: String,
@Header("Upload-Offset") offset: Long,
@Body chunk: RequestBody, // Content-Type: application/offset+octet-stream
): Response<Void>
}
class UploadWorker(
context: Context,
params: WorkerParameters,
private val api: TusApi, // provided by a WorkerFactory, for example Hilt's
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val file = File(inputData.getString(KEY_PATH) ?: return Result.failure())
val uploadUrl = inputData.getString(KEY_UPLOAD_URL) ?: return Result.failure()
if (!file.exists()) return Result.failure(workDataOf(KEY_ERROR to "file_missing"))
if (runAttemptCount >= MAX_ATTEMPTS) return Result.failure(workDataOf(KEY_ERROR to "gave_up"))
setForeground(foregroundInfo(percent = 0))
return try {
// Ask the server how many bytes it already has
val head = api.offset(uploadUrl)
if (!head.isSuccessful) return if (head.code() >= 500) Result.retry() else Result.failure()
var offset = head.headers()["Upload-Offset"]?.toLongOrNull() ?: return Result.retry()
val total = file.length()
val buffer = ByteArray(CHUNK_SIZE)
var lastPercent = -1
RandomAccessFile(file, "r").use { raf ->
while (offset < total) {
val n = minOf(CHUNK_SIZE.toLong(), total - offset).toInt()
raf.seek(offset)
raf.readFully(buffer, 0, n)
val response = api.patch(uploadUrl, offset, buffer.toRequestBody(OFFSET_STREAM, 0, n))
when {
response.isSuccessful ->
offset = response.headers()["Upload-Offset"]?.toLongOrNull() ?: return Result.retry()
response.code() == 409 -> return Result.retry() // offset mismatch: ask again next run
response.code() >= 500 || response.code() == 429 -> return Result.retry()
else -> return Result.failure(workDataOf(KEY_ERROR to "http_" + response.code()))
}
val percent = (offset * 100 / total).toInt()
if (percent != lastPercent) {
lastPercent = percent
setProgress(workDataOf(KEY_PERCENT to percent))
setForeground(foregroundInfo(percent))
}
}
}
Result.success()
} catch (e: IOException) {
Result.retry()
}
}
private fun foregroundInfo(percent: Int): ForegroundInfo {
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID) // IMPORTANCE_LOW channel
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setContentTitle("Uploading")
.setProgress(100, percent, false)
.setOngoing(true)
.setOnlyAlertOnce(true)
.addAction(
android.R.drawable.ic_delete, "Cancel",
WorkManager.getInstance(applicationContext).createCancelPendingIntent(id),
)
.build()
val notificationId = id.hashCode()
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ForegroundInfo(notificationId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
ForegroundInfo(notificationId, notification)
}
}
companion object {
const val KEY_PATH = "path"
const val KEY_UPLOAD_URL = "upload_url"
const val KEY_PERCENT = "percent"
const val KEY_ERROR = "error"
const val CHANNEL_ID = "uploads"
const val CHUNK_SIZE = 5 * 1024 * 1024 // 5 MiB, reused buffer
const val MAX_ATTEMPTS = 10
val OFFSET_STREAM = "application/offset+octet-stream".toMediaType()
}
}The manifest entries that let WorkManager's foreground service use the dataSync type (Android 14+):
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application>
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:foregroundServiceType="dataSync"
tools:node="merge" />
</application>
</manifest>- Every run starts with
HEAD, so a chunk that reached the server while its response was lost is not sent again. - The file is read one chunk at a time into a reused 5 MiB buffer, so memory use does not grow with file size.
- Progress and the notification update only when the percentage changes.
setProgressis for the UI only; the next attempt gets its position from the server. - Only
IOException, 5xx, 429 and offset conflicts retry.CancellationExceptionis not caught, so the cancel action and WorkManager's own stops work. - The repository enqueues it with a network constraint,
setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)andenqueueUniqueWork("upload-" + uploadId, ExistingWorkPolicy.KEEP, request).
Run the idea in plain Kotlin
// Fake tus server: it only remembers how many bytes it has
class FakeTusServer(val length: Long) {
var offset = 0L
private set
fun head(): Long = offset
// Returns the new offset, or -1 (409) if the client's offset is wrong
fun patch(clientOffset: Long, bytes: Int): Long {
if (clientOffset != offset) return -1
offset += bytes
return offset
}
}
class Client(private val server: FakeTusServer, private val chunk: Int) {
var sentChunks = 0
// One worker run. failAfter simulates the connection dropping after N chunks.
fun run(failAfter: Int = Int.MAX_VALUE, loseLastResponse: Boolean = false): String {
var offset = server.head()
println(" HEAD -> offset " + offset)
var done = 0
while (offset < server.length) {
val n = minOf(chunk.toLong(), server.length - offset).toInt()
val newOffset = server.patch(offset, n)
sentChunks++
if (newOffset < 0) return "retry (409)"
done++
if (loseLastResponse && done == failAfter) return "retry (response lost after server stored it)"
offset = newOffset
if (done == failAfter) return "retry (network dropped)"
}
return "success"
}
}
fun main() {
val server = FakeTusServer(length = 23_000_000L)
val client = Client(server, chunk = 5_000_000)
println("Run 1:")
println(" " + client.run(failAfter = 2))
println("Run 2:")
println(" " + client.run(failAfter = 1, loseLastResponse = true))
println("Run 3:")
println(" " + client.run())
println("Server has " + server.offset + " of 23000000 bytes, PATCH calls=" + client.sentChunks)
}Expected output:
Run 1:
HEAD -> offset 0
retry (network dropped)
Run 2:
HEAD -> offset 10000000
retry (response lost after server stored it)
Run 3:
HEAD -> offset 15000000
success
Server has 23000000 of 23000000 bytes, PATCH calls=5
In production
- Large video uploads often took far longer than expected on flaky networks, and server logs showed the same early chunks arriving again and again.
- The worker saved its chunk index with
setProgress()and read it back frominputDataon the next attempt. - Progress
Datais not passed to the next run and the input never changes, so every retry started at chunk 0.
- At the start of each run the worker now asks the server for its offset (
HEADin tus) and continues from there. setProgress()is used only to drive the progress bar in the UI.- Added a test with
TestListenableWorkerBuilderand a fake server that fails after two chunks, asserting that the second run sends only the remaining bytes.
- After the app moved to
targetSdk34, large uploads stopped and crash reports showed aMissingForegroundServiceTypeExceptionfrom the worker's foreground call. - The worker called
setForeground()with aForegroundInfothat had no service type, and the manifest did not declare a type forSystemForegroundService.
- Passed
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNCin theForegroundInfo. - Declared
android:foregroundServiceType="dataSync"onandroidx.work.impl.foreground.SystemForegroundServicewithtools:node="merge", and added theFOREGROUND_SERVICE_DATA_SYNCpermission. - Declared the use of the
dataSynctype in the Play Console foreground service declaration, and tested uploads on Android 14 and 15 devices with the app in the background.
Common mistakes
- Resuming from
setProgress()data. Progress is only visible while the worker runs; the next attempt gets the original input. Ask the server for its offset, or store the position in Room yourself. - Trusting a local byte counter. A chunk can reach the server even though the response never arrived. If you resume from your own count, you send it again or the server rejects the offset. Always ask the server first.
- Calling File.readBytes() on a large file. It allocates the whole file at once and can throw
OutOfMemoryError. Read one chunk at a time withRandomAccessFile.seek()andreadFully(). - Keeping only a
content://URI for a later retry. A temporary URI grant may be gone when the worker runs again after a restart. Copy the file into app storage, or take a persistable permission where the provider supports it. - No foreground service type on Android 14+.
setForeground()without a type, or without the manifest declaration onSystemForegroundService, throws when the app targets 34 or higher. PassFOREGROUND_SERVICE_TYPE_DATA_SYNCand declare it. - Using
ExistingWorkPolicy.REPLACEfor uploads. Tapping upload again cancels the running upload. UseKEEPper file. - Retrying forever. WorkManager has no retry cap. Check
runAttemptCount, fail after a limit, and show a retry button; also fail at once on errors that will never succeed, like an expired upload session.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you make a file upload survive a process kill?”
“What are the Android 14 and 15 foreground service rules for a long upload?”
“How do you report upload progress to the user?”
“When do you use a single multipart POST versus a chunked resumable upload?”
Quiz
A worker calls setProgress() after each chunk. After a network error it returns Result.retry(). Where should the next attempt get its starting position?
Your app targets API 34. What does a WorkManager upload need in order to run as a dataSync foreground service?
Why read each chunk with RandomAccessFile instead of calling File.readBytes() once?
On Android 15, what limit applies to a dataSync foreground service?
0 of 4 answered
Mini task
15-minute exercise: resumable upload worker with progress
-
Write a fake
TusApiin your test sources that keeps anoffsetper upload URL, returns it fromoffset()in theUpload-Offsetheader, acceptspatch()only when the client's offset matches (otherwise 409), and can be told to throw anIOExceptionafter N chunks. -
Write
UploadWorkeras aCoroutineWorkerwith inputspathandupload_url. IndoWork(), calloffset()first, then loop:seekto the offset,readFullyone chunk into a reused buffer,patch, and take the new offset from the response. -
After each chunk, call
setProgress(workDataOf("percent" to percent))only when the percentage changes. ReturnResult.retry()onIOException, 5xx, 429 and 409, andResult.failure()on other 4xx or after 10 attempts (runAttemptCount). -
Build the request with a
NetworkType.CONNECTEDconstraint andsetBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS), and enqueue it withenqueueUniqueWork("upload-" + uploadId, ExistingWorkPolicy.KEEP, request). -
Add
setForeground()with aForegroundInfoof typeFOREGROUND_SERVICE_TYPE_DATA_SYNC, the manifest entry forSystemForegroundService, anIMPORTANCE_LOWchannel, and a cancel action.
Done condition: a TestListenableWorkerBuilder test where the fake fails after two chunks returns Result.retry(), a second run sends only the remaining bytes, and the fake server ends with exactly the file's length. On a device, killing the process with adb shell am kill <package> mid-upload and reopening the app continues from the server's offset.