A filmmaker uploads a 12 GB wedding film. At 83%, the Wi-Fi drops. The browser knows which chunk it was sending, but it has no idea whether the server saved it. Start the chunk again and you might write the same bytes twice. Skip it and you might leave a hole in the file. Either mistake can leave the editor staring at a completed progress bar while the video fails to process.
A client gallery FAQ covering video upload limits and delivery illustrates the size of the files this workflow can involve. The implementation below is an example of how to handle those uploads. It uses one number to settle every retry: the byte offset confirmed by the server.
Give the upload its own state
When an upload starts, the server creates a session tied to the account, the destination gallery, and the expected file size. The session has a committedBytes counter. If it says 16777216, the first 16 MiB are stored and accounted for. The next chunk starts at that offset.
A minimal API has three operations on an existing session:
-
GET /uploads/:idreturnscommittedBytes. -
PATCH /uploads/:idaccepts a chunk and its starting offset. It returns the new committed offset or409 Conflictif the starting offset is stale. -
POST /uploads/:id/completeverifies the assembled file and schedules processing. Calling it again returns the same asset or job.
Keep the session ID with the upload job in the browser. After a failed request, read the session again. If the server saved the chunk but its response was lost, the offset has advanced. If the server never committed the chunk, the offset still points to its beginning. The browser can use the same resume path in both cases.
Slice the file at the confirmed offset
This client uses 8 MiB chunks. It pauses on a network or server error, so the UI can offer a retry that calls resumeUpload again with the same session and file.
const CHUNK_SIZE = 8 * 1024 * 1024
async function resumeUpload(file, uploadId, onProgress, signal) {
const url = `/uploads/${encodeURIComponent(uploadId)}`
async function readOffset() {
const response = await fetch(url, { cache: "no-store", signal })
if (!response.ok) throw new Error(`Upload status: ${response.status}`)
const { committedBytes } = await response.json()
if (!Number.isSafeInteger(committedBytes) ||
committedBytes < 0 || committedBytes > file.size) {
throw new Error("Invalid upload offset")
}
return committedBytes
}
let offset = await readOffset()
onProgress(offset, file.size)
while (offset < file.size) {
const end = Math.min(offset + CHUNK_SIZE, file.size)
const response = await fetch(url, {
method: "PATCH",
headers: {
"Content-Type": "application/octet-stream",
"Upload-Offset": String(offset)
},
body: file.slice(offset, end),
signal
})
if (response.status === 409) {
const latest = await readOffset()
if (latest <= offset) throw new Error("Upload conflict. Retry later.")
offset = latest
} else {
if (!response.ok) throw new Error(`Chunk upload: ${response.status}`)
const { committedBytes } = await response.json()
if (committedBytes !== end) throw new Error("Unexpected upload offset")
offset = committedBytes
}
onProgress(offset, file.size)
}
const done = await fetch(`${url}/complete`, { method: "POST", signal })
if (!done.ok) throw new Error(`Upload completion: ${done.status}`)
return done.json()
}
file.slice(offset, end) gives the request a Blob for that byte range. The end offset is exclusive, including on the final chunk. The progress bar uses the server’s acknowledgments. At 100%, switch the label to “Processing” until the video is playable.
Make each server commit safe to retry
Store a chunk under a unique staging key. Once the write succeeds, record its key and length and advance the offset in one database transaction. Use a conditional update that succeeds only if the current offset still matches the request. If two tabs send the same chunk, one transaction wins. The other gets a conflict, and its unreferenced staged object can be cleaned up. The committed chunk has its own key, so the losing request cannot overwrite it.
Authenticate each request and check that the caller can still upload to the destination gallery. Enforce chunk size and remaining upload length on the server. If a refresh makes the browser ask the user to select the file again, compare a content fingerprint before resuming. Filename and size alone can match a different export, and appending that export would create a file made from two versions.
Test the failure after the write
The most revealing test drops the connection after the server commits a chunk but before the browser receives the response. On retry, the client should skip that chunk. Repeat the test with a drop before commit. This time it should resend the same byte range.
The completion request deserves the same test. If its response disappears, retrying should return the existing processing job. At that point, losing a connection can delay delivery, but it can no longer silently corrupt the upload or schedule a second transcode.
Top comments (0)