Designing File Uploads: Presigned URLs, Resumable Uploads, Scanning and Processing Pipelines
The first version of the upload endpoint is twelve lines: accept a multipart form, write the file to S3, insert a row, return 201. It works in the demo. In production, a user on a train uploads a 40 MB video. The connection drops at 38 MB and the upload starts again from zero, three times. Meanwhile each in-flight upload holds an app server worker for the whole transfer, so 2,000 slow mobile uploads tie up 2,000 workers, and the API that serves the home feed starts timing out because there is nobody left to answer it.
Then security asks what stops someone uploading a 4 GB file named cat.jpg that is actually an executable, or an SVG with an embedded script that runs when another user opens it. The honest answer is “nothing”.
File uploads look like a CRUD endpoint and behave like a distributed system: large payloads over unreliable networks, untrusted content, asynchronous processing and global delivery. This article designs one properly.
What a file upload system is
An upload system takes bytes from an untrusted client, stores them durably, verifies they are what they claim to be, transforms them into the forms the product needs (thumbnails, transcodes, previews), and makes them available to the right people through a CDN. It has four planes:
- Control plane: your API. Authenticates the user, enforces quotas, decides the object key, issues upload credentials, records metadata.
- Data plane: the bytes, which should flow from client to object storage without passing through your servers.
- Processing plane: asynchronous workers that scan, validate and transform.
- Delivery plane: a CDN serving processed variants, often with signed URLs, covered in CDN and edge caching.
How it works
Direct-to-storage with presigned URLs
Routing bytes through app servers costs bandwidth, memory and worker time for the full duration of each upload, which on mobile can be tens of seconds. Instead, the API hands the client a presigned URL: a URL to the bucket that embeds your credentials’ signature, an expiry, and the exact operation allowed. The client uploads straight to storage.
sequenceDiagram participant C as Client participant A as Upload API participant S as Object storage participant Q as Queue C->>A: POST /uploads with size, type, sha256 A->>A: Auth, quota check, choose key A-->>C: Presigned URL, upload id, expires in 10 min C->>S: PUT bytes to presigned URL S-->>C: 200 with ETag S->>Q: ObjectCreated event C->>A: POST /uploads/id/complete A-->>C: 202 processing
Two flavours on S3, and the difference matters:
- Presigned PUT. Signs one
PUTto one key. You can sign specific headers such asContent-Type, an exactContent-Lengthandx-amz-checksum-sha256, so the upload must match them. You cannot express a size range. - Presigned POST with a policy. The client submits an HTML form-style
POST, and a signed policy document lists conditions S3 enforces:content-length-range(say, 1 byte to 25 MB),starts-withon the key, an exactContent-Type, and an expiry. This is the right tool when the browser does not know the exact size in advance or you want a hard size cap.
Rules that keep this safe:
- The server picks the key, for example
uploads/2026/11/30/<uuid>, never the user’s filename. User filenames go in metadata. - Short expiry, minutes not days. With SigV4, a presigned URL cannot outlive 7 days, and one signed with temporary credentials dies when those credentials do.
- Upload into a quarantine location, not the bucket the CDN serves from.
- Configure bucket CORS for browser uploads, limited to your origins and the methods you use.
Large files: multipart and resumable uploads
A single PUT that fails at 95% restarts from zero. For anything over a few tens of megabytes, split it.
S3 multipart upload. The API calls CreateMultipartUpload and presigns a URL per part. The client uploads parts in parallel (up to 10,000 parts, each 5 MiB to 5 GiB except the last), retries only failed parts, and the API calls CompleteMultipartUpload with the list of part ETags. ListParts tells a resuming client which parts already arrived. Abandoned uploads keep their parts billed until aborted, so every bucket needs a lifecycle rule with AbortIncompleteMultipartUpload after a few days.
The tus protocol. An open protocol for resumable uploads over HTTP. The client creates an upload with POST, sends bytes with PATCH carrying an Upload-Offset header, and after a disconnect asks HEAD for the current offset and continues from there. Client libraries exist for browsers, iOS and Android, and servers such as tusd can store into S3. Use tus when you want byte-level resume behind your own endpoint rather than part-level resume against S3.
The IETF resumable uploads draft (draft-ietf-httpbis-resumable-upload, in the HTTP working group) standardises a similar approach for plain HTTP. As of November 2026 it is still an Internet-Draft, not an RFC.
Part size is a trade-off. Small parts (8 MiB) waste little on a retry and allow fine progress bars; large parts mean fewer requests. With 10,000 parts as the ceiling, a 100 GiB file needs parts of at least about 10.3 MiB.
Integrity
Corruption happens in memory, in proxies and in buggy clients. Verify end to end:
- The client computes a checksum (SHA-256 or CRC) before uploading and sends it in the create request.
- The upload carries the checksum header (
x-amz-checksum-sha256or a CRC variant). S3 rejects the upload if the bytes do not match. Since December 2024 S3 also calculates a CRC checksum by default for uploads that do not supply one, and current AWS SDKs send CRC checksums automatically. - The worker that processes the file verifies the stored checksum against the one recorded in the database before marking the upload valid.
Validation, quarantine and malware scanning
Never trust the client’s Content-Type or file extension. The processing pipeline should:
- Check size against the policy, even though the policy already enforced it.
- Sniff the real type from magic bytes, and reject anything not on an allowlist.
- Scan for malware with an engine such as ClamAV or a managed service. Amazon GuardDuty Malware Protection for S3 scans new objects and tags them with the result.
- Re-encode images. Decoding and re-encoding a JPEG or PNG strips metadata (including GPS location in EXIF), discards appended payloads, and normalises dimensions. Treat image decoders as an attack surface: run them in a sandbox with memory and time limits, because decompression bombs (a tiny file that expands to gigapixels) are real.
- Handle dangerous formats explicitly. SVG and HTML can carry scripts. Either convert SVG to a raster, sanitise it, or serve user content from a separate domain with
Content-Disposition: attachmentandX-Content-Type-Options: nosniffso it can never run in your site’s origin. - Only then copy the object from quarantine to the clean bucket and mark it available. Failed files stay in quarantine for review and expire via lifecycle.
The processing pipeline
flowchart LR Q0["Quarantine bucket"] -->|"ObjectCreated event"| Q["Queue with DLQ"] Q --> V["Validate and scan workers"] V -->|"clean"| CB["Clean bucket"] V -->|"rejected"| R["Mark rejected<br/>notify user"] CB -->|"event"| T["Transform queue"] T --> W1["Thumbnail workers"] T --> W2["Transcode workers"] W1 --> D["Derived variants"] W2 --> D D --> CDN["CDN with signed URLs"] style Q0 fill:#FAEEDA,stroke:#854F0B,color:#633806 style Q fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style T fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style CB fill:#E1F5EE,stroke:#0F6E56,color:#085041 style R fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style CDN fill:#E1F5EE,stroke:#0F6E56,color:#085041
The storage service emits an event per new object into a queue (S3 can send to SQS, SNS, Lambda or EventBridge). Workers pull jobs, which decouples upload spikes from processing capacity: if 10x the usual uploads arrive after a holiday, the queue grows and drains over the next hour instead of failing uploads. Queues and dead-letter queues are covered in message queues.
Make every job idempotent. Events can be delivered more than once and workers can crash halfway, so a retry must produce the same result without duplicates. Deterministic output keys (variants/<id>/w640.webp) make reprocessing an overwrite rather than a duplicate. The general technique is in idempotency.
Video transcoding is heavy enough that it usually goes to a dedicated pool or a managed service, with a job per rendition (several resolutions and bitrates for adaptive streaming) and progress tracked in the database.
The upload record moves through a small state machine: pending, uploaded, scanning, processing, ready, or rejected. The client polls or gets a push notification (real-time options) when it becomes ready.
Content-addressed storage and deduplication
If the object key is the hash of the content (blobs/sha256/9f/86d0...), identical files are stored once no matter how many users upload them, and integrity checks are built in because the key is the checksum. A separate table maps users’ files to blobs, with reference counts or periodic garbage collection to delete blobs nobody references.
Trade-offs: the hash must be verified server-side, not trusted from the client; deleting becomes a garbage collection problem; and cross-user deduplication can leak information (“this file already exists” tells an attacker someone else uploaded it), so many systems deduplicate only within one account, or never let the upload API reveal whether a blob already existed.
Quotas, abuse and lifecycle
- Quotas are checked in the control plane before issuing a URL: per-user storage, per-file size, uploads per hour. Reserve the size at create time and reconcile on completion, so a user cannot open 1,000 uploads at once to get around the limit. Request limits use the techniques in rate limiting algorithms.
- Lifecycle rules: expire quarantine objects after a few days, abort incomplete multipart uploads, move originals to cheaper storage classes after 30 to 90 days, and delete derived variants that can be regenerated.
- Deletion: when a user deletes a file, delete the database row first so it disappears from the product, then delete objects asynchronously, and purge CDN copies.
Delivery
Public images go to the CDN with long TTLs and content-addressed or versioned URLs. Private files are served through the CDN with signed URLs or signed cookies that expire in minutes to hours, so the CDN still caches the bytes but only serves them to holders of a valid signature. Serve user content from a separate domain from your app to contain any script that slips through.
Worked example: a photo app at 50 million uploads a day
Set the estimator to 25M daily users, 2 writes per user and an object size of 3,000 KB to reproduce the numbers below, then change the peak factor to see the effect on bandwidth.
Where it breaks
- Trusting the client. File extension,
Content-Type, size and checksum from the client are hints. Enforce size in the POST policy or signed headers, sniff the type server-side and verify checksums. - Long-lived presigned URLs. A URL valid for 7 days that leaks into a log or a chat lets anyone upload or download. Keep expiries in minutes.
- Serving uploads from the app’s origin. An uploaded HTML or SVG file served from your main domain can run script with your cookies. Use a separate domain and
nosniff. - Processing in the request path. Generating thumbnails synchronously before returning makes uploads slow and fragile. Return 202 and process asynchronously.
- Non-idempotent workers. Duplicate events create duplicate variants or double-count quota. Use deterministic output keys and idempotent state transitions.
- No dead-letter queue. A corrupt file that crashes the decoder is retried forever, blocking a worker each time. Move it to a DLQ after a few attempts.
- Orphans. Objects without database rows (client never called complete) and rows without objects (upload failed after create). Reconcile with a periodic job and lifecycle expiry on the quarantine prefix.
- Hot prefixes. Very high upload rates into one key prefix can hit per-prefix request limits. Spread keys with a high-cardinality component early in the key, such as a hash prefix.
Real-world systems
- Amazon S3, Google Cloud Storage, Azure Blob Storage and Cloudflare R2 all support presigned or signed URLs for direct uploads and multipart or resumable uploads.
- tus is used by open source tools and SaaS upload services; tusd is the reference server and can store into S3 or GCS.
- S3 Event Notifications to SQS or EventBridge, and Lambda triggers, are the standard glue for the processing pipeline.
- Amazon GuardDuty Malware Protection for S3 scans newly uploaded objects and tags them, which a pipeline can use to gate promotion out of quarantine.
- CloudFront and Cloudflare both support signed URLs or tokens for private media delivery.
How to apply it
- Control plane issues short-lived presigned POST (for size ranges) or PUT (for exact size and checksum) into a quarantine prefix with a server-chosen key.
- Files over about 100 MB use multipart or tus, with parallel parts and resume.
- Client sends a checksum; storage verifies it; worker verifies again.
- Storage events go to a queue with a DLQ; idempotent workers validate, scan, re-encode, and promote to the clean bucket.
- Transform workers create variants with deterministic keys; the record moves to
ready. - Deliver through the CDN from a separate domain, with signed URLs for private content.
- Lifecycle rules: expire quarantine, abort incomplete uploads, tier originals, delete regenerable variants.
- Quotas reserved at create time and reconciled on completion.
| Decision | Default | Switch when |
|---|---|---|
| Upload path | Direct to storage | Tiny files where an extra round trip matters more |
| Credential | Presigned POST policy | Native apps that know exact size: presigned PUT with signed length and checksum |
| Large files | S3 multipart | You need byte-level resume or one protocol across storage backends: tus |
| Processing | Queue plus worker pool | Low volume: serverless functions triggered by events |
| Dedup | Per account | Massive duplicate public content, with care for privacy |
Interview angle
Interview questions
Q1: Why use presigned URLs instead of uploading through the API, and what are the risks?
Bytes go straight from the client to object storage, so app servers do not spend bandwidth, memory or a worker for the length of every upload, and storage scales the data plane for you. The control plane still authenticates, authorises, enforces quotas and chooses the key. Risks: a leaked URL grants whatever it signs until it expires, so keep expiries short and scope each URL to one key; a presigned PUT cannot enforce a size range, so use a POST policy with content-length-range or sign an exact length; and the uploaded content is still untrusted, so it lands in quarantine and is validated before use.
Q2: How do you make large uploads reliable on mobile networks?
Split the file. With S3 multipart, the client uploads parts in parallel using per-part presigned URLs, retries only failed parts, and after an app restart asks the API which parts already arrived (ListParts) before continuing, then the API completes the upload. With tus, the client asks the server for the current offset and continues with a PATCH from that byte. Persist the upload ID on the device so a restart can resume, choose part sizes around 8 to 16 MiB for mobile, and add a lifecycle rule to abort incomplete multipart uploads so abandoned parts stop costing money.
Q3: A thumbnail worker sometimes processes the same image twice and sometimes crashes on a malformed file. How do you fix both?
Duplicates are expected because storage events and queues are at-least-once. Make the job idempotent: write outputs to deterministic keys derived from the upload ID and variant, so a second run overwrites identical bytes, and make the state transition conditional (only move processing to ready once). For the crashing file, run decoders in a sandbox with memory and time limits, cap the number of retries, and send poison messages to a dead-letter queue for inspection while marking the upload rejected so the user gets an answer.
✅ Key takeaways
- Separate the control plane (auth, quota, key choice, metadata) from the data plane (bytes direct to object storage via presigned URLs).
- Presigned POST policies can enforce size ranges; presigned PUT can pin exact headers like length and checksum. Keep expiries in minutes and let the server choose keys.
- Large files need multipart or tus so failures resume instead of restarting; abort incomplete uploads with lifecycle rules.
- Treat every upload as hostile: quarantine, checksum, type sniffing, malware scanning, sandboxed re-encoding, and a separate serving domain.
- Process asynchronously through a queue with idempotent workers and a DLQ; deliver through a CDN with signed URLs.
- At 50 million uploads a day, ingress is about 14 Gbps average and storage grows by about 66 PB a year, so lifecycle tiering dominates cost.
🧠 Check your understanding
0 / 4-
1You need browsers to upload directly to S3 but must reject files larger than 25 MB. What should the API issue?
A POST policy can state a content-length-range that S3 enforces. A presigned PUT can only pin an exact Content-Length if you sign it, not a range, and giving browsers long-lived keys is a serious security risk.
-
2At peak, 1,740 photo uploads per second arrive and each takes about 3 seconds on a phone. Roughly how many uploads are in flight at once?
Little's Law: concurrency equals arrival rate times duration, 1,740 x 3 s = about 5,200. Forgetting the duration gives 1,740. That concurrency is why uploads should bypass app servers.
-
3Storage events sometimes deliver the same new-object notification twice. What is the right worker design?
At-least-once delivery is the norm, so jobs must be safe to repeat; deterministic keys make a rerun an overwrite. Relying on exactly-once delivery from the queue is a misconception, deleting originals loses data, and synchronous processing makes uploads slow and fragile.
-
4Why serve user-uploaded files from a separate domain from your web app?
Same-origin policy means script in a file served from your app's domain can act as the logged-in user. A separate domain, plus nosniff and attachment disposition for risky types, contains it. Hit rates and storage requirements are unrelated.
Where to go next
- Message queues: the buffer between upload spikes and processing capacity, with dead-letter queues for poison files.
- Idempotency: making create, complete and processing steps safe to retry.
- Design a news feed: where uploaded media meets fan-out and delivery at scale.
- Cloud cost engineering: storage classes, egress and lifecycle policies are where upload systems spend their money.
Finished this lesson?
Mark it complete to track your progress across the roadmap.