A user uploads a 300 MB recipe video with the Firebase Storage Android SDK and Android kills the process halfway; how do you resume without re-sending the first half?
answer
- every upload is a resumable session
- the session outlives your process
- persist uploadSessionUri
- putFile with a third argument
- sessions last one week
basics
~20 sSave the upload snapshot's uploadSessionUri to persistent storage once it appears, then after the restart call putFile(uri, metadata, sessionUri). The SDK asks the server how many bytes arrived and continues from there; sessions last a week.
solid answer
~50 sEvery `UploadTask` runs over a resumable upload session on the server, and the session survives your process even though the task object does not. While the upload runs, read `uploadSessionUri` from the `TaskSnapshot` in a progress listener and, the first time it is non-null, write it to `SharedPreferences` or DataStore with the local Uri. After the restart, call `putFile(localUri, storageMetadata { }, sessionUri)`: the metadata argument must not be null, and only `putFile` has this overload. The SDK queries the session for the bytes received, skips that much of the local file and sends the rest. Sessions last one week; an expired or failed session ends in the failure listener, and you start a fresh upload. The SDK does not check that the file is unchanged, so resume only from the same, unmodified file. Clear the saved Uri on success, and when a resume attempt fails.
code
kotlin · 27 linesimport android.content.SharedPreferences
import android.net.Uri
import androidx.core.content.edit
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import com.google.firebase.storage.storageMetadata
fun startOrResume(ref: StorageReference, video: Uri, prefs: SharedPreferences): UploadTask {
val saved = prefs.getString("upload_session", null)?.let(Uri::parse)
val task = if (saved != null) {
ref.putFile(video, storageMetadata { }, saved)
} else {
ref.putFile(video, storageMetadata { contentType = "video/mp4" })
}
task.addOnProgressListener { snapshot ->
val session = snapshot.uploadSessionUri
if (session != null && saved == null && !prefs.contains("upload_session")) {
prefs.edit { putString("upload_session", session.toString()) }
}
}.addOnSuccessListener {
prefs.edit { remove("upload_session") }
}.addOnFailureListener {
// A failed resume usually means an expired or dead session: start fresh next time.
if (saved != null) prefs.edit { remove("upload_session") }
}
return task
}go deeper
Recall that uploads keep running through rotation and that uploadSessionUri plus putFile's third argument is how an upload continues after a restart.
Explain the resumable session behind every UploadTask, in-process retries until maxUploadRetryTimeMillis, and why only putFile can reattach to a session after the process is gone.
Design the full path: persist the session with file size and timestamp, resume when the user is signed in, handle expiry after a week, and avoid duplicate objects when the process dies at the finish.
Decide how much reliability the app owes large uploads: resumable sessions alone, a background job that resumes them, or server-side processing that tolerates partial and duplicate uploads.
## Three ways an upload gets interrupted A long upload from a phone is interrupted in three different ways, and the Firebase Storage Android SDK handles each differently. | Interruption | What survives | What you do | |---|---|---| | Network drop, process alive | the `UploadTask` and the server session | nothing; the SDK retries with backoff | | Activity recreated (rotation, dialog) | the task keeps running in the process | re-attach listeners through `getActiveUploadTasks()` | | Process killed | only the server-side session | persist the session Uri and resume with `putFile` | ## Inside a single process Every upload method (`putBytes`, `putStream`, `putFile`) starts a **resumable upload session** on the server and sends the file in chunks. The chunk size starts at 256 KB, doubles after each successful chunk up to 32 MB, and drops back to 256 KB after a failed one. - **Retries.** Failed requests are retried with exponential backoff until `FirebaseStorage.maxUploadRetryTimeMillis` runs out, ten minutes by default. Then the task fails; when the network was unavailable, the code is `StorageException.ERROR_RETRY_LIMIT_EXCEEDED`. - **Pause and resume.** `pause()` and `resume()` stop and continue the same session; the paused and progress listeners fire. - **Lifecycle.** An upload is not tied to an Activity. It continues through configuration changes, and listeners you attached stay attached, which can update a dead UI. Register them with the `Activity` overloads so they are removed when it stops, save the reference's path in `onSaveInstanceState`, and after recreation call `getActiveUploadTasks()` on the reference to find the running task and attach fresh listeners. None of this survives the process. When Android kills it, the `UploadTask`, its listeners and its in-memory progress are gone. ## Resuming after the process dies The server-side session is still there, and its address is exposed as `UploadTask.TaskSnapshot.uploadSessionUri`. 1. **Start with `putFile`.** Only `putFile` has the overload that accepts an existing session, so a byte array or stream upload cannot be resumed this way. 2. **Capture the session Uri.** It is null until the session has been created; read it in a progress listener and persist it the first time it is non-null, together with the local file Uri and the storage path. 3. **Resume.** After the restart, rebuild the reference and call `putFile(localUri, metadata, sessionUri)`. Pass `storageMetadata { }` rather than null: the SDK rejects a null metadata argument on this overload. 4. **The SDK reconciles.** It queries the session for how many bytes the server has received, advances the local stream by that amount, and uploads only the remainder. 5. **Clean up.** Delete the persisted Uri on success, and when a resume attempt fails, before starting over. ## Limits you must design for - **One week.** Sessions last a week. Resuming an expired session, or one that had already failed, fails the task; start a new upload from byte zero. - **Same file, same bytes.** The SDK only skips ahead by the server's byte count; it does not compare content. If the user edited or replaced the file, a resumed upload produces a corrupted object. The documentation makes this the app's responsibility, so record the file's size and modification time with the session and discard the session if they changed. - **Something must run the resume.** The SDK resumes only when your code calls `putFile` again. Scheduling that call after a restart, for example with a background job, belongs to Android's background-work APIs rather than to Firebase. - **Cancellation is final.** `cancel()` tells the server to end the session, and the task fails with `ERROR_CANCELED`; clear any saved session Uri for it rather than trying to resume. - **Completion is still a client event.** If the process dies after the last chunk but before your success listener runs, the object may already exist; calling `getMetadata()` on the reference tells you before re-uploading. ## Example ```kotlin val ref = Firebase.storage.reference.child(path) ref.putFile(videoUri, storageMetadata { contentType = "video/mp4" }).addOnProgressListener { snap -> val session = snap.uploadSessionUri if (session != null && prefs.getString("session", null) == null) { prefs.edit().putString("session", session.toString()).apply() } } ``` After a restart, read the saved string, parse it with `Uri.parse`, and pass it as the third argument to `putFile` on a reference to the same path.
- The resumed upload fails immediately. What are the likely causes, and what should the app do?The session may be older than a week, or it had already failed or been cancelled, so the server no longer accepts it; the task's failure listener fires. The app should delete the saved session Uri and start a new `putFile` without it. If failures continue, check the `StorageException` code: `ERROR_NOT_AUTHENTICATED` after a restart can mean the user is not signed in yet when the resume runs.
- Why can't you resume an upload that was started with putStream()?Only `putFile` has the overload that takes an existing upload session Uri; it reopens the file or content Uri and skips the bytes the server already has. A `putStream` upload also runs over a session and retries within the process, but after a restart there is no API to attach a new stream to the old session.
- Uploads are lost on process death; the only option is to restart from zero
- The SDK automatically resumes interrupted uploads after the app restarts
- putBytes and putStream can resume a saved session like putFile
- A saved upload session stays valid indefinitely
- The SDK verifies the file is unchanged before resuming the session