Design a file upload service

Learn how to design a resumable Android file upload: WorkManager, chunked uploads with byte offsets, setForeground with dataSync, and progress notifications. About 28 minutes.

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 Activity or 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 dataSync now has a daily time limit. Knowing how WorkManager's setForeground() 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:

ProtocolHow 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 uploadA session URI; chunks are multiples of 256 KiB (except the last); a status query returns the bytes received
Amazon S3 multipart uploadParts of at least 5 MiB (except the last) uploaded by part number, then a complete call with the part ETags
Custom chunk APIPUT /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.

ConcernMechanism
Survive process deathWorkManager persists the request and reruns it
Survive network lossNetwork constraint, Result.retry(), exponential backoff
Resume without resendingServer-reported byte offset (tus HEAD, GCS status query)
User visibilitysetForeground() notification with progress and a cancel action
DuplicatesOffsets make chunk writes repeatable; idempotency key on create and complete calls
MemoryStream one chunk at a time from the file

Notes

  • WorkManager stores the request and its input Data in its own database and reruns the worker after process death or Result.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 progress Data.
  • 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; check runAttemptCount and return Result.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. REPLACE would cancel a running upload.
  • For a long upload, call setForeground() early in doWork(). From Android 14 pass a ForegroundInfo with ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC and declare android:foregroundServiceType="dataSync" on SystemForegroundService in 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, dataSync foreground 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() and readFully() 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 needs POST_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 POST is 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. setProgress is for the UI only; the next attempt gets its position from the server.
  • Only IOException, 5xx, 429 and offset conflicts retry. CancellationException is 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) and enqueueUniqueWork("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

Uploads restarted from zero after every retry
  • 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 from inputData on the next attempt.
  • Progress Data is not passed to the next run and the input never changes, so every retry started at chunk 0.
The fix
  • At the start of each run the worker now asks the server for its offset (HEAD in tus) and continues from there.
  • setProgress() is used only to drive the progress bar in the UI.
  • Added a test with TestListenableWorkerBuilder and a fake server that fails after two chunks, asserting that the second run sends only the remaining bytes.
Upload crashed after raising targetSdk to 34
  • After the app moved to targetSdk 34, large uploads stopped and crash reports showed a MissingForegroundServiceTypeException from the worker's foreground call.
  • The worker called setForeground() with a ForegroundInfo that had no service type, and the manifest did not declare a type for SystemForegroundService.
The fix
  • Passed ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC in the ForegroundInfo.
  • Declared android:foregroundServiceType="dataSync" on androidx.work.impl.foreground.SystemForegroundService with tools:node="merge", and added the FOREGROUND_SERVICE_DATA_SYNC permission.
  • Declared the use of the dataSync type 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 with RandomAccessFile.seek() and readFully().
  • 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 on SystemForegroundService, throws when the app targets 34 or higher. Pass FOREGROUND_SERVICE_TYPE_DATA_SYNC and declare it.
  • Using ExistingWorkPolicy.REPLACE for uploads. Tapping upload again cancels the running upload. Use KEEP per 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

  1. Write a fake TusApi in your test sources that keeps an offset per upload URL, returns it from offset() in the Upload-Offset header, accepts patch() only when the client's offset matches (otherwise 409), and can be told to throw an IOException after N chunks.

  2. Write UploadWorker as a CoroutineWorker with inputs path and upload_url. In doWork(), call offset() first, then loop: seek to the offset, readFully one chunk into a reused buffer, patch, and take the new offset from the response.

  3. After each chunk, call setProgress(workDataOf("percent" to percent)) only when the percentage changes. Return Result.retry() on IOException, 5xx, 429 and 409, and Result.failure() on other 4xx or after 10 attempts (runAttemptCount).

  4. Build the request with a NetworkType.CONNECTED constraint and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS), and enqueue it with enqueueUniqueWork("upload-" + uploadId, ExistingWorkPolicy.KEEP, request).

  5. Add setForeground() with a ForegroundInfo of type FOREGROUND_SERVICE_TYPE_DATA_SYNC, the manifest entry for SystemForegroundService, an IMPORTANCE_LOW channel, 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.

Next: Gradle build performance