Sub topic 5
Uploading and Ingesting Source Video
This chapter covers how source video gets from a creator's device into your platform and becomes ready for transcoding. It assumes you know basic HTTP, object storage (such as S3), and message queues. It also assumes you have read the architecture overview chapter, so you know where ingest sits in the pipeline.
What Ingest Must Do
Ingest takes a large file from an untrusted client and hands your pipeline a verified, durable source asset. Source files are often several gigabytes. Mobile networks drop. Users close laptops mid-upload. The design has to survive all of that.
Ingest has four jobs:
- Accept the bytes reliably, including resuming after a failure.
- Store them durably, before anything else happens.
- Validate that the file is real, safe, and within limits.
- Signal the transcoding pipeline that a new asset is ready.
The main design decision is that the bytes should not pass through your application servers. API servers handle small JSON requests. Routing multi-gigabyte streams through them ties up connections and memory, and it makes them the bandwidth bottleneck.
Direct-to-Storage Uploads
The standard pattern is to let the client upload straight to object storage using a short-lived signed URL. Your API only authorizes the upload and records metadata.
The flow has a few important properties:
- The signed URL is scoped to one object key and expires in minutes, so a leaked URL has limited value.
- The API chooses the object key. The client never picks its own storage path.
- The upload record has a state (
created,uploading,uploaded,validating,ready,rejected), so the UI and your operators can see where each asset is.
Multipart and Resumable Uploads
A single PUT of a 4 GB file fails if the connection drops at 99%. Multipart upload splits the file into parts that are sent independently and assembled by the storage service.
With S3, the rules are:
- Each part except the last must be at least 5 MiB.
- An upload can have at most 10,000 parts, and a part can be at most 5 GiB.
- Parts can be sent in parallel and retried individually.
- Uploaded parts are billed until the upload is completed or aborted.
Choose a part size that keeps you under the part limit. For a 50 GB file, 64 MiB parts give about 800 parts. Larger parts mean fewer requests but more bytes to resend after a failure.
The client keeps a list of completed part numbers and ETags. After a failure, it asks the API (which calls ListParts) which parts already exist and uploads only the missing ones. If you need to support non-S3 clients or browsers on unreliable networks, an open protocol such as tus offers resumable uploads with the same idea: the server reports an offset, and the client continues from it.
The server-side code below shows how an API can start a multipart upload and issue signed URLs for each part. It uses boto3.
import math
import uuid
import boto3
s3 = boto3.client("s3")
BUCKET = "video-source-uploads"
PART_SIZE = 64 * 1024 * 1024 # 64 MiB
URL_TTL_SECONDS = 900
def create_upload(filename: str, size_bytes: int, user_id: str) -> dict:
asset_id = str(uuid.uuid4())
key = f"incoming/{user_id}/{asset_id}/source"
part_count = math.ceil(size_bytes / PART_SIZE)
if part_count > 10_000:
raise ValueError("file too large for the configured part size")
mpu = s3.create_multipart_upload(
Bucket=BUCKET,
Key=key,
Metadata={"original-name": filename, "asset-id": asset_id},
)
urls = [
s3.generate_presigned_url(
"upload_part",
Params={
"Bucket": BUCKET,
"Key": key,
"UploadId": mpu["UploadId"],
"PartNumber": n,
},
ExpiresIn=URL_TTL_SECONDS,
)
for n in range(1, part_count + 1)
]
return {
"assetId": asset_id,
"uploadId": mpu["UploadId"],
"partSize": PART_SIZE,
"urls": urls,
}
def complete_upload(key: str, upload_id: str, parts: list[dict]) -> None:
# parts: [{"PartNumber": 1, "ETag": "..."}, ...] sorted by PartNumber
s3.complete_multipart_upload(
Bucket=BUCKET,
Key=key,
UploadId=upload_id,
MultipartUpload={"Parts": parts},
)Pre-signing every part URL up front is simple, but a 10,000-part upload produces a large response. For very large files, issue URLs in batches on request.
Add a bucket lifecycle rule that aborts incomplete multipart uploads after a set time, such as seven days. Without it, abandoned parts stay in storage and keep costing money.
Integrity Checks
Network corruption is rare, but a corrupted source is expensive. It shows up as broken output after the transcode has already run. Check integrity at two points.
- Per part: the client sends a checksum header (for example
x-amz-checksum-sha256) with each part, and storage rejects parts that do not match. - Whole file: the client declares a checksum when it creates the upload. A validation step compares it with the stored object's checksum before transcoding starts.
A mismatch moves the asset to rejected and tells the client to re-upload. It should not fail later in the transcoder with an unclear error.
Validating the Source
Passing the upload does not mean the file is a usable video. Validation runs asynchronously, triggered by the storage event, so a slow check never blocks the client.
Typical checks:
- Size and type limits. Enforce a maximum size, and check the real container format from the file's bytes, not its extension or the
Content-Typeheader the client supplied. - Probe the streams. Run
ffprobeto read the container, codecs, duration, resolution, frame rate, and audio tracks. Reject files with no video stream or a zero duration. - Policy limits. For example, a maximum duration, a maximum resolution, or unsupported codecs.
- Safety scanning. Scan for malware, and run content-policy checks such as hash matching against known-abuse lists, if your product requires them.
ffprobe -v error -print_format json -show_format -show_streams source.mp4Store the probe output as asset metadata. The transcoding and bitrate-ladder stages use it later, for example to skip upscaling a 480p source into a 1080p rendition, or to detect a rotation flag from a phone.
Decoupling Ingest from Transcoding
Do not call the transcoder directly from the upload handler. Put a durable queue between them. The storage event feeds validation, and a successful validation publishes an AssetReady message that the transcoding pipeline consumes.
This gives you several benefits:
- Upload spikes, such as a popular event ending, do not overwhelm transcoding workers. The queue absorbs the burst.
- Failed jobs can be retried or sent to a dead-letter queue for inspection.
- Ingest and transcoding scale and deploy independently.
Make consumers idempotent. Storage events and queue deliveries are usually at-least-once, so the same ObjectCreated event can arrive twice. Key the work on the asset ID and check the asset's state before acting. A repeated message for an asset already in validating or ready should do nothing.
Source Storage and Retention
Keep the original upload. Transcoding settings improve over time, and new codecs such as AV1 may justify re-encoding the whole catalog. Without the source you cannot do that at full quality.
Source files are written once and read rarely, so after transcoding, move them to a cheaper storage class, such as an infrequent-access or archive tier. Keep the incoming bucket separate from the bucket that holds finished renditions. This lets you apply stricter access rules and different lifecycle policies to each.
Other Ingest Paths
User uploads are not the only way video arrives.
| Path | Typical use | Notes |
|---|---|---|
| Browser or app upload | User-generated content | Multipart or tus, signed URLs |
| Server-to-server transfer | Studio or partner deliveries | Often over SFTP or a bulk transfer tool, with a manifest file listing expected checksums |
| Pull from a URL | Importing from another service | The server fetches the file, so block requests to internal addresses to prevent server-side request forgery |
| Live contribution | Live streaming | Uses protocols such as RTMP or SRT, covered in the live streaming chapter |
All paths should end in the same place: an object in the incoming bucket, a record in the metadata store, and the same validation step.
Common Errors
- Proxying uploads through the API. It works in testing and fails under load. Use signed URLs.
- No abort lifecycle rule. Abandoned parts accumulate cost.
- Trusting the file extension or MIME type. Probe the actual content.
- Non-idempotent event handlers. Duplicate events create duplicate transcode jobs.
- Signed URLs that live too long or are not scoped to one key. They become a way to write arbitrary objects.
- Deleting the source after transcoding. You lose the ability to re-encode later.
Exercise
A user uploads a 40 GB file using 5 MiB parts to an S3-compatible store that allows at most 10,000 parts per upload. Why does the upload fail, and what is the smallest part size, in whole MiB, that works?
Show answer
40 GB is 40 × 1024 MiB = 40,960 MiB. With 5 MiB parts that is 8,192 parts, which fits under the limit, so the part count is fine. The failure comes from using a smaller count than needed only if the size is larger: if "GB" means 40 GiB, 40,960 / 5 = 8,192 parts, which is under 10,000. The upload therefore does not fail on the part limit at all. The smallest workable part size is ceil(40,960 / 10,000) = 5 MiB, which is also the minimum allowed part size. In practice you would still pick a larger part size, such as 64 MiB (640 parts), to reduce request overhead.
Exercise
The storage service delivers the same ObjectCreated event twice for one upload. What prevents two transcode jobs from being started for the asset?
Show answer
The handler is idempotent. It keys on the asset ID and checks the asset's state in the metadata store before acting, ideally with an atomic conditional update such as moving from uploaded to validating only if the current state is uploaded. The second event finds the state already changed and does nothing.