Designing File Upload Systems for Scale
Build file upload systems that handle large files: chunked uploads, resumable transfers, size and type guards, and async virus scanning.
On this page
Introduction
Uploading a profile avatar is easy. Uploading a four-gigabyte video over a flaky mobile connection, resuming it after the train goes through a tunnel, scanning it for malware before it reaches your storage, and doing this for ten thousand concurrent users — that is hard. Most file upload code is written for the easy case and breaks under the hard one: requests that time out at the server’s body-size limit, partial files left on disk when the connection drops, memory exhaustion from buffering the whole file, and a storage bucket that becomes a malware repository.
This article designs a file upload system for scale. We cover streaming to avoid buffering, chunked and resumable uploads for large files and unreliable networks, size and type validation at every layer, and asynchronous virus scanning with a quarantine workflow. The examples are in Node.js, but the architecture is language-agnostic.
Never Buffer the Whole File in Memory
The first rule of handling uploads is never to hold the entire file in memory. A naive req.body or await uploadfile.read() that buffers a two-gigabyte file will exhaust your process memory and crash under concurrent load. The fix is to stream: pipe the request body to storage in fixed-size chunks so memory usage is constant regardless of file size.
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { randomUUID } from "node:crypto";
async function streamUpload(req: Request, destDir: string): Promise<{ path: string; size: number }> {
const id = randomUUID();
const dest = `${destDir}/${id}.tmp`;
let size = 0;
// Track bytes as they flow, enforcing the size limit mid-stream.
const counter = new Transform({
transform(chunk, _enc, cb) {
size += chunk.length;
if (size > MAX_BYTES) cb(new Error("file too large"));
else cb(null, chunk);
},
});
await pipeline(req.body, counter, createWriteStream(dest));
return { path: dest, size };
}
The pipeline from node:stream/promises is important: it destroys all streams and propagates the error if any stage fails, so a client disconnect mid-upload does not leave a half-written file leaking a file descriptor. The size check inside the Transform aborts the stream the moment the limit is exceeded, rather than waiting for the upload to finish — a client sending a hundred-gigabyte file is cut off after MAX_BYTES, not after a hundred gigabytes.
Validate Size and Type Before You Store Anything
Validate at three layers: the client (for UX), the edge (cheap, synchronous), and the storage boundary (authoritative). Client validation is a courtesy; the server is the guarantee. Check the size from the Content-Length header before you start streaming — a request declaring a fifty-gigabyte body can be rejected with a 413 Payload Too Large before a single byte is written. Then enforce the limit again on the actual bytes, because Content-Length can be missing or lie.
File type is harder than it looks. The file extension is user-controlled and meaningless. The Content-Type header is user-controlled and frequently wrong. The only reliable check is a magic number (file signature) read from the first bytes of the stream. A PNG begins with \x89PNG\r\n\x1a\n; a JPEG with \xff\xd8\xff. Libraries like file-type sniff the leading bytes and return the detected type.
import { fileTypeFromBuffer } from "file-type";
const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
const MAX_BYTES = 100 * 1024 * 1024; // 100 MB
async function validateType(head: Buffer) {
const type = await fileTypeFromBuffer(head);
if (!type || !ALLOWED.has(type.mime)) throw new UploadError(415, "unsupported file type");
return type.mime;
}
Sniffing the type from the leading bytes defeats the user who renames malware.exe to avatar.png. Combine it with an allowlist (never a denylist — you will forget a type) and you have a type check that cannot be spoofed by renaming.
Chunked and Resumable Uploads
For large files and unreliable networks, a single monolithic request is the wrong shape. If a thirty-minute upload fails at ninety-nine percent, the user starts over from zero. Chunked upload splits the file into fixed-size pieces (say, five megabytes), uploads each as a separate request, and lets the server assemble them. If a chunk fails, only that five-megabyte chunk is retried. If the connection drops, the client resumes from the next unacknowledged chunk.
The protocol is simple. The client requests an upload session; the server returns an upload id. The client uploads chunks to /uploads/:id/chunks/:index; the server acknowledges each. When all chunks are present, the client calls /uploads/:id/complete and the server concatenates (or, better, the chunks were appended in order and the file is already complete) and moves it to final storage.
// Server: accept one chunk, append to the partial file.
router.put("/uploads/:id/chunks/:index", rawBody({ limit: CHUNK_BYTES }), async (req, res) => {
const { id, index } = req.params;
const session = await uploads.get(id);
if (!session) return res.status(404).end();
if (req.body.length > CHUNK_BYTES) return res.status(413).end();
// Append at the expected offset; reject out-of-order or duplicate chunks.
const offset = Number(index) * CHUNK_BYTES;
await appendFile(session.partialPath, req.body, offset);
await uploads.markChunk(id, Number(index));
res.json({ received: Number(index), complete: session.isComplete() });
});
// Client: resume by asking which chunks the server already has.
async function resumeUpload(id: string, file: File) {
const { chunks } = await fetch(`/uploads/${id}/status`).then(r => r.json());
const total = Math.ceil(file.size / CHUNK_BYTES);
for (let i = 0; i < total; i++) {
if (chunks.includes(i)) continue; // already have it — skip
const blob = file.slice(i * CHUNK_BYTES, Math.min((i + 1) * CHUNK_BYTES, file.size));
await fetch(`/uploads/${id}/chunks/${i}`, { method: "PUT", body: blob });
}
await fetch(`/uploads/${id}/complete`, { method: "POST" });
}
The resume endpoint is what makes the system resilient to dropped connections and page reloads. The client asks the server which chunks it already has and uploads only the gaps. This is the same idea behind the tus.io protocol and S3 multipart uploads — split, acknowledge, resume.
Asynchronous Virus Scanning and the Quarantine
Scanning every file synchronously during the upload request couples your response time to the scanner’s load and the file’s size. Instead, move the file to a quarantine area, return 202 Accepted to the client immediately, and scan asynchronously. The file becomes visible to the user only after the scan passes.
async function completeUpload(id: string) {
const session = await uploads.get(id);
if (!session.isComplete()) throw new Error("incomplete");
const staged = await moveToQuarantine(session.partialPath); // not yet user-visible
await scanQueue.add({ fileId: id, path: staged }); // async job
return { status: "processing", fileId: id };
}
// Worker
scanQueue.process(async (job) => {
const { fileId, path } = job.data;
const clean = await clamav.scan(path); // clamdscan, or an external scanner
if (clean) {
await moveToStorage(path, fileId); // now user-visible
await uploads.setStatus(fileId, "ready");
} else {
await moveToQuarantineVault(path, fileId); // isolated, never visible
await uploads.setStatus(fileId, "rejected");
await audit.log({ fileId, reason: "malware detected" });
}
});
The quarantine is the safety net. A file that has not passed scanning is never in a location the application serves to users. If the scanner is down, files pile up in quarantine rather than being served unscanned — fail closed, not open. Surface the scan status to the client via a status endpoint or a websocket so the UI can show “scanning…” and then “ready” or “rejected.”
Idempotency and Deduplication
Uploads are expensive; users retry them. Make the upload idempotent by keying the session on a client-generated id (a UUID or a content hash). If the client retries the POST /uploads with the same id, return the existing session instead of creating a new one. For deduplication, hash the file content (a streaming SHA-256 computed during upload) and check storage before writing — if an identical file already exists, return a reference to it instead of storing a second copy. This is how S3-style deduplication and content-addressable storage work, and it saves meaningful bandwidth and space for files that many users upload identically.
Storage Backends, Direct-to-Cloud Uploads, and Upload UX
Where the file lands after it passes validation is an architecture decision with long-term consequences. The three common backends are local disk, a networked filesystem, and object storage (S3, GCS, Azure Blob). Local disk is simplest but does not scale past a single host — a file uploaded to host A is not visible to host B without a shared store, so a multi-instance deployment needs sticky sessions or a shared volume, both of which are fragile. Object storage is the right answer for almost every production system: it is durable, infinitely scalable, served over HTTP with CDN integration, and decoupled from your application servers. Upload to object storage, store the object key in your database, and serve the file through the CDN.
The most important optimization for upload throughput is to keep the file off your application servers entirely. A upload that flows through your API consumes bandwidth, CPU, and memory on the server for bytes you only intend to forward to storage. The direct-to-cloud pattern avoids this: your API issues a short-lived presigned URL that authorizes the browser to upload directly to the object store, and the browser PUTs the file to S3 without it ever touching your servers. Your API’s only job is to authorize the upload and, on completion, record the result.
// API: issue a presigned URL for the browser to upload directly to S3.
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
router.post("/uploads/sign", async (req, res) => {
const { filename, contentType, size } = req.body;
if (size > MAX_BYTES) return res.status(413).end();
if (!ALLOWED.has(contentType)) return res.status(415).end();
const key = `${req.user.id}/${crypto.randomUUID()}/${filename}`;
const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: "uploads", Key: key, ContentType: contentType }), { expiresIn: 300 });
res.json({ uploadUrl: url, key, expiresIn: 300 });
});
// Client: upload directly to S3, then notify the API.
async function uploadDirect(file: File) {
const { uploadUrl, key } = await fetch("/uploads/sign", { method: "POST", body: JSON.stringify({ filename: file.name, contentType: file.type, size: file.size }) }).then(r => r.json());
await fetch(uploadUrl, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
await fetch("/uploads/complete", { method: "POST", body: JSON.stringify({ key }) });
}
The presigned URL is scoped to a single key, a single content type, and a short expiry, so even if it is intercepted it cannot be used to upload a different file or to overwrite an arbitrary object. The size and type validation happen at signing time, before the upload begins, so an invalid request is rejected without a byte transferred. The direct upload moves the bandwidth from your API to the object store, which is built for it, and leaves your API to do the work only it can do — authorization and recording.
Once the file is in object storage, serve it through a CDN. The CDN caches the object at edge locations close to the user, so the second request for the same file is served from the edge with no origin hit. Set a long Cache-Control for immutable, content-addressed files (keyed by a hash so the URL changes when the content does) and a shorter one for files that may be replaced. For private files, use signed URLs for download as well as upload, with a short expiry, so the CDN caches per-signed-URL and a leaked URL expires quickly.
The upload UX is the part the user sees, and it is worth as much attention as the backend. Show progress — the fetch API does not give upload progress, so use XMLHttpRequest or the axios onUploadProgress callback for a progress bar that reflects bytes sent. For chunked uploads, show progress per chunk and an overall indicator. Provide a cancel button that aborts the in-flight request (AbortController) and cleans up the partial upload on the server. For large uploads, show the estimated time remaining and allow the user to navigate away with the upload continuing in a service worker or a background tab, with a notification when it completes. An upload that shows a spinner for ten minutes with no progress is an upload the user assumes has failed; an upload that shows a progress bar is an upload the user trusts.
function uploadWithProgress(file: File, onProgress: (pct: number) => void): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total); };
xhr.onload = () => xhr.status < 400 ? resolve() : reject(new Error(`HTTP ${xhr.status}`));
xhr.open("PUT", uploadUrl); xhr.send(file);
});
}
Conclusion
A file upload system that scales streams instead of buffers, validates size and true type at every layer, splits large files into resumable chunks, scans for malware asynchronously behind a quarantine that fails closed, and makes uploads idempotent so retries are cheap. Each of these is a defense against a specific failure mode: buffering against memory exhaustion, streaming against partial files, chunking against unreliable networks, sniffing against spoofed types, quarantine against malware, and idempotency against wasted work. Build them in and your upload endpoint handles the four-gigabyte video on the train as gracefully as the profile avatar.
Report a problem with this articleOpens a pre-filled issue on GitHub.