Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 5 · Concept · 20 min · revision 3

Large Uploads and Post-Processing Pipelines

Let clients upload large files straight to object storage with presigned multipart uploads, then check, scan and process each file in a background job before marking it ready.

Contentsand lesson path

What you will learn

  • Let clients upload large files directly to object storage with presigned uploads, and post-process them asynchronously before marking them available.

01. Why it matters

Lesson 03 sent each file in one presigned POST. That works for photos, but a multi-gigabyte video in one request is fragile: if the connection drops at 95%, the whole upload starts again, and one stream rarely uses all of a fast connection. And once the bytes have landed, nobody may download them until a background job has checked what they really are and scanned them, which for large files means doing that without loading the whole file into memory.

02. S3 multipart uploads: resilience and parallelism

S3 and S3-compatible stores such as SeaweedFS offer multipart upload for large files. AWS suggests considering it from about 100 MB.

  1. Create. The API calls CreateMultipartUpload and gets an UploadId for one bucket and key.
  2. Upload parts. The client splits the file and uploads each part with a part number from 1 to 10,000. Every part except the last must be 5 MiB to 5 GiB. Parts can travel in parallel and in any order, and a failed part is retried alone. S3 answers each part with an ETag, and the client must keep the list of part numbers and ETags.
  3. Complete. CompleteMultipartUpload with that list makes S3 join the parts, in part-number order, into one object. Its ETag is not an MD5 of the whole file.
  4. Abort. Until an upload is completed or aborted, its parts stay hidden from listings but are stored and billed. A bucket lifecycle rule with AbortIncompleteMultipartUpload removes abandoned ones.

03. Presigned multipart uploads in code

With presigned URLs the bytes still go straight to storage, as in lesson 03, but the API signs one URL per part. Each call below would sit behind an authenticated endpoint that loads the upload from the signed-in user's own database row:

  • start checks the declared size, chooses the key, opens the multipart upload and stores the plan: upload ID, part size and part count.
  • sign_part returns a 15-minute PUT URL for one planned part and signs that part's exact size as ContentLength. The URL then lists content-length;host in X-Amz-SignedHeaders, and storage refuses any other Content-Length with 403 SignatureDoesNotMatch. Without ContentLength only host is signed, and a part of any size up to 5 GiB would be accepted.
  • complete first checks that the client listed exactly parts 1 to part_count: signing fixes each part's length, but the client still chooses which parts to list, and two of four parts would make a valid, shorter object. It then checks the assembled size with head_object, as lesson 03 does, and moves the row to scanning.

Browsers need one more thing. A page can read only a few response headers from another origin unless the server lists more in Access-Control-Expose-Headers, and ETag is not among them, so without ExposeHeaders: ["ETag"] in the bucket CORS rule the browser cannot build the list for complete. The code uses the SeaweedFS storage and bucket from lesson 03; the rule keeps POST for its form uploads, because a new CORS configuration replaces the old one.

Python · mpu_api.py, part 1: client and bucket rules
import math
import os

import boto3
from botocore.config import Config

BUCKET = os.environ.get("S3_BUCKET", "secure-uploads")  # the bucket from lesson 03
PART_SIZE = 8 * 1024 * 1024  # every part but the last must be at least 5 MiB
MAX_BYTES = 1024**3  # keep at or below what the malware scanner accepts (see below)
s3 = boto3.client(
    "s3", endpoint_url=os.environ["S3_ENDPOINT"],  # the storage from lesson 03
    aws_access_key_id=os.environ["S3_ACCESS_KEY"],
    aws_secret_access_key=os.environ["S3_SECRET_KEY"], region_name="us-east-1",
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}))


def setup_bucket(app_origin: str) -> None:
    try:
        s3.create_bucket(Bucket=BUCKET)
    except s3.exceptions.BucketAlreadyOwnedByYou:
        pass  # a second run reuses the bucket
    # Browsers may read only a few response headers unless the bucket exposes
    # more; without ETag here, the client cannot build the completion list
    s3.put_bucket_cors(Bucket=BUCKET, CORSConfiguration={"CORSRules": [{
        "AllowedOrigins": [app_origin], "AllowedMethods": ["POST", "PUT"],  # 03 + 04
        "AllowedHeaders": ["content-type"], "ExposeHeaders": ["ETag"],
        "MaxAgeSeconds": 3000}]})
    # Parts of uploads nobody completes cost storage until they are aborted
    s3.put_bucket_lifecycle_configuration(Bucket=BUCKET, LifecycleConfiguration={
        "Rules": [{"ID": "abort-stale-uploads", "Status": "Enabled",
                   "Filter": {"Prefix": ""},
                   "AbortIncompleteMultipartUpload": {"DaysAfterInitiation": 3}}]})
Python · mpu_api.py, part 2: start, sign one part, complete
def start(file_id: str, size: int, content_type: str) -> dict:
    """Step 1: the API opens the multipart upload and fixes the part plan."""
    if not 0 < size <= MAX_BYTES:
        raise ValueError("size not allowed")
    key = f"uploads/{file_id}"  # the API chooses the key, never the client
    up = s3.create_multipart_upload(Bucket=BUCKET, Key=key, ContentType=content_type)
    return {"key": key, "upload_id": up["UploadId"], "part_size": PART_SIZE,
            "part_count": math.ceil(size / PART_SIZE), "size": size}


def sign_part(row: dict, part_number: int) -> str:
    """Step 2: one short-lived PUT URL per planned part, for exactly its size."""
    if not 1 <= part_number <= row["part_count"]:
        raise ValueError(f"part {part_number} is not part of this upload")
    length = min(row["part_size"], row["size"] - (part_number - 1) * row["part_size"])
    return s3.generate_presigned_url("upload_part", ExpiresIn=900, Params={
        "Bucket": BUCKET, "Key": row["key"], "UploadId": row["upload_id"],
        "PartNumber": part_number,
        "ContentLength": length})  # signed: storage refuses any other length


def complete(row: dict, parts: list[dict]) -> dict:
    """Step 3: check the part list, assemble, then check the result (lesson 03)."""
    numbers = sorted(p["PartNumber"] for p in parts)
    if numbers != list(range(1, row["part_count"] + 1)):
        # Signing fixes each part's length, not which parts the client lists
        raise ValueError(f"expected parts 1-{row['part_count']}, got {numbers}")
    s3.complete_multipart_upload(
        Bucket=BUCKET, Key=row["key"], UploadId=row["upload_id"],
        MultipartUpload={"Parts": sorted(parts, key=lambda p: p["PartNumber"])})
    head = s3.head_object(Bucket=BUCKET, Key=row["key"])
    if head["ContentLength"] != row["size"]:  # check what storage really assembled
        s3.delete_object(Bucket=BUCKET, Key=row["key"])
        return {"status": "rejected", "size": head["ContentLength"]}
    # The background job (process_upload below) sniffs the type and scans it
    return {"status": "scanning", "etag": head["ETag"]}

The client, standing in for browser code, asks for a URL per part, sends four parts at a time, and keeps each part's ETag from the response header. The test file is a fixed MP4 header plus seeded random bytes, so the ETags repeat on every run. Four negative tests follow: a part number outside the plan, a completion that lists only two of four parts, a made-up ETag, and a client that sends 1 MiB more than it declared.

Python · client.py, part 1: parallel part uploads with httpx
import random
from concurrent.futures import ThreadPoolExecutor

import httpx
from botocore.exceptions import ClientError

import mpu_api as api

api.setup_bucket("https://app.example.com")
rule = api.s3.get_bucket_cors(Bucket=api.BUCKET)["CORSRules"][0]
print("CORS exposes:", rule["ExposeHeaders"])
# A fixed test "video": an MP4 file-type box, then seeded random bytes
data = (b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom"
        + random.Random(42).randbytes(30 * 1024 * 1024 + 123_456))


def put_part(http: httpx.Client, row: dict, n: int, body: bytes) -> dict:
    for attempt in range(3):  # a failed part is retried alone
        try:
            r = http.put(api.sign_part(row, n), content=body)
            r.raise_for_status()
            return {"PartNumber": n, "ETag": r.headers["ETag"]}
        except httpx.TransportError:
            if attempt == 2:
                raise


def upload(file_id: str, payload: bytes, declared: int) -> dict:
    row = api.start(file_id, declared, "video/mp4")  # in real life: POST /uploads
    size = row["part_size"]
    chunks = [payload[i:i + size] for i in range(0, len(payload), size)]
    with httpx.Client(timeout=60) as http, ThreadPoolExecutor(max_workers=4) as pool:
        parts = list(pool.map(lambda n: put_part(http, row, n, chunks[n - 1]),
                              range(1, len(chunks) + 1)))
    for p in parts:
        print(f"  part {p['PartNumber']}: {len(chunks[p['PartNumber'] - 1]):>8} bytes"
              f"  ETag {p['ETag']}")
    return api.complete(row, parts)
Python · client.py, part 2: an honest upload and four that must fail
print("honest:", upload("f1", data, len(data)))
# Negative tests: a part outside the plan, a short part list, a wrong ETag, and
# a client that sends more than it declared
row = api.start("f2", len(data), "video/mp4")
try:
    api.sign_part(row, 99)
except ValueError as exc:
    print("sign part 99:", exc)
size = row["part_size"]
with httpx.Client(timeout=60) as http:
    parts = [put_part(http, row, n, data[(n - 1) * size:n * size])
             for n in range(1, row["part_count"] + 1)]
try:
    api.complete(row, parts[:2])  # every part uploaded, but only two listed
except ValueError as exc:
    print("complete with 2 of 4 parts:", exc)
try:
    api.complete(row, [{"PartNumber": 1, "ETag": '"0123456789abcdef"'}] + parts[1:])
except ClientError as exc:
    print("wrong ETag:", exc.response["Error"]["Code"])
api.s3.abort_multipart_upload(Bucket=api.BUCKET, Key=row["key"],
                              UploadId=row["upload_id"])
try:
    upload("f3", data + b"x" * 1024 * 1024, len(data))  # 1 MiB more than declared
except httpx.HTTPStatusError as exc:
    code = exc.response.text.split("<Code>")[1].split("</Code>")[0]
    print("oversized part:", exc.response.status_code, code)
Bash · run against the lesson 03 storage (Python 3.12)
# Storage: the lab-s3 container from lesson 03 (docker start lab-s3 if stopped)
export S3_ENDPOINT=http://localhost:8333
export S3_ACCESS_KEY=lab-admin S3_SECRET_KEY=lab-secret
until curl -s -o /dev/null "$S3_ENDPOINT"; do sleep 0.5; done  # wait until it answers
pip install "boto3==1.44.12" "httpx==0.28.1"
python client.py
Expected output (SeaweedFS weed mini: 4.51 as in lesson 03 and 4.54 print the same)
CORS exposes: ['ETag']
  part 1:  8388608 bytes  ETag "3e3f52e9a69f740df7004ae6554d6dbf"
  part 2:  8388608 bytes  ETag "c81ae3b984b06f33fadd37f7613920c9"
  part 3:  8388608 bytes  ETag "d390501fd3a78aef87c164b13e562684"
  part 4:  6414936 bytes  ETag "b15af91d166a38ca452ba12d0a9ab0b4"
honest: {'status': 'scanning', 'etag': '"d287e837dc1eed4bbe0aea01f951f494-4"'}
sign part 99: part 99 is not part of this upload
complete with 2 of 4 parts: expected parts 1-4, got [1, 2]
wrong ETag: InvalidPart
oversized part: 403 SignatureDoesNotMatch

The final ETag ends in -4, the number of parts. The API refused part 99 and the short part list itself. Storage refused the made-up ETag with InvalidPart and the oversized last part with 403 SignatureDoesNotMatch, because its length differs from the signed one. Only a server that checks signatures shows this: moto, a popular S3 fake, accepted both when this example was tested. No browser sent a CORS preflight in this run, so try the rule from a real page.

04. Checking, scanning and processing in the background

Once the bytes are in storage, the file needs work before anyone may download it: a malware scan, a thumbnail, perhaps transcoding. Doing it inside the upload request ties up a web worker. Instead, complete sets the row to scanning and queues a job (Celery, RQ, SQS), or storage sends an s3:ObjectCreated:* event. Only the job may move the file to ready or rejected.

Queues deliver at least once, so a job can run twice, even at the same time. Every final update is therefore conditional (… AND status = 'scanning'): the first decision wins, a late copy cannot flip rejected back to ready. A file that is not what it claims, carries malware or cannot be decoded is rejected at once. Storage or scanner trouble is retried, and when the retries run out the file is rejected rather than left in scanning.

The job is written for large files:

  1. Type check on the first bytes. A ranged GET fetches the first 1,445 bytes, the resource header size used by the WHATWG MIME Sniffing standard, and sniff_type checks the magic bytes: %PDF-, the PNG signature, the JPEG start marker, or for MP4 an ftyp box with an mp4 brand. The client's Content-Type is only a claim.
  2. Streamed malware scan. clamd_scan feeds iter_chunks(65536) from the S3 response into clamd's INSTREAM command, so the worker holds 64 KiB at a time. FOUND rejects the file; any other reply except OK is a scanner problem and is retried.
  3. Only small images are decoded. The worker writes a re-encoded copy without EXIF (GPS included) and a thumbnail to new keys, and the conditional UPDATE switches storage_key to them. The upload is never overwritten while a duplicate job may still be reading it with IfMatch, so a duplicate cannot see a changed object and reject a clean file; the job that loses the race deletes its own copies. A failed attempt can also leave copies behind, so a periodic sweep should delete clean/ and thumbnails/ objects no row points to.

Every read uses IfMatch with the ETag recorded by complete, so an object replaced afterwards is rejected. get_session comes from a small db.py on lesson 03's database, which gains a thumbnail_key column.

Python · worker.py, part 1: limits and type sniffing
import io
import socket
import struct
import uuid
from collections.abc import Iterable

from botocore.exceptions import BotoCoreError, ClientError
from celery import Celery
from PIL import Image
from sqlalchemy import text

from db import get_session
from mpu_api import BUCKET, MAX_BYTES, s3

celery_app = Celery("file_pipeline", broker="redis://localhost:6379/0")
CLAMD = ("clamav", 3310)  # clamd, e.g. from the clamav/clamav container image
IMAGE_LIMIT = 10 * 1024 * 1024  # images come through lesson 03's 10 MB POST policy
SIGNATURES = {b"\xff\xd8\xff": "image/jpeg", b"\x89PNG\r\n\x1a\n": "image/png",
              b"%PDF-": "application/pdf"}


class Rejected(Exception):
    """A problem with the file itself; retrying cannot fix it."""


class ScannerError(Exception):
    """clamd could not give a verdict (down, misconfigured); worth a retry."""


def is_mp4(head: bytes) -> bool:
    """The 'signature for MP4' check from the WHATWG MIME Sniffing Standard."""
    size = int.from_bytes(head[:4], "big")
    if len(head) < 12 or len(head) < size or size % 4 or head[4:8] != b"ftyp":
        return False
    brands = [head[8:11]] + [head[i:i + 3] for i in range(16, size, 4)]
    return b"mp4" in brands


def sniff_type(head: bytes) -> str | None:
    """Content type from the file's first bytes, never from the client."""
    if is_mp4(head):
        return "video/mp4"
    return next((t for sig, t in SIGNATURES.items() if head.startswith(sig)), None)
Python · worker.py, part 2: streamed scan and conditional finish
def clamd_scan(chunks: Iterable[bytes]) -> str:
    """Stream chunks to clamd (INSTREAM) without holding the file in memory."""
    with socket.create_connection(CLAMD, timeout=120) as sock:
        sock.sendall(b"zINSTREAM\0")
        for chunk in chunks:
            sock.sendall(struct.pack("!L", len(chunk)) + chunk)
        sock.sendall(struct.pack("!L", 0))
        verdict = sock.recv(4096).rstrip(b"\0").decode()
    if verdict.endswith(" FOUND"):  # malware, or a limit hit with AlertExceedsMax
        raise Rejected(verdict)
    if not verdict.endswith(" OK"):  # e.g. 'INSTREAM size limit exceeded. ERROR'
        raise ScannerError(verdict)
    return verdict


def finish(session, file_id: str, status: str, **extra) -> str:
    # Only a row still in 'scanning' may change: a duplicate or late
    # delivery can never flip 'rejected' back to 'ready', or the reverse
    sets = "".join(f", {k} = :{k}" for k in extra)
    changed = session.execute(
        text(f"UPDATE stored_files SET status = :status{sets}"
             " WHERE id = :id AND status = 'scanning'"),
        {"status": status, "id": file_id, **extra}).rowcount
    session.commit()
    if changed:
        return status
    # Another delivery decided first: report what the row really says
    return session.execute(text("SELECT status FROM stored_files WHERE id = :id"),
                           {"id": file_id}).scalar_one()
Python · worker.py, part 3: cleaning images
def clean_image(data: bytes) -> tuple[bytes, bytes]:
    """Re-encode the original (drops EXIF, including GPS) and make a thumbnail."""
    try:
        with Image.open(io.BytesIO(data)) as img:
            img.load()
            original = io.BytesIO()
            img.save(original, format=img.format)  # no exif= argument: EXIF dropped
            img.thumbnail((400, 400))
            thumb = io.BytesIO()
            img.save(thumb, format="WEBP", quality=85)
    except Exception as exc:  # local decoding only: OSError, SyntaxError, ...
        # Pillow raises many types for broken input (a truncated file gives
        # OSError, a corrupt PNG chunk SyntaxError); all fail every time
        raise Rejected(f"cannot decode image: {exc!r}") from exc
    return original.getvalue(), thumb.getvalue()
Python · worker.py, part 4: the Celery task, checks and scan
@celery_app.task(bind=True, max_retries=3, default_retry_delay=60)
def process_upload(self, file_id: str) -> str:
    """Runs after complete() set the row to 'scanning'."""
    session = get_session()
    try:
        row = session.execute(text(
            "SELECT storage_key, content_type, etag, status"
            " FROM stored_files WHERE id = :id"), {"id": file_id}).one()
        if row.status != "scanning":
            return row.status  # redelivered task: already decided
        # IfMatch on every read: refuse an object replaced after complete()
        get = {"Bucket": BUCKET, "Key": row.storage_key, "IfMatch": row.etag}
        # 1. Type check on the first 1,445 bytes (WHATWG's resource header size)
        head = s3.get_object(**get, Range="bytes=0-1444")["Body"].read()
        if sniff_type(head) != row.content_type:
            raise Rejected("content does not match the declared type")
        obj = s3.get_object(**get)
        size = obj["ContentLength"]
        is_image = row.content_type.startswith("image/")
        if size > (IMAGE_LIMIT if is_image else MAX_BYTES):
            raise Rejected(f"{size} bytes is over the limit for this type")
        # 2. Malware scan, streamed in 64 KiB chunks: memory use stays flat
        clamd_scan(obj["Body"].iter_chunks(65536))
Python · worker.py, part 5: new keys for clean copies, and errors
        extra = {}
        if is_image:  # 3. Small images: a clean copy and a thumbnail, at new keys
            original, thumb = clean_image(s3.get_object(**get)["Body"].read())
            # The upload itself stays untouched while we work, so a duplicate job's
            # IfMatch reads still succeed; each attempt writes keys of its own
            run = uuid.uuid4().hex[:12]
            clean_key = f"clean/{file_id}-{run}"
            thumb_key = f"thumbnails/{file_id}-{run}.webp"
            put = s3.put_object(Bucket=BUCKET, Key=clean_key, Body=original,
                                ContentType=row.content_type)
            s3.put_object(Bucket=BUCKET, Key=thumb_key, Body=thumb,
                          ContentType="image/webp")
            extra = {"storage_key": clean_key, "etag": put["ETag"],
                     "thumbnail_key": thumb_key}
        status = finish(session, file_id, "ready", **extra)
        if extra:  # did our conditional UPDATE switch the row to our copy?
            won = session.execute(text("SELECT storage_key FROM stored_files"
                                       " WHERE id = :id"), {"id": file_id}).scalar_one()
            spare = [row.storage_key] if won == clean_key else [clean_key, thumb_key]
            for key in spare:  # the EXIF original, or the copies that lost
                s3.delete_object(Bucket=BUCKET, Key=key)
        return status
    except Rejected:
        session.rollback()
        return finish(session, file_id, "rejected")  # permanent: no retry
    except (ClientError, BotoCoreError, OSError, ScannerError) as exc:
        session.rollback()
        code = getattr(exc, "response", {}).get("ResponseMetadata", {}).get(
            "HTTPStatusCode", 500)
        if code < 500 or self.request.retries >= self.max_retries:
            # 4xx (object missing or replaced) or retries used up
            return finish(session, file_id, "rejected")
        raise self.retry(exc=exc)  # transient: storage or scanner trouble
    finally:
        session.close()
Python · db.py
import os

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

# The same database as lesson 03; this lesson adds one column for thumbnails:
# ALTER TABLE stored_files ADD COLUMN thumbnail_key TEXT
engine = create_engine("sqlite:///" + os.environ.get("FILES_DB", "files.db"))


def get_session() -> Session:
    return Session(engine)

clamd has its own size limits, far below a 1 GiB upload by default. Past StreamMaxLength (default 100M) clamd answers INSTREAM size limit exceeded. ERROR, which this worker retries and finally rejects. A file over MaxFileSize (default 100M) is not scanned, and one over MaxScanSize (default 400M) is scanned only up to that amount, yet both are reported OK unless AlertExceedsMax yes turns them into a Heuristics.Limits.Exceeded FOUND. ClamAV cannot scan files over 2 GB, hence MAX_BYTES of 1 GiB. Raise the limits to the upload limit or route larger files elsewhere; the clamd.conf sample warns that high limits cost scanner memory and time.

The worker was tested with Celery 5.7 in eager mode, SeaweedFS and a small fake clamd that speaks INSTREAM, flags the EICAR test string and enforces a stream limit. The 30 MiB MP4 became ready (the job held under 5 MiB of Python memory); HTML labelled video/mp4, MP4 plus EICAR, a truncated JPEG, a corrupt PNG and a replaced object were rejected; a duplicate job left the photo ready with one clean copy; and with a 25M stream limit the MP4 was retried, then rejected. Check the limits with the real clamav/clamav container.

clamd.conf · limits for a 1 GiB upload (excerpt; not run here)
StreamMaxLength 1024M
MaxFileSize 1024M
MaxScanSize 1024M
AlertExceedsMax yes

05. Check your understanding

Practice check · 3 questions

Large upload architecture and pipeline check

Three questions about browser multipart uploads, unfinished uploads and duplicate processing jobs.

Q1. A browser app uploads all four parts of a file with presigned PUT URLs, and every PUT returns 200. But `response.headers.get("ETag")` is `null` for each part, so the call to `complete` cannot be built. What is the most likely fix?
Q2. What happens if an app never aborts failed multipart uploads and has no lifecycle rule for them?
Q3. A late duplicate of the processing task arrives for a file that is already `rejected`. Why does the worker's final UPDATE not set it to `ready`?
Practice only: not graded, not saved, not evidence.

06. Apply it

Extend your practice service:

  • Accept files over 10 MB through start, sign_part and complete endpoints like the ones above, with the CORS rule and an AbortIncompleteMultipartUpload lifecycle rule on the bucket.
  • Upload a 200 MB file from a script in four parallel parts, stop it halfway, and make a rerun upload only the missing parts.
  • Run the worker from a real queue against the clamav/clamav container with the limits above, and test that a renamed HTML file, the EICAR string and a truncated JPEG end as rejected, the 200 MB file ends as ready, and a duplicate job cannot change a decided file.

07. Review prompt

Describe the four steps of a multipart upload and what the client keeps from each part. Explain why the bucket must expose ETag, how a signed ContentLength stops a client sending more than it declared, and why complete must still check the part list and the size. Then explain how the worker checks and scans a large file without loading it into memory, which clamd limits must match the upload limit, and why the clean copy goes to a new key.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check