Lesson 242 of 296
Design: file upload service
What you will learn
- Why files should not go through your API servers
- Pre-signed URLs for direct uploads to object storage
- Multipart and resumable uploads
- Processing pipelines: virus scanning, thumbnails, validation
- Serving files securely through a CDN
- Metadata, lifecycle and cost
On this page
Requirements
Users upload files (profile photos, documents up to several GB, videos); files are processed (thumbnails, scanning); users download their own files (and maybe share them); uploads should be reliable on weak mobile connections; files must be private unless shared.
Do not stream big files through your API
Uploading a 2 GB video through your Node.js API ties up a server connection for minutes, uses bandwidth twice (client → API → storage), and makes scaling expensive. Instead:
Direct upload with pre-signed URLs
Object storage (Amazon S3, Google Cloud Storage, Azure Blob, Cloudflare R2) stores files ("objects") cheaply and durably at any scale. A pre-signed URL is a temporary URL, signed with your credentials, that allows one specific action (for example PUT to one key) for a limited time, without giving the client any credentials.
1. Client → API: POST /uploads { fileName, contentType, size }
2. API: checks the user may upload, validates type and size, creates an "uploads" record (status: pending),
generates a key like tenants/42/users/7/2026/11/3f2a9c.pdf and a pre-signed PUT URL (expires in 10 minutes)
3. API → Client: { uploadId, url }
4. Client → S3: PUT the file directly to the pre-signed URL
5. S3 → event (S3 event notification → SQS / Lambda) "object created"
6. Worker: verifies the file, scans it, processes it, marks the upload "ready" in the databaseWith the AWS SDK v3:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const s3 = new S3Client({ region: "eu-west-2" });
export async function createUploadUrl(key: string, contentType: string) {
const command = new PutObjectCommand({ Bucket: "jobprep-uploads", Key: key, ContentType: contentType });
return getSignedUrl(s3, command, { expiresIn: 600 });
}Notes:
- Never use the user's file name as the storage key (path tricks, collisions, personal data in keys); generate your own and store the original name as metadata.
- For size limits enforced by storage itself, use a pre-signed POST policy with a
content-length-rangecondition (a pre-signed PUT cannot limit size by itself); still re-check the real size after upload. - Verify the content, not just the declared type: read the file's first bytes ("magic numbers") to confirm it is really a PNG or PDF.
Multipart and resumable uploads
For large files: split into parts (for example 10 MB each), upload parts in parallel, retry only failed parts, then complete the upload. S3 multipart upload supports parts from 5 MB up to 10,000 parts. The client asks the API for pre-signed URLs per part. A tus-style resumable protocol is an alternative. Add a lifecycle rule to delete incomplete multipart uploads after a few days (they cost storage).
Processing pipeline
Triggered by the "object created" event, through a queue (Lesson 236) so spikes do not overwhelm workers:
- Malware scanning (ClamAV or a managed scanner) before anyone else can download the file.
- Images: strip EXIF metadata (it can contain GPS location), generate thumbnails and web-friendly formats (WebP, AVIF).
- Videos: transcode to several resolutions and streaming formats (HLS) with a managed service (AWS Elemental MediaConvert) or workers with ffmpeg.
- Documents: extract text for search; generate previews.
- Update the database status: pending → scanning → ready (or rejected). The UI shows progress.
Use a quarantine bucket or prefix for unscanned files, and move them to the main location only when clean.
Serving files
- Keep the bucket private (block public access).
- For private files: the API checks permissions (Lesson 203), then returns a short-lived pre-signed GET URL, or uses CloudFront signed URLs or cookies so downloads come through the CDN (fast, cached near users) while staying private.
- For public assets (product images): serve through the CDN from a dedicated public path, with long cache lifetimes and versioned keys.
- Set
Content-Disposition: attachmentfor user-uploaded files that should download rather than open in the browser, which reduces the risk of uploaded HTML or SVG running scripts on your domain. Better still, serve user content from a separate domain.
Metadata and lifecycle
The database stores metadata, not file bytes:
files: id, tenant_id, owner_id, storage_key, original_name, content_type, size_bytes, checksum, status, created_at, deleted_at- Lifecycle rules: move old files to cheaper storage classes (S3 Standard-IA, Glacier) and delete expired ones.
- Versioning and replication for important data; encryption at rest (on by default in S3).
- Deletion: delete the object and the record; with soft deletes, purge files after the retention period (and on GDPR erasure requests).
- Cost: storage per GB, requests, and especially data transfer out; a CDN reduces repeated transfers from the origin.
How to say it in an interview
"Files never stream through the API. The API authorises the upload, validates the declared type and size, creates a pending record with a generated storage key and returns a short-lived pre-signed URL, or pre-signed POST to enforce size; the client uploads directly to S3, using multipart uploads for large files. An object-created event goes through a queue to workers that verify the real content type, scan for malware, strip metadata and generate thumbnails or transcodes, then mark the file ready. The bucket stays private: downloads use permission checks plus short-lived signed URLs, ideally through CloudFront, with user content served as attachments from a separate domain. Metadata lives in the database, and lifecycle rules control cost."
Key words
| Word | Meaning |
|---|---|
| Object storage | Cheap, durable storage for files (S3) |
| Pre-signed URL | A temporary URL allowing one action without credentials |
| Multipart upload | Uploading a large file in parallel parts |
| Magic numbers | The first bytes identifying a file's real format |
| EXIF | Photo metadata that can include location |
| Transcoding | Converting video to other formats and resolutions |
| Lifecycle rule | Automatic moving or deleting of stored objects |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.