Skip to content

    System Design

    File Upload and Media Processing Pipelines

    Design a file upload and media pipeline: direct uploads, resumable parts, untrusted-file quarantine, queued idempotent workers, renditions and safe serving.

    By Published 13 min read

    Share

    Standard lessonintermediateBackend System Design

    Before this: Object and Blob Storage, Message Queues and Pub/Sub

    What you'll learn: By the end of this lesson you will be able to split an upload system into an upload path and a processing path, choose between a single request, multipart and a resumable protocol, treat every uploaded file as untrusted until it has been checked, track a file through states from pending to ready, run processing as idempotent queued jobs, and explain what a video pipeline produces for streaming.

    Think of a baggage hall. You drop a bag at the counter and get a tag. The bag is not put on the aircraft yet: it is screened, labelled, and sorted onto a cart by a different team that works in the back. If a screener drops a bag, the cart is rebuilt from the tag. You never wait at the counter for the whole chain.

    A media pipeline works the same way. The upload path accepts the bytes and gives the client a receipt. A separate processing path checks the file, makes the versions readers need, and flips a status when they exist. This lesson is the design of that whole chain. The storage mechanics (keys, multipart, presigned URLs) are in object and blob storage, the queue mechanics are in message queues, and serving the result is in CDN and edge networking. This is an educational reference design, not the verified internal architecture of any company.

    Verified on 2026-12-02 against the Amazon S3 User Guide, Amazon SQS Developer Guide, Google Cloud Storage documentation, the tus 1.0.0 protocol, RFC 8216 and the OWASP File Upload Cheat Sheet. The arithmetic on this page was run with Node; there is no lab.

    The core idea

    Accept bytes cheaply, trust nothing, and do the slow work later as retry-safe jobs. Four decisions follow: where the bytes go (straight to storage, not through application servers), how a big file survives a bad network (parts or a resumable session), when a file may be used (only after checks, tracked by a status), and how the processing is repeated safely (idempotent jobs with outputs at predictable keys).

    Three illustrations run through it: a minimal example (one image that goes pending, checked, ready), a realistic example (ShopStream store tablets uploading product photos and short videos) and a failure example (a job that runs twice).

    Two paths, not one

    Upload path and processing pathClient to App server (ask for a slot); App server to Database (pending row); Client to Quarantine bucket (bytes, signed); Quarantine bucket to Queue (event); Queue to Workers; Workers to Public bucket (renditions); Workers to Database (mark ready)Client: tablet or appClienttablet or appApp server: authorize, sign, recordApp serverauthorize, sign,recordDatabase: upload statusDatabaseupload statusQuarantine bucket: raw, untrustedQuarantinebucketraw, untrustedQueue: one job per fileQueueone job per fileWorkers: scan, convertWorkersscan, convertPublic bucket: checked outputsPublic bucketchecked outputsask for a slotpending rowbytes, signedeventrenditionsmark ready

    Figure 1. The bytes never touch the app tier. How to read this: the app server authorizes and signs, the client sends the bytes straight to a quarantine bucket, and an event starts a queued job. Workers write checked outputs to a separate bucket and flip the status. The two bucket names are a design choice, not a product feature.

    The upload path (client, app server, database) is judged by latency and success rate; the processing path (queue, workers) by throughput and by how safely it can be repeated. A slow video encode must never make the upload button hang.

    Getting the bytes in

    The default is a presigned URL: the app server checks the user, signs one method, one key and a short expiry, and the client sends the bytes to storage. The S3 guide calls these URLs bearer tokens and notes that an upload URL replaces an existing object with the same key. So the server chooses the key (a unique id), never the client, and the expiry is minutes.

    Large files need more than one request. Three common shapes:

    Shape How it resumes Notes from the sources
    Single PUT It does not: restart from byte zero Simple; S3 suggests considering multipart around 100 MB
    Multipart upload Resend only the failed part S3: three steps (initiate, parts, complete); parts in any order; 1 to 10,000 parts, 5 MiB to 5 GiB each, last part has no minimum
    Resumable session Ask the server how much it has, continue from there tus 1.0.0: HEAD returns Upload-Offset, PATCH continues. Google Cloud Storage: a session URI; query the persisted offset and resume

    The Google documentation adds that anyone holding the session URI can upload to it, so the session URI is a credential too, and that only a completed resumable upload appears in the bucket.

    Choosing a part size

    A smaller part wastes less work when a part fails; a larger part means fewer requests. The limits bound the choice. For a 4 GiB file (illustrative size), this Node script prints the plan for three part sizes:

    const MiB = 1024 * 1024;
    const size = 4 * 1024 * MiB;
    function plan(partSizeMiB) {
      const part = partSizeMiB * MiB;
      const parts = Math.ceil(size / part);
      const last = size - (parts - 1) * part;
      return { partSizeMiB, parts, lastPartMiB: last / MiB, retryCostMiB: partSizeMiB };
    }
    for (const p of [5, 8, 64]) console.log(JSON.stringify(plan(p)));

    Output of that script, run with Node 26.13.1 on 2026-12-02:

    {"partSizeMiB":5,"parts":820,"lastPartMiB":1,"retryCostMiB":5}
    {"partSizeMiB":8,"parts":512,"lastPartMiB":8,"retryCostMiB":8}
    {"partSizeMiB":64,"parts":64,"lastPartMiB":64,"retryCostMiB":64}

    At 5 MiB the file needs 820 parts, well inside the 10,000-part limit, and a failed part wastes at most 5 MiB. The S3 guide adds two bookkeeping rules: the client must record each part number and ETag, because the complete request needs them, and an upload never completed or aborted keeps costing storage (the abort rule is in object and blob storage).

    Checking integrity on the way in

    S3 can verify a checksum you send: the guide says S3 independently calculates a checksum on the server side and validates it against the provided value before storing the object, and lists several algorithms. A mismatch fails the request instead of storing a damaged file. A checksum catches corruption in transit; it says nothing about whether the file is safe.

    Untrusted files

    An uploaded file is attacker-controlled input. The OWASP File Upload Cheat Sheet is the reference list. Its main points, in the order a pipeline applies them:

    • Do not trust the Content-Type header. Validate the type itself, and keep an allow-list of extensions the business needs.
    • Replace the user's filename with a generated one, and cap lengths if names must be kept.
    • Store uploads away from the application, with least-privilege permissions.
    • Set a size limit, and for archives a limit on what they unpack to.
    • Scan with antivirus or a sandbox where possible; for documents consider content disarm and reconstruction.
    • Re-encode images (decode, then encode to an allowed format) so embedded payloads are dropped and metadata can be stripped.

    In this design those controls live in two places: the signed request (who, which key, how big, how long) and a quarantine bucket that readers and the CDN cannot reach. Nothing leaves quarantine until a worker has checked and re-encoded it. See also input validation and injection prevention.

    Knowing a file has arrived

    The client's bytes land in storage with no help from the app server, so something must announce them. Two sources, used together:

    • A storage event. The S3 documentation says event notifications are designed to be delivered at least once, typically in seconds but sometimes a minute or longer. Destinations include SNS, SQS, Lambda and EventBridge. It warns that a notification writing back to the bucket that triggers it can loop, so trigger only on the incoming prefix or use two buckets.
    • A client "done" call. The client tells the app server the upload finished. The server does not trust it: it checks the object exists and matches the recorded key and size before enqueueing.

    Because delivery is at least once, the same file can be announced twice, and the job must tolerate that. The upload record is the single place that knows where a file is:

    stateDiagram-v2 accTitle: States of an uploaded file accDescr: A file starts pending when a slot is issued. It becomes uploaded when bytes are confirmed, then scanning, then ready. A failed check moves it to rejected. A processing error after retries moves it to failed. A pending file that never arrives expires. [*] --> Pending: slot issued Pending --> Uploaded: bytes confirmed Pending --> Expired: never arrived Uploaded --> Processing: job picked up Processing --> Ready: checks and renditions done Processing --> Rejected: check failed Processing --> Failed: retries exhausted Failed --> Processing: manual replay

    Figure 2. One status column, explicit transitions. How to read this: readers only ever see Ready. Every other state is internal. Failed is not a dead end: a replay moves it back to Processing.

    Each transition is a conditional update (where status = 'uploaded'), so a duplicate event finds the row already moved and does nothing. This is the same idea as an idempotency key, applied to a state machine.

    Processing as idempotent jobs

    One file produces one job on a queue. SQS standard queues, for example, ensure at-least-once delivery, may deliver more than one copy, and make only a best-effort attempt to keep order; the guide says they suit work like resizing or encoding media in the background, provided the application handles duplicates and reordering. Its visibility timeout hides a received message from other consumers for 30 seconds by default, and if the worker does not delete the message before it expires, the message reappears for another attempt. That is both the retry mechanism and the source of duplicates. Retry limits and dead-letter queues are in dead-letter queues and retries.

    Three rules make a job safe to run twice:

    1. Outputs at deterministic keys. The 400 px rendition of upload u_7f3 is always written to the same key, built from the upload id and the processing version. A second run overwrites the first with identical bytes.
    2. The status flip is last and conditional. Processing to Ready happens only after every output exists.
    3. The timeout fits the work. If an encode takes longer than the visibility timeout, a second worker starts the same job. Extend the timeout while working, or split the work into smaller jobs.
    sequenceDiagram accTitle: One upload from slot to ready accDescr: The client asks the app server for a slot. The server records a pending row and returns a signed url. The client uploads to quarantine. The storage event enqueues a job. A worker checks and converts the file, writes renditions, then marks the row ready with a conditional update. The client sees ready on its next status request. participant C as Client participant A as App server participant Q as Quarantine bucket participant W as Worker participant P as Public bucket C->>A: request upload slot A-->>C: signed url, upload id C->>Q: PUT bytes Q-->>W: event via queue (at least once) W->>Q: read, scan, re-encode W->>P: write renditions at fixed keys W->>A: mark ready if status is processing C->>A: GET status A-->>C: ready, rendition urls

    Figure 3. The whole path. How to read this: the client talks to the app server only twice (slot, status). The heavy work is between the bucket event and the conditional status update.

    Images and video

    For images, a job reads the original, re-encodes it, and writes a few sizes. Keep the original in a private archive so derived versions can be regenerated. Video has the same shape but costs far more, so it is split. HLS, defined in RFC 8216, is a common streaming format. A Media Playlist lists Media Segments that play in sequence; a Master Playlist lists Variant Streams, each a different version of the same content; and every variant tag must carry a BANDWIDTH attribute, which the RFC defines as the peak segment bit rate. Clients are expected to switch between variants to match network conditions. So a video job fans out: one transcode task per variant, then a packaging step that writes the segments and playlists.

    Video job fan-outOriginal video to Planner job; Planner job to Encode tasks (tasks); Encode tasks to Packaging; Packaging to Public bucket (when all done)Original video: quarantineOriginal videoquarantinePlanner job: one task per variantPlanner jobone task pervariantEncode tasks: run in parallelEncode tasksrun in parallelPackaging: segments, playlistsPackagingsegments,playlistsPublic bucket: then CDNPublic bucketthen CDNtaskswhen all done

    Figure 4. Fan out, then join. How to read this: encodes are independent and can be retried one by one. The playlist is written last, only when every variant exists, so a player never sees a playlist that points at a missing segment.

    Playlist-last is the conditional status flip again: publish the pointer after what it points to. See also the video streaming case and the photo sharing case.

    Serving the result

    Public renditions are immutable: the key includes a version, so the CDN can cache them for a long time and a replaced image gets a new URL. Private files are served through short-lived signed read URLs, with the same bearer-token care as uploads. S3 logs identify the signer, not who later used the URL, so record issuance in the application if you need an audit trail (audit logging).

    Trade-offs

    Choice Gain Cost Wrong when
    Direct upload to storage App tier carries no bytes Signed URLs are credentials; status needs an event You must inspect bytes before storing any
    Multipart or resumable Failed parts retry alone Client part logic; orphan cleanup Files are small
    Quarantine bucket, then promote Hostile files never reach readers Extra copy and delay Files are fully trusted internal data
    Queue plus workers Scales independently; retries At-least-once means duplicates The work is a few milliseconds
    Deterministic output keys Safe to rerun Needs a version in the key Outputs must be unique per run

    Build it

    There is no lab for this lesson. The measured parts are the part-size script above and the shape of the state machine; every service behaviour comes from the documentation cited. A good first build is the status table with conditional updates and a test that delivers the same event twice.

    In practice: ShopStream product photos and short videos

    This is a realistic scenario, not a case history.

    The situation

    ShopStream has 5,000 stores and 100,000 products per region (the shared figures, illustrative). Store staff photograph products and record short clips on tablets over weak links. Today the app servers receive each file, resize it inline and store it. Uploads time out, a slow resize blocks other requests, and one store uploaded a file named like an image that was not one.

    Starting architecture

    Starting architecture: everything in the requestStore tablets to App servers (whole file); App servers to One bucket; App servers to DatabaseStore tabletsStore tabletsApp servers: receive, resize, storeApp serversreceive, resize,storeOne bucket: originals and resizedOne bucketoriginals andresizedDatabase: product rowsDatabaseproduct rowswhole file

    Figure 5. Bytes and CPU in the request path. How to read this: app servers do the slow work while the tablet waits, and everything lands in one bucket that readers also use.

    Options considered

    Option Gain Cost Wrong when
    A. Bigger timeouts, more app servers No new parts Pays for idle CPU; hostile files still reach readers Uploads keep growing
    B. Presigned single PUT plus a worker Bytes skip the app; resize moves out Failed upload restarts from zero Files are large on weak links
    C. Presigned multipart for large files, quarantine bucket, queued idempotent workers, playlist-last video packaging Resumable, isolated, retry-safe Client part logic; more moving parts The team cannot operate a queue

    The decision

    Option C. The app server authorizes the store and product, creates a pending row with a server-chosen key, and returns signed part URLs valid for minutes. Tablets send parts and record ETags. The storage event enqueues one job. Workers check type and size, re-encode, write renditions at deterministic keys to the public bucket and flip the status last. Videos fan out per variant and write the playlist last. A lifecycle rule aborts incomplete multipart uploads, and a pending row older than a day becomes expired.

    Rollout and verification

    Start with photos for a few stores, then add video. Verify that a file with a wrong extension is rejected, the same event delivered twice leaves one set of outputs, a worker killed mid-job is retried, and a Ready row always has every rendition. Watch upload success rate, part retries, queue age and the gap between stored and visible bytes.

    The 2 a.m. failure

    The page reads: "queue age rising, ready rate falling". A new encode step now takes longer than the queue's visibility timeout, so each video is picked up by a second worker while the first is still working. Both write the same keys, the queue backs up with duplicates, and some jobs hit the retry limit.

    flowchart TD accTitle: Duplicate jobs from a short visibility timeout accDescr: A worker receives a video job and starts a long encode. The visibility timeout expires before it finishes. The message becomes visible again and a second worker receives it. Both encode the same video. Duplicates grow the backlog and some reach the retry limit and the dead letter queue. A["Worker 1 receives job"] --> B["Long encode starts"] B --> C{"Done before timeout?"} C -->|yes| D["Delete message, mark ready"] C -->|no| E["Message visible again"] E --> F["Worker 2 receives same job"] F --> G["Backlog grows, retries hit limit"]

    First checks: compare encode duration with the visibility timeout, and look for the same upload id in two workers' logs. Mitigation: extend the visibility timeout while working (the documentation describes a heartbeat) or split the encode into smaller jobs; the deterministic keys mean the duplicate work was wasted but did no harm. Follow-up: alert when job duration approaches the timeout, and replay the dead-letter queue after the fix.

    Architect's notes

    • Choose the key on the server, never from the client's filename.
    • Quarantine first; nothing is public until checked and re-encoded.
    • Publish pointers last: the status row, the playlist.
    • Keep originals so renditions can be regenerated.
    • Measure the gaps: stored versus visible bytes, queue age, job duration versus the timeout.

    Common mistakes

    • Trusting Content-Type or the extension to decide what a file is.
    • Resizing inside the request, or marking a file ready before every output exists.
    • A visibility timeout shorter than the job.
    • Serving from the bucket that receives uploads.
    • Long-lived, broad signed URLs and incomplete multipart uploads with no abort rule.

    Key takeaways

    • Separate the upload path (fast, small) from the processing path (slow, retried).
    • Send bytes straight to storage with a short-lived, narrow signed URL; use parts or a resumable session for large files.
    • Treat every upload as hostile: generated names, size limits, type validation, scanning, re-encoding, quarantine.
    • Storage events and queues deliver at least once; make jobs and status updates idempotent.
    • Write outputs at deterministic keys and flip the status or playlist last.
    • Video fans out per variant and joins; HLS uses a master playlist of variants and media playlists of segments.

    Practice exercises

    Exercise 1 (30 min). Change the script to a 20 GiB file. Which part sizes are even allowed by the 10,000-part limit?

    Exercise 2 (1 hour). Write the SQL for the conditional uploaded to processing update and explain what a duplicate event sees.

    Exercise 3 (2 hours). Design the key scheme for original, thumbnail and playlist objects, including the processing version, so reprocessing never changes what an existing URL returns.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments