Sub topic 7
Chunked and resumable uploads for large files and unreliable networks
This chapter assumes you know presigned URLs from the previous chapter and have used S3 or a similar object store. You should also be comfortable with fetch and with one server-side language. Examples use Python with boto3 and browser JavaScript.
Why one request is not enough
A single POST or PUT carries the whole file. If the connection drops at 95% of a 4 GiB video, the client must start over. Three problems follow:
- Wasted work. Every failure throws away all bytes already sent.
- Fragile limits. A single presigned
PUTon S3 is capped at 5 GiB, and proxies or load balancers often have shorter timeouts. - No parallelism. One TCP stream rarely fills a fast link.
Chunked uploads split the file into parts. Each part is a small, independently retryable request. Resumable uploads add one more idea: the server remembers which parts it has, so a client can reconnect later and send only the missing ones.
The S3 multipart model
S3 multipart upload has four operations:
create_multipart_uploadreturns anUploadId.upload_partstores one numbered part and returns itsETag.complete_multipart_uploadassembles the parts in number order into one object.abort_multipart_uploaddiscards the parts.
| Limit | Value |
|---|---|
| Minimum part size | 5 MiB, except the last part |
| Maximum part size | 5 GiB |
| Maximum parts per upload | 10,000 |
| Maximum object size | 5 TiB |
Until you complete or abort, the uploaded parts stay in the bucket and you pay for them. They do not appear in normal object listings. The final section of this chapter returns to that cost.
Server side
The API server never touches file bytes. It creates the upload, signs part URLs, reports progress, and completes the upload. Choose the part size on the server so the client cannot exceed the 10,000-part limit.
import math
import boto3
s3 = boto3.client("s3")
BUCKET = "example-uploads"
MIB = 1024 * 1024
MAX_PARTS = 10_000
def choose_part_size(file_size: int) -> int:
smallest = math.ceil(file_size / MAX_PARTS)
return math.ceil(max(smallest, 16 * MIB) / MIB) * MIB
def start_upload(key: str, content_type: str) -> str:
response = s3.create_multipart_upload(
Bucket=BUCKET, Key=key, ContentType=content_type
)
return response["UploadId"]
def sign_part(key: str, upload_id: str, part_number: int) -> str:
return s3.generate_presigned_url(
"upload_part",
Params={
"Bucket": BUCKET,
"Key": key,
"UploadId": upload_id,
"PartNumber": part_number,
},
ExpiresIn=900,
)
def uploaded_parts(key: str, upload_id: str) -> dict:
parts = {}
pages = s3.get_paginator("list_parts").paginate(
Bucket=BUCKET, Key=key, UploadId=upload_id
)
for page in pages:
for part in page.get("Parts", []):
parts[part["PartNumber"]] = {"ETag": part["ETag"], "Size": part["Size"]}
return parts
def finish_upload(key: str, upload_id: str, expected_parts: int) -> None:
parts = uploaded_parts(key, upload_id)
if sorted(parts) != list(range(1, expected_parts + 1)):
raise ValueError("upload is incomplete")
s3.complete_multipart_upload(
Bucket=BUCKET,
Key=key,
UploadId=upload_id,
MultipartUpload={
"Parts": [
{"PartNumber": n, "ETag": parts[n]["ETag"]} for n in sorted(parts)
]
},
)Two design choices here matter.
- The server asks S3 for the part list. The client does not report ETags. S3 is the source of truth, so a buggy or malicious client cannot claim parts that were never uploaded. It also makes resuming simple:
uploaded_partsanswers "what is done?" for any client, on any device. - Part URLs are short-lived. Each URL lasts 15 minutes and covers one part. A long upload asks for fresh URLs as it goes, and a URL that leaks is useful only briefly.
Store the UploadId, key, owner, and expected part count in your database. Check that the caller owns the upload before signing or completing anything.
Client side
The client slices the file with Blob.slice, sends each slice with PUT, and retries failures with exponential backoff and jitter. Only retry errors that can succeed later: network failures, 429, and 5xx. A 403 usually means an expired URL. Ask the server for a new one instead of retrying the same URL.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function putPart(getUrl, blob, attempts = 5) {
for (let attempt = 0; attempt < attempts; attempt++) {
try {
const res = await fetch(await getUrl(), { method: "PUT", body: blob });
if (res.ok) return;
const retryable = res.status === 403 || res.status === 429 || res.status >= 500;
if (!retryable) throw Object.assign(new Error(`Part failed: ${res.status}`), { fatal: true });
} catch (err) {
if (err.fatal) throw err;
}
await sleep(2 ** attempt * 500 + Math.random() * 250);
}
throw new Error("Part failed after all retries");
}
async function uploadParts(file, session, concurrency = 3) {
const { partSize, done, signPart } = session; // done: array of finished part numbers
const total = Math.ceil(file.size / partSize);
const pending = [];
for (let n = 1; n <= total; n++) {
if (!done.includes(n)) pending.push(n);
}
async function worker() {
while (pending.length > 0) {
const n = pending.shift();
const blob = file.slice((n - 1) * partSize, n * partSize);
await putPart(() => signPart(n), blob);
}
}
await Promise.all(Array.from({ length: concurrency }, worker));
}On a fresh start, done is empty. After a page reload, the client reads the saved UploadId from localStorage, calls an endpoint backed by uploaded_parts, and passes the result as done. Because a part PUT is idempotent, resending a part that actually arrived is harmless. S3 keeps the latest copy of that part number.
A few practical settings:
- Concurrency: 3 to 6 parts at once is typical. More streams compete for the same link and can slow each other.
- Part size: Larger parts mean fewer requests but more bytes to resend on failure. 8 to 64 MiB is a common range.
- Progress: Count completed parts for coarse progress. Use
XMLHttpRequestupload events if you need smooth per-byte progress inside a part.
What multipart cannot enforce
A presigned POST policy can cap size and pin the content type, as in the earlier chapter. Presigned upload_part URLs have no such conditions. Nothing in the URL limits the total number of parts or their sizes beyond S3's own limits. So you must check after completion:
- Call
head_objectand compareContentLengthto the size the user declared and to your per-type maximum. - Read the first bytes with a ranged
get_objectand check the file signature. - Delete the object, or move it to a quarantine prefix, if any check fails.
Only then let the post-upload pipeline treat the file as trusted.
Alternatives
| Approach | Where state lives | Good fit |
|---|---|---|
| S3 multipart with presigned part URLs | In S3, keyed by `UploadId` | Large files going straight to S3 |
| Google Cloud Storage resumable session | A session URL issued by GCS | GCS-based storage |
| tus protocol | A tus server you run or host | Storage-agnostic clients and servers |
All three share the same idea. The server records an offset or part list, and the client asks for it after a failure. If you already use S3, multipart avoids running another service.
Cleaning up abandoned uploads
Users close tabs, and phones lose signal. Each abandoned upload leaves parts that are billed but invisible in the console's object list. Add a lifecycle rule that aborts incomplete multipart uploads after a fixed time, for example seven days:
{
"Rules": [
{
"ID": "abort-stale-multipart-uploads",
"Status": "Enabled",
"Filter": { "Prefix": "incoming/" },
"AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
}
]
}Make that window longer than the longest upload you want to allow to resume. The final chapter on lifecycle rules and cost covers this in more detail.
Exercise
A user uploads a 200 GiB file. Your server uses 5 MiB parts. What goes wrong, and how should the server choose the part size?
Show answer
200 GiB divided into 5 MiB parts needs about 40,960 parts, which exceeds the 10,000-part limit. The server should compute the smallest size that fits, ceil(file_size / 10,000), which is about 20.5 MiB here, and round it up to a whole MiB. It should also keep a floor such as 16 MiB for efficiency and return the chosen size to the client, so the client slices the file the same way on every resume.
Exercise
A client reports that every part upload succeeds, but the final complete call fails with an invalid-part error. Name two likely causes.
Show answer
First, the client may have sent wrong or missing ETags, for example because CORS did not expose the ETag header. Second, parts other than the last may be under 5 MiB, or the part list may be incomplete or out of order. Building the list on the server from list_parts avoids the ETag and ordering problems.