Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 04 · Storage, Queues & Event StreamingChapter 20 of 33
19.
Phase 04Read time ~25 minDifficulty advanced

File Upload & Media Systems

In this chapter
  • 01Introduction
  • 02The Basic File Upload Flow
  • 03Direct-to-Object-Storage Upload
  • 04Pre-Signed URLs
  • 05Why?
  • 06Upload Session
  • 07Why Upload Sessions Matter
  • 08Large-File Uploads
  • 09Multipart Upload
  • 10Multipart Upload Lifecycle
  • 11Resumable Uploads
  • 12Upload Progress
  • 13Server-Side Progress Tracking
  • 14File Validation
  • 15File Size Validation
  • 16Filename Security
  • 17Content Hashing
  • 18Deduplication
  • 19Malware Scanning
  • 20Quarantine
  • 21Image Processing
  • 22Thumbnail Generation
  • 23Image Processing Pipeline
  • 24Video Processing
  • 25Why Video Processing Must Be Asynchronous
  • 26Queue-Based Media Processing
  • 27Queue Backpressure
  • 28Retry Strategy
  • 29Idempotent Media Processing
  • 30Exactly-Once Processing Is Difficult
  • 31Processing Status
  • 32Metadata Database
  • 33Public vs Private Files
  • 34Public
  • 35Private
  • 36Private File Download
  • 37Access Control
  • 38Signed Download URLs
  • 39CDN Delivery
  • 40Range Requests
  • 41Download Optimization
  • 42Adaptive Video Streaming
  • 43Media Pipeline Architecture
  • 44Storage Cleanup
  • 45Orphaned Object Problem
  • 46Upload Security Checklist
  • 47Authentication
  • 48Authorization
  • 49Size limits
  • 50Type validation
  • 51Malware scanning
  • 52Safe object keys
  • 53Rate limiting
  • 54Quotas
  • 55Encryption
  • 56Private access
  • 57Upload Rate Limiting
  • 58Storage Quotas
  • 59Upload Reservation
  • 60File Upload Architecture for a SaaS Application
  • 61Why Not Store Files in SQL?
  • 62File Upload API Design
  • 63Upload State Machine
  • 64Failure Scenarios
  • 65Scenario 1 — Upload fails
  • 66Scenario 2 — Worker crashes
  • 67Scenario 3 — Processing repeatedly fails
  • 68Scenario 4 — Duplicate job
  • 69Scenario 5 — User loses network
  • 70Scenario 6 — Object exists but DB update failed
  • 71Scenario 7 — DB says READY but output missing
  • 72Observability
  • 73Upload
  • 74Queue
  • 75Processing
  • 76Storage
  • 77CDN
  • 78Cost Considerations
  • 79Production Design Example — Photo Sharing Application
  • 80Production Design Example — Video Platform
  • 81Important Design Trade-Offs
  • 82Application server upload vs direct upload
  • 83Synchronous processing vs asynchronous processing
  • 84Store every duplicate vs deduplicate
  • 85Public URLs vs signed URLs
  • 86Common Mistakes
  • 87Mistake 1
  • 88Mistake 2
  • 89Mistake 3
  • 90Mistake 4
  • 91Mistake 5
  • 92Mistake 6
  • 93Mistake 7
  • 94Mistake 8
  • 95Mistake 9
  • 96Mistake 10
  • 97Mistake 11
  • 98Mistake 12
  • 99Interview Framework
  • 100Interview Question: Why Use Pre-Signed URLs?
  • 101Interview Question: Why Multipart Upload?
  • 102Interview Question: Why Process Media Asynchronously?
  • 103Interview Question: How Do You Handle Duplicate Jobs?
  • 104Interview Question: How Do You Secure Private Downloads?
  • 105Mini Project
  • 106Requirements
  • 107Suggested Data Model
  • 108Production Checklist
  • 109Key Mental Model
  • 110Chapter Summary
  • 111Interview Revision Checklist
  • 112Next Chapter
  • 113Chapter 19 — Message Queues
In this chapter (113 sections)
01Introduction02The Basic File Upload Flow03Direct-to-Object-Storage Upload04Pre-Signed URLs05Why?06Upload Session07Why Upload Sessions Matter08Large-File Uploads09Multipart Upload10Multipart Upload Lifecycle11Resumable Uploads12Upload Progress13Server-Side Progress Tracking14File Validation15File Size Validation16Filename Security17Content Hashing18Deduplication19Malware Scanning20Quarantine21Image Processing22Thumbnail Generation23Image Processing Pipeline24Video Processing25Why Video Processing Must Be Asynchronous26Queue-Based Media Processing27Queue Backpressure28Retry Strategy29Idempotent Media Processing30Exactly-Once Processing Is Difficult31Processing Status32Metadata Database33Public vs Private Files34Public35Private36Private File Download37Access Control38Signed Download URLs39CDN Delivery40Range Requests41Download Optimization42Adaptive Video Streaming43Media Pipeline Architecture44Storage Cleanup45Orphaned Object Problem46Upload Security Checklist47Authentication48Authorization49Size limits50Type validation51Malware scanning52Safe object keys53Rate limiting54Quotas55Encryption56Private access57Upload Rate Limiting58Storage Quotas59Upload Reservation60File Upload Architecture for a SaaS Application61Why Not Store Files in SQL?62File Upload API Design63Upload State Machine64Failure Scenarios65Scenario 1 — Upload fails66Scenario 2 — Worker crashes67Scenario 3 — Processing repeatedly fails68Scenario 4 — Duplicate job69Scenario 5 — User loses network70Scenario 6 — Object exists but DB update failed71Scenario 7 — DB says READY but output missing72Observability73Upload74Queue75Processing76Storage77CDN78Cost Considerations79Production Design Example — Photo Sharing Application80Production Design Example — Video Platform81Important Design Trade-Offs82Application server upload vs direct upload83Synchronous processing vs asynchronous processing84Store every duplicate vs deduplicate85Public URLs vs signed URLs86Common Mistakes87Mistake 188Mistake 289Mistake 390Mistake 491Mistake 592Mistake 693Mistake 794Mistake 895Mistake 996Mistake 1097Mistake 1198Mistake 1299Interview Framework100Interview Question: Why Use Pre-Signed URLs?101Interview Question: Why Multipart Upload?102Interview Question: Why Process Media Asynchronously?103Interview Question: How Do You Handle Duplicate Jobs?104Interview Question: How Do You Secure Private Downloads?105Mini Project106Requirements107Suggested Data Model108Production Checklist109Key Mental Model110Chapter Summary111Interview Revision Checklist112Next Chapter113Chapter 19 — Message Queues

1. Introduction#

File upload looks simple:

User → Server → Disk

At small scale, this can work.

At production scale, however, files introduce very different requirements from normal API requests:

  • files can be much larger than JSON requests
  • uploads can take minutes
  • users may have unstable networks
  • uploads can fail halfway through
  • multiple users can upload simultaneously
  • files need validation and security scanning
  • images may need resizing and thumbnails
  • videos may need transcoding into multiple formats
  • processing can take much longer than the original HTTP request
  • files may need private access control
  • downloads may need CDN delivery
  • large files may require range requests
  • duplicate files can waste storage
  • failed or abandoned uploads can leave orphaned objects

This chapter connects the storage concepts from Chapter 17 with a complete production-grade media system.


2. The Basic File Upload Flow#

A simple architecture is:

Browser
   |
   | POST /upload
   v
Application Server
   |
   v
Object Storage

For a small application this may be acceptable.

The application receives the entire file and then sends it to object storage.

The problem is that the application server becomes part of the file-data path.

For a 1 GB file:

User
  |
  | 1 GB
  v
App Server
  |
  | 1 GB
  v
Object Storage

The application server consumes:

  • bandwidth
  • memory/buffers
  • network connections
  • CPU
  • request capacity
  • connection duration

At large scale, this becomes inefficient.


3. Direct-to-Object-Storage Upload#

A common production architecture is:

                 ┌─────────────────┐
                 │ Application API │
                 └────────┬────────┘
                          |
                    create upload
                          |
                          v
                     Upload URL
                          |
                          v
User ─────────────────────────────→ Object Storage

The application server does not transfer the actual file bytes.

Instead:

  1. Client asks the API to start an upload.
  2. API authenticates the user.
  3. API validates metadata.
  4. API creates an upload session.
  5. API generates a pre-signed upload URL.
  6. Client uploads directly to object storage.
  7. Storage confirms the object.
  8. Client/API triggers processing.
  9. Background workers process the media.

This architecture dramatically reduces application-server bandwidth usage.


4. Pre-Signed URLs#

A pre-signed URL is a temporary URL that grants permission to perform a specific storage operation.

Conceptually:

POST /uploads
        |
        v
API creates temporary permission
        |
        v
Pre-signed URL
        |
        v
Client → Object Storage

The URL should normally have:

  • expiration time
  • allowed HTTP method
  • object key
  • expected content type where supported
  • size constraints where supported
  • scoped permissions

The client should not receive permanent cloud credentials.

Why?#

Giving a browser unrestricted storage credentials would be dangerous.

A compromised client could potentially:

  • upload arbitrary objects
  • delete objects
  • read private files
  • consume large amounts of storage

Pre-signed URLs provide limited authorization.


5. Upload Session#

For reliable large uploads, create an upload session.

Example:

POST /uploads

Request:

{
  "filename": "vacation.mp4",
  "size": 524288000,
  "contentType": "video/mp4"
}

Response:

{
  "uploadId": "upl_123",
  "objectKey": "users/42/uploads/upl_123/original.mp4",
  "status": "created"
}

The upload session can have states:

CREATED
   |
UPLOADING
   |
UPLOADED
   |
PROCESSING
   |
READY

Failure states might include:

FAILED
CANCELLED
EXPIRED

This state machine becomes important for reliable systems.


6. Why Upload Sessions Matter#

Without a session, the system may not know:

  • which user owns the file
  • whether an upload is still active
  • whether the file was completed
  • whether processing already started
  • whether a retry is safe
  • whether an abandoned upload should be deleted

An upload record can contain:

upload_id
user_id
filename
object_key
content_type
expected_size
received_size
status
created_at
expires_at
checksum

The database stores metadata.

Object storage stores the actual bytes.


7. Large-File Uploads#

Uploading a 5 KB image is very different from uploading a 20 GB video.

For large files, sending one HTTP request is fragile.

Suppose:

10 GB file

and the network fails after:

9.5 GB

If the system requires restarting the entire upload, the user wastes:

9.5 GB

of transfer.

Instead, divide the file into parts.


8. Multipart Upload#

Example:

10 GB file
 
+--------+--------+--------+--------+
| Part 1 | Part 2 | Part 3 | Part 4 |
+--------+--------+--------+--------+

Each part can be uploaded independently.

For example:

Part size = 100 MB
 
10 GB / 100 MB ≈ 100 parts

The client can upload several parts concurrently.

              ┌─ Part 1 ─→ Storage
              ├─ Part 2 ─→ Storage
File ─────────┼─ Part 3 ─→ Storage
              ├─ Part 4 ─→ Storage
              └─ Part 5 ─→ Storage

After all parts are uploaded, the client or server asks storage to complete the multipart upload.


9. Multipart Upload Lifecycle#

Typical lifecycle:

1. Initiate multipart upload
          |
          v
2. Receive upload ID
          |
          v
3. Upload parts
          |
          v
4. Track part numbers + checksums
          |
          v
5. Retry failed parts
          |
          v
6. Complete upload
          |
          v
7. Object becomes available

The storage provider generally handles the final assembly.

The application should track the upload session and completion state.


10. Resumable Uploads#

Resumable uploads allow the client to continue after interruption.

Example:

Part 1 ✓
Part 2 ✓
Part 3 ✓
Part 4 ✗
Part 5 ✓

Only Part 4 needs to be retried.

This is especially useful for:

  • large videos
  • mobile uploads
  • unreliable networks
  • remote locations
  • long-running uploads

11. Upload Progress#

Users expect progress information.

A simple percentage is:

progress =
uploadedBytes / totalBytes * 100

For example:

uploaded = 400 MB
total = 1000 MB
 
progress = 40%

The browser can track client-side upload progress.

For multipart uploads, progress can be calculated from completed parts plus the current part.

Example:

Completed parts: 600 MB
Current part: 50 MB of 100 MB
 
Total uploaded = 650 MB

12. Server-Side Progress Tracking#

For more advanced systems, maintain progress in the database or a fast store.

Example:

upload_id
uploaded_bytes
total_bytes
status
updated_at

However, do not write to the database on every tiny progress event.

That can create excessive write load.

Instead:

  • update periodically
  • update when a part completes
  • use Redis for highly frequent temporary progress
  • persist important final state to the database

13. File Validation#

Never trust the filename or client-provided MIME type.

A client can claim:

Content-Type: image/png

while sending something completely different.

Validation should consider:

Extension
+
Declared MIME type
+
File signature / magic bytes
+
Actual size
+
Application-specific rules

Example:

avatar.png

should actually contain a valid image format.


14. File Size Validation#

Before accepting an upload, define limits.

Example:

Profile image: 10 MB
Document: 50 MB
Video: 5 GB

Enforce limits as early as possible.

Why?

Because unlimited uploads create:

  • storage abuse
  • bandwidth abuse
  • denial-of-service risk
  • unexpected cloud bills

15. Filename Security#

Do not use the original filename directly as the storage path.

Bad:

/uploads/user-input-filename

Potential problems include:

  • collisions
  • unsafe characters
  • path traversal attempts
  • inconsistent encoding

Instead generate an internal object key.

Example:

users/42/uploads/8b9f2c/original

Store the original filename separately as metadata.


16. Content Hashing#

A file can be represented by a cryptographic hash.

Example:

SHA-256(file)

Conceptually:

same bytes
   |
   v
same hash

This enables duplicate detection.

Example:

File A → SHA-256 → abc123
File B → SHA-256 → abc123

The system can recognize that both files have identical content.


17. Deduplication#

Suppose 10,000 users upload the exact same 100 MB file.

Without deduplication:

10,000 × 100 MB
= 1,000,000 MB
≈ 1 TB

With content-addressed deduplication, the underlying object may be stored once.

Metadata can represent ownership separately:

User A → object abc123
User B → object abc123
User C → object abc123

Important consideration:

Do not delete the shared object until all references are gone.


18. Malware Scanning#

User-uploaded files are untrusted input.

A production system may run malware scanning before making a file available.

Architecture:

Client
  |
  v
Object Storage
  |
  v
Queue
  |
  v
Malware Scanner
  |
  +---- clean ----→ Processing
  |
  +---- infected → Quarantine

A newly uploaded file should not automatically become downloadable to other users.


19. Quarantine#

A useful design is to separate uploaded files into states or locations:

quarantine/
processed/
public/
private/

Example:

Upload
  |
  v
Quarantine
  |
  v
Security scan
  |
  +---- infected → isolated
  |
  +---- clean → processing

This reduces the chance that unsafe content is immediately served.


20. Image Processing#

A single uploaded image may need multiple variants.

Example:

Original
   |
   +── thumbnail
   +── small
   +── medium
   +── large
   +── Web-optimized

Architecture:

Object Storage
      |
      v
Message Queue
      |
      v
Image Worker
      |
      +---- thumbnail
      +---- small
      +---- medium
      +---- optimized

The original should normally be preserved if business requirements require it.


21. Thumbnail Generation#

Suppose a user uploads:

photo.jpg

The system can create:

photo-original.jpg
photo-200.jpg
photo-800.jpg
photo-1600.jpg

The application can choose the appropriate version based on:

  • device
  • viewport
  • network conditions
  • requested quality

This reduces bandwidth.


22. Image Processing Pipeline#

A realistic pipeline might be:

Upload
  |
  v
Validate
  |
  v
Malware Scan
  |
  v
Decode Image
  |
  v
Resize
  |
  v
Compress
  |
  v
Generate Variants
  |
  v
Store Results
  |
  v
Mark READY

Each stage should ideally be independently observable and retryable.


23. Video Processing#

Video is significantly more expensive.

A user may upload:

1080p.mp4

but the application may need:

240p
360p
480p
720p
1080p

It may also need different codecs or streaming formats.

Architecture:

Upload
   |
   v
Object Storage
   |
   v
Queue
   |
   v
Video Processor
   |
   +---- Transcode
   +---- Extract metadata
   +---- Generate thumbnails
   +---- Generate preview
   +---- Generate streaming segments
   |
   v
Processed Media

24. Why Video Processing Must Be Asynchronous#

Suppose transcoding takes:

3 minutes

Do not keep the original upload HTTP request open for three minutes.

Instead:

POST /videos
       |
       v
Create processing job
       |
       v
Return 202 Accepted
       |
       v
Worker processes asynchronously

The client can later query:

GET /videos/{id}/status

Example:

{
  "status": "processing",
  "progress": 63
}

25. Queue-Based Media Processing#

A queue decouples upload from processing.

                  ┌──────────────┐
                  │ Object Store │
                  └──────┬───────┘
                         |
                         v
                  ┌──────────────┐
                  │ Message Queue│
                  └──────┬───────┘
                         |
             ┌───────────┼───────────┐
             v           v           v
          Worker 1    Worker 2    Worker 3

Benefits:

  • buffering
  • retry
  • horizontal scaling
  • workload isolation
  • asynchronous processing

26. Queue Backpressure#

Suppose:

Uploads = 10,000/hour
Processing capacity = 5,000/hour

The queue grows.

That is not necessarily a failure.

The queue provides a buffer.

But the system must monitor:

queue depth
oldest message age
processing latency
failure rate
worker utilization

If the queue grows continuously, add workers or increase processing capacity.


27. Retry Strategy#

Media processing can fail because of:

  • temporary storage failure
  • worker crash
  • malformed input
  • timeout
  • dependency failure
  • resource exhaustion

Transient errors can be retried.

Permanent errors should eventually fail.

A typical strategy:

Attempt 1 → fail
      |
      v
wait
      |
Attempt 2 → fail
      |
      v
wait longer
      |
Attempt 3 → fail
      |
      v
Dead-letter queue

Use exponential backoff.

Example:

1s
2s
4s
8s
16s

Add jitter to avoid synchronized retries.


28. Idempotent Media Processing#

Workers may receive the same job more than once.

Therefore processing should be idempotent where possible.

Suppose:

job = generate-thumbnail(upload_123)

If executed twice, the system should not produce inconsistent results or corrupt state.

A worker can use a deterministic output key:

uploads/123/thumbnail-400.webp

Before writing:

Does output already exist?

or maintain a processing record:

job_id
upload_id
operation
status
attempt_count

29. Exactly-Once Processing Is Difficult#

Distributed systems commonly provide at-least-once delivery.

That means:

same message
may be processed more than once

Therefore:

at-least-once delivery
+
idempotent consumer

is a common design.

Do not assume:

message received once = operation executed once

30. Processing Status#

A media object can have:

UPLOADING
UPLOADED
SCANNING
PROCESSING
READY
FAILED
DELETED

For video:

UPLOADED
   |
SCANNING
   |
TRANSCODING
   |
GENERATING_THUMBNAILS
   |
PUBLISHING
   |
READY

The state should have valid transitions.

For example:

READY → PROCESSING

might not be allowed unless a reprocessing operation is explicitly requested.


31. Metadata Database#

Do not put all media metadata inside the object store.

A database can store:

media_id
owner_id
object_key
original_filename
content_type
size
checksum
status
visibility
created_at
updated_at
duration
width
height

Object storage stores:

actual bytes

Database:

"What is this file?"

Object storage:

"Here are the bytes."

32. Public vs Private Files#

A system usually has different visibility models.

Public#

Anyone with the URL may access the object.

Useful for:

  • public images
  • website assets
  • public videos

Private#

Only authorized users may access it.

Useful for:

  • documents
  • invoices
  • personal photos
  • internal company files

33. Private File Download#

A private file should not simply expose a permanent public URL.

Instead:

Client
  |
  | GET /files/123
  v
Application
  |
  | authorize
  v
Generate signed download URL
  |
  v
Client
  |
  v
Object Storage / CDN

The URL should expire.

Example:

valid for 5 minutes

34. Access Control#

Authorization should happen before generating access.

Example:

User A requests File X
 
        |
        v
Is User A allowed?
        |
     +--+--+
     |     |
    YES    NO
     |     |
     v     v
Signed   403
URL

Do not rely solely on an unguessable object key for authorization.

Security should be enforced by an explicit access-control policy.


35. Signed Download URLs#

A signed URL can contain authorization information that the storage/CDN validates.

Typical properties:

resource
expiration
signature

This allows:

temporary access

without exposing permanent credentials.


36. CDN Delivery#

Large media should generally be delivered through a CDN when global or high-volume delivery is required.

Architecture:

User
 |
 v
CDN
 |
 +---- cache hit → response
 |
 +---- cache miss
          |
          v
     Object Storage

Benefits:

  • lower latency
  • reduced origin load
  • better global performance
  • bandwidth optimization

37. Range Requests#

Large files often need partial downloads.

HTTP supports byte ranges.

Conceptually:

Range: bytes=0-999999

The server can return only that portion.

This is useful for:

  • video seeking
  • resumable downloads
  • large documents
  • media streaming

Example:

10 GB video
 
User jumps to minute 45
 
Client does not necessarily need
to download the first 45 minutes.

38. Download Optimization#

A media delivery system can optimize downloads through:

  • CDN caching
  • compression where appropriate
  • correct content type
  • HTTP range requests
  • adaptive streaming
  • multiple image resolutions
  • modern image formats
  • cache-control headers

For large files, avoid routing every byte through the application server.


39. Adaptive Video Streaming#

For video platforms, a single large MP4 may not be sufficient.

The system can create multiple representations:

240p
360p
480p
720p
1080p

The client can select an appropriate representation based on network conditions.

Common streaming approaches include segmented adaptive streaming such as HLS or MPEG-DASH.

Conceptually:

Master Manifest
       |
       +---- 240p
       +---- 360p
       +---- 720p
       +---- 1080p

Each representation is divided into segments.


40. Media Pipeline Architecture#

A production architecture may look like:

                         ┌───────────────┐
                         │ Application API│
                         └───────┬───────┘
                                 |
                         Upload Session
                                 |
                                 v
Client ───────────────────→ Object Storage
                                 |
                                 v
                              Queue
                                 |
                ┌────────────────┼────────────────┐
                v                v                v
          Virus Scanner    Image Worker     Video Worker
                |                |                |
                └────────────────┼────────────────┘
                                 v
                         Processed Storage
                                 |
                                 v
                                CDN
                                 |
                                 v
                               Users

The API manages metadata and authorization.

Object storage manages bytes.

Workers manage expensive processing.

Queues provide asynchronous coordination.

CDN handles delivery.


41. Storage Cleanup#

Abandoned uploads are common.

Example:

User starts 5 GB upload
↓
User closes browser
↓
Multipart upload remains incomplete

If never cleaned up, storage resources accumulate.

Use lifecycle cleanup.

Example:

Incomplete upload older than 24 hours
        |
        v
Abort

Also clean:

  • temporary files
  • failed processing outputs
  • old media versions
  • orphaned objects
  • expired thumbnails
  • deleted-user data according to retention requirements

42. Orphaned Object Problem#

Suppose:

Database row deleted
Object remains

or:

Object deleted
Database row remains

Now the system is inconsistent.

Possible solutions include:

  • transactional metadata workflows
  • soft deletion
  • asynchronous cleanup jobs
  • periodic reconciliation
  • object inventory scans

A reconciliation job can find:

objects without metadata
metadata without objects

43. Upload Security Checklist#

Important controls include:

Authentication#

Know who is uploading.

Authorization#

Verify what the user is allowed to upload.

Size limits#

Prevent abuse.

Type validation#

Do not trust only the filename.

Malware scanning#

Scan untrusted files.

Safe object keys#

Do not directly use user-controlled paths.

Rate limiting#

Prevent upload abuse.

Quotas#

Limit per-user or per-tenant storage.

Encryption#

Protect data at rest and in transit.

Private access#

Do not accidentally expose sensitive objects.


44. Upload Rate Limiting#

Suppose a malicious user sends:

10,000 upload requests/minute

Even before files are transferred, this can overload the upload-session API.

Rate-limit:

create upload
complete upload
generate signed URL
download authorization

You can apply limits by:

  • user
  • tenant
  • IP
  • API key
  • endpoint

45. Storage Quotas#

For multi-tenant systems:

Tenant A → 100 GB
Tenant B → 1 TB
Tenant C → 10 GB

Track:

used_bytes
quota_bytes

Before creating a new upload:

used + expected_size <= quota

But remember that concurrent uploads create race conditions.

Quota enforcement may require reservation.


46. Upload Reservation#

Suppose a user has:

1 GB remaining

Two simultaneous uploads each request:

700 MB

If both check independently:

700 MB <= 1 GB
700 MB <= 1 GB

Both may be accepted.

Actual usage:

1.4 GB

To avoid this, reserve capacity:

available = quota - used - reserved

Then:

reservation + expected_size

must fit.


47. File Upload Architecture for a SaaS Application#

Example:

                    Internet
                       |
                       v
                 API Gateway
                       |
                       v
               Upload Service
                       |
          +------------+------------+
          |                         |
          v                         v
    Metadata DB              Signed URL
                                    |
                                    v
                              Object Storage
                                    |
                                    v
                                  Queue
                                    |
                +-------------------+-------------------+
                |                   |                   |
                v                   v                   v
            Scanner            Image Worker       Video Worker
                |                   |                   |
                +-------------------+-------------------+
                                    |
                                    v
                             Processed Storage
                                    |
                                    v
                                   CDN

This separates responsibilities cleanly.


48. Why Not Store Files in SQL?#

A database can technically store binary data.

But for large media workloads, object storage is usually more appropriate because it is designed for:

  • large objects
  • high durability
  • large-scale storage
  • independent scaling
  • lower-cost storage tiers
  • lifecycle policies

The database should usually store metadata and relationships.


49. File Upload API Design#

Example APIs:

POST /uploads
GET  /uploads/{id}
POST /uploads/{id}/complete
POST /uploads/{id}/cancel
GET  /uploads/{id}/status
DELETE /uploads/{id}

For a multipart implementation:

POST /uploads/{id}/parts
POST /uploads/{id}/complete

The exact API depends on the storage provider and architecture.


50. Upload State Machine#

A useful model:

             +-----------+
             |  CREATED  |
             +-----+-----+
                   |
                   v
             +-----------+
             | UPLOADING |
             +-----+-----+
                   |
             complete
                   |
                   v
             +-----------+
             | UPLOADED  |
             +-----+-----+
                   |
                   v
             +-----------+
             | SCANNING  |
             +-----+-----+
                   |
                   v
             +-----------+
             | PROCESSING|
             +-----+-----+
                   |
                   v
             +-----------+
             |   READY   |
             +-----------+

Failure can transition to:

FAILED

Cancellation can transition to:

CANCELLED

51. Failure Scenarios#

Scenario 1 — Upload fails#

Solution:

resume failed part

Scenario 2 — Worker crashes#

Solution:

queue retry

Scenario 3 — Processing repeatedly fails#

Solution:

dead-letter queue

Scenario 4 — Duplicate job#

Solution:

idempotent worker

Scenario 5 — User loses network#

Solution:

resumable upload

Scenario 6 — Object exists but DB update failed#

Solution:

reconciliation

Scenario 7 — DB says READY but output missing#

Solution:

verification/reconciliation

52. Observability#

Monitor the entire pipeline.

Important metrics:

Upload#

upload success rate
upload failure rate
average upload duration
bytes uploaded
active uploads

Queue#

queue depth
oldest message age
retry count
dead-letter count

Processing#

processing duration
success rate
failure rate
worker utilization
CPU
memory

Storage#

total bytes
object count
storage growth
orphaned objects

CDN#

cache hit ratio
origin traffic
bandwidth
latency
error rate

53. Cost Considerations#

Media systems can become expensive.

Costs can come from:

Storage
+
PUT/GET operations
+
Bandwidth
+
CDN
+
Transcoding
+
Scanning
+
Worker compute
+
Database

For example, a video platform may spend significant resources on transcoding rather than raw storage.

Optimization strategies include:

  • lifecycle policies
  • compression
  • deduplication
  • CDN caching
  • lower-resolution previews
  • archive tiers
  • deleting temporary files
  • controlling redundant processing

54. Production Design Example — Photo Sharing Application#

Requirements:

  • users upload photos
  • private/public visibility
  • thumbnails
  • multiple resolutions
  • CDN delivery
  • malware scanning
  • large files
  • high availability

Architecture:

Mobile/Web Client
       |
       v
Upload API
       |
       +---- Metadata DB
       |
       +---- Signed Upload URL
                    |
                    v
              Object Storage
                    |
                    v
                  Queue
                    |
             Malware Scanner
                    |
                    v
               Image Worker
                    |
          +---------+---------+
          |         |         |
          v         v         v
       Thumb     Medium      Large
          |         |         |
          +---------+---------+
                    |
                    v
             Processed Store
                    |
                    v
                   CDN
                    |
                    v
                  Users

55. Production Design Example — Video Platform#

Requirements:

  • large video uploads
  • resumable uploads
  • transcoding
  • thumbnails
  • adaptive streaming
  • CDN delivery

Architecture:

Client
  |
  v
Upload API
  |
  v
Multipart Upload
  |
  v
Object Storage
  |
  v
Queue
  |
  +---- Scan
  |
  +---- Extract Metadata
  |
  +---- Transcode
  |
  +---- Generate Thumbnails
  |
  +---- Generate Segments
  |
  v
Processed Storage
  |
  v
CDN
  |
  v
Viewer

56. Important Design Trade-Offs#

Application server upload vs direct upload#

Application server:

simpler
but expensive at scale

Direct object storage:

more architecture
but scales better

Synchronous processing vs asynchronous processing#

Synchronous:

simple
poor for expensive work

Asynchronous:

more components
better scalability and reliability

Store every duplicate vs deduplicate#

No deduplication:

simpler
higher storage cost

Deduplication:

more complexity
lower storage usage

Public URLs vs signed URLs#

Public:

simple
not appropriate for private content

Signed:

secure temporary access
more authorization complexity

57. Common Mistakes#

Mistake 1#

Sending every large file through the application server.

Mistake 2#

Using permanent cloud credentials in the browser.

Mistake 3#

Trusting the filename extension.

Mistake 4#

Processing videos synchronously.

Mistake 5#

Not supporting resumable uploads.

Mistake 6#

Not cleaning abandoned multipart uploads.

Mistake 7#

Assuming queue messages execute exactly once.

Mistake 8#

Deleting an object without checking shared references.

Mistake 9#

Exposing private objects publicly.

Mistake 10#

No quota or rate limit.

Mistake 11#

No reconciliation process.

Mistake 12#

No observability around the media pipeline.


58. Interview Framework#

When asked:

Design a file upload system.

Start with requirements.

Ask:

What file types?
Maximum file size?
How many uploads/day?
Public or private?
Need resumability?
Need image processing?
Need video transcoding?
Need CDN?
Need virus scanning?
Retention requirements?
Multi-region?

Then define:

API
Metadata DB
Object storage
Upload mechanism
Queue
Workers
CDN
Security
Observability

Then discuss scale and failures.


59. Interview Question: Why Use Pre-Signed URLs?#

Answer:

Pre-signed URLs allow clients to upload directly to object storage using temporary, scoped authorization. This avoids routing large file payloads through application servers and improves scalability.


60. Interview Question: Why Multipart Upload?#

Answer:

Multipart upload divides a large file into independently transferable parts. Failed parts can be retried without restarting the entire upload, and multiple parts can be uploaded concurrently.


61. Interview Question: Why Process Media Asynchronously?#

Answer:

Media processing such as image transformation and video transcoding can be CPU- and time-intensive. Asynchronous queues and workers prevent long-running processing from blocking user-facing HTTP requests and allow processing capacity to scale independently.


62. Interview Question: How Do You Handle Duplicate Jobs?#

Answer:

Assume at-least-once delivery and make workers idempotent. Use deterministic output keys, processing records, idempotency keys, or conditional writes so repeated execution does not create inconsistent results.


63. Interview Question: How Do You Secure Private Downloads?#

Answer:

Authenticate
   ↓
Authorize
   ↓
Generate short-lived signed URL
   ↓
Client downloads through storage/CDN

Do not expose permanent public URLs for private content.


64. Mini Project#

Build a production-style media service.

Requirements#

Implement:

POST /uploads
GET /uploads/:id
GET /uploads/:id/status
POST /uploads/:id/complete
DELETE /uploads/:id

Add:

  • upload sessions
  • object-storage abstraction
  • metadata database
  • checksum
  • file validation
  • asynchronous processing
  • queue
  • worker
  • retry
  • idempotency
  • status tracking

For image files:

original
thumbnail
medium
large

For private files:

signed download URL

65. Suggested Data Model#

Media
----------------
id
owner_id
object_key
original_name
content_type
size
checksum
status
visibility
created_at
updated_at

Processing job:

MediaJob
----------------
id
media_id
operation
status
attempt_count
last_error
created_at
updated_at

66. Production Checklist#

Before considering the system production-ready, verify:

[ ] Direct upload supported
[ ] Pre-signed URLs
[ ] Large-file support
[ ] Multipart uploads
[ ] Resumable uploads
[ ] Upload expiration
[ ] File validation
[ ] Malware scanning
[ ] Safe object keys
[ ] Content hashing
[ ] Optional deduplication
[ ] Metadata DB
[ ] Queue
[ ] Async workers
[ ] Retries
[ ] Idempotency
[ ] Dead-letter handling
[ ] Private/public access control
[ ] Signed downloads
[ ] CDN
[ ] Range requests
[ ] Cleanup
[ ] Reconciliation
[ ] Quotas
[ ] Rate limiting
[ ] Encryption
[ ] Monitoring
[ ] Alerting
[ ] Cost controls

67. Key Mental Model#

Remember this architecture:

              CONTROL PLANE
                   |
                   v
              Application
                   |
        metadata / auth / policy
                   |
                   v
 
               DATA PLANE
                   |
                   v
            Object Storage
                   |
                   v
                 Queue
                   |
                   v
             Media Workers
                   |
                   v
           Processed Storage
                   |
                   v
                  CDN
                   |
                   v
                 Users

The application controls the system.

Object storage holds the bytes.

Queues coordinate asynchronous work.

Workers perform expensive transformations.

CDNs deliver content efficiently.


68. Chapter Summary#

In this chapter we learned how a production-grade file and media system works.

The key concepts are:

  1. Direct-to-object-storage uploads.
  2. Pre-signed URLs.
  3. Upload sessions.
  4. Multipart uploads.
  5. Resumable uploads.
  6. Upload progress.
  7. File validation.
  8. Malware scanning.
  9. Quarantine.
  10. Content hashing.
  11. Deduplication.
  12. Image processing.
  13. Thumbnail generation.
  14. Video transcoding.
  15. Asynchronous media pipelines.
  16. Message queues.
  17. Retry and exponential backoff.
  18. Idempotent workers.
  19. Processing state machines.
  20. Metadata databases.
  21. Private/public access.
  22. Signed download URLs.
  23. CDN delivery.
  24. Range requests.
  25. Adaptive video streaming.
  26. Storage cleanup.
  27. Reconciliation.
  28. Quotas and rate limiting.
  29. Observability.
  30. Cost optimization.

The most important architectural principle is:

Do not make the application server carry
large media traffic or perform long-running
media processing synchronously.
 
Separate:
 
API
Storage
Processing
Delivery

That separation allows each part of the system to scale independently.


69. Interview Revision Checklist#

Before moving forward, you should be able to explain:

  • Why direct uploads are preferred at scale.
  • What a pre-signed URL is.
  • Why cloud credentials should not be exposed to browsers.
  • How multipart uploads work.
  • How resumable uploads work.
  • How upload progress is tracked.
  • Why MIME type alone is insufficient for validation.
  • Why malware scanning should happen before publication.
  • Why image/video processing should be asynchronous.
  • Why queues are useful in media pipelines.
  • Why workers must be idempotent.
  • Why at-least-once delivery requires duplicate handling.
  • How private files are securely downloaded.
  • Why CDNs are useful for media.
  • What HTTP range requests solve.
  • How abandoned uploads are cleaned up.
  • How deduplication works using content hashes.
  • How to design a photo upload system.
  • How to design a video platform media pipeline.
  • What metrics you would monitor.

70. Next Chapter#

Chapter 19 — Message Queues#

In the next chapter we will move from media pipelines to the broader concept of message queues.

We will learn:

  • What a message queue is
  • Why queues exist
  • Producers and consumers
  • Queue vs database
  • Synchronous vs asynchronous communication
  • Push vs pull
  • Delivery guarantees
  • At-most-once, at-least-once and effectively-once processing
  • Acknowledgements
  • Visibility timeouts
  • Retries
  • Dead-letter queues
  • Ordering
  • Priority queues
  • Delayed messages
  • Consumer groups
  • Backpressure
  • Queue scaling
  • Queue partitioning
  • Poison messages
  • Idempotency
  • Message retention
  • Queue monitoring
  • Real-world architectures
  • System-design interview questions

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 17 — Storage SystemsNext ChapterChapter 19 — Message Queues
PrevNext