Building a file upload feature usually starts simple. You create a POST route, accept a multipart form payload, write the incoming bytes to disk or database, and call it a day.
In local development with small test images, this pattern works flawlessly. But in production, the moment a user uploads a 2GB file under heavy load, your application degrades quickly.
Handling file streams directly in your API layer causes several critical issues:
- Memory Exhaustion: Buffering large files in application memory causes garbage collection lag or out-of-memory crashes.
- Thread Starvation: Sockets remain open for minutes while uploading slow streams, exhausting server connection pools.
- Database Bloat: Storing binary files (BLOBs) inside relational databases degrades database performance and makes backups unnecessarily massive.
- Security Risks: Accepting files directly on your primary application servers exposes your infrastructure to malware execution, path traversal attacks, and uncontrolled resource usage.
To build an upload pipeline that scales, you must change how files enter your system.
1. Bypass Your API with Pre-Signed URLs
Your application server should act as a controller, not a data pipe. Instead of routing raw binary streams through your backend, offload the transfer to object storage like AWS S3 or Google Cloud Storage.
The standard pattern is to request a pre-signed URL from your API. Your backend authenticates the client, generates a temporary signed authorization link for object storage, and returns that link to the front end. The client then uploads the payload directly to the storage provider.
Here is how to generate a pre-signed upload URL in Node.js using AWS SDK v3:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; import { randomUUID } from "crypto"; const s3Client = new S3Client({ region: "us-east-1" }); export async function generateUploadUrl(userId: string, fileType: string) { // Never trust user filenames. Generate a server-side UUID. const fileKey = `quarantine/${userId}/${randomUUID()}`; const command = new PutObjectCommand({ Bucket: process.env.QUARANTINE_BUCKET_NAME, Key: fileKey, ContentType: fileType, }); // Limit link validity to 15 minutes const presignedUrl = await getSignedUrl(s3Client, command, { expiresIn: 900, }); return { presignedUrl, fileKey }; } With this pattern, your API overhead drops to a lightweight JSON request and response. The network bandwidth and file handling are managed by infrastructure designed specifically for object storage.
2. Quarantine and Process Asynchronously
Never place user uploads directly into public or servable storage buckets. Treat every uploaded file as potentially malicious until validated.
Structure your workflow using isolated buckets:
- Upload to Quarantine: Pre-signed URLs should point only to an isolated staging bucket.
- Event-Driven Signal: The object storage service triggers an event (e.g., AWS SQS, EventBridge, or Webhook) when the file landing is complete.
- Background Validation: Background workers scan the file for viruses, validate file headers (mime-type verification), and extract metadata.
- Promotion or Purge: If the file passes checks, the worker moves it to a clean storage bucket and updates the application database. If it fails, the system deletes it immediately.
Here is a Python worker function handling post-upload validation and movement:
import os import boto3 s3 = boto3.client("s3") def handle_quarantine_file(event_record): source_bucket = event_record["s3"]["bucket"]["name"] file_key = event_record["s3"]["object"]["key"] # 1. Run safety checks (e.g., antivirus, file signature validation) if not is_file_safe(source_bucket, file_key): s3.delete_object(Bucket=source_bucket, Key=file_key) raise ValueError(f"Security check failed for file: {file_key}") # 2. Copy safe file to clean bucket clean_bucket = os.environ["CLEAN_BUCKET_NAME"] destination_key = file_key.replace("quarantine/", "raw/") s3.copy_object( Bucket=clean_bucket, CopySource={"Bucket": source_bucket, "Key": file_key}, Key=destination_key, ) # 3. Clean up the staging area s3.delete_object(Bucket=source_bucket, Key=file_key) By decoupling scanning, image thumbnail generation, and OCR processing into asynchronous jobs, your core user interface stays fast and responsive.
3. Enforce Strict Limits at Every Layer
Defense in depth is required to protect your system from unthrottled payloads. Most frameworks default to high or unmetered body limits. You should enforce boundaries across your network topology:
- Reverse Proxy Layer: Set strict request body limits in Nginx (
client_max_body_size) or your API gateway to reject oversized requests before they touch backend runtimes. - Object Storage Policies: Restrict pre-signed URL conditions by declaring exact
content-length-rangebounds inside the storage command policy. - Rate Limiting: Enforce request limits on presigned URL generation endpoints to stop malicious users from requesting millions of upload tokens.
Decoupling data transport from your API layer protects application memory, improves resilience under high traffic, and helps keep your infrastructure clean.
Tanmay builds AI agents and automation for businesses and is open to freelance projects. Connect on LinkedIn to discuss your backend or automation needs.

