13. CDN & Object Storage

Big picture: Your app stores facts in a database and files in object storage. A CDN puts copies of popular files close to users so downloads feel instant β€” like stocking neighborhood kiosks instead of making everyone drive to one central warehouse.


Learning goals

After this chapter you should be able to:

  • Explain why databases are the wrong place for large files (videos, PDFs, profile photos)
  • Describe what object storage is and how keys/URLs work
  • Draw a CDN in an HLD and explain cache hits vs origin fetches
  • Compare simple upload vs presigned (direct) upload and when to use each
  • Explain signed URLs for private content
  • Sketch a media pipeline: upload β†’ queue β†’ transcode β†’ CDN
  • Place S3 + CDN correctly in an Instagram/Netflix-style design

Prerequisites: 08-databases.md, 10-caching.md, 12-queues-async.md


Everyday analogy: library warehouse vs neighborhood kiosk

Imagine a city with one giant library warehouse in the middle of the country. Every time someone in Sydney wants a book, a truck drives from the warehouse to Sydney. It works β€” but it's slow and expensive when millions of people want the same bestseller.

Now imagine neighborhood kiosks: copies of popular books sit in small shelves near where people live. The first person in Sydney might still trigger a delivery from the warehouse (a cache miss). After that, everyone in Sydney gets the book from the local kiosk (a cache hit).

Real-world pieceSystem design piece
Central warehouseOrigin (S3 bucket, your API, origin server)
Neighborhood kioskCDN edge node (CloudFront, Cloudflare, Fastly)
Book title / shelf locationObject key (videos/2026/abc.mp4)
Library card catalogDatabase (metadata: title, owner, s3_key)
The actual book pagesObject bytes (file content in S3)

Key insight: The warehouse (origin) has unlimited shelf space and is cheap to run at scale. The kiosks (CDN edges) are about speed and reducing load on the warehouse β€” not about being the system of record.


Databases are bad at big files

A relational database like Postgres or MySQL is excellent at:

  • Structured rows with relationships
  • Transactions ("deduct balance AND insert order" atomically)
  • Queries with filters, joins, indexes

It is terrible at storing 50 MB video files as BLOB columns because:

ProblemWhy it hurts
SizeDB storage is expensive; backups and replication balloon
ThroughputStreaming bytes through DB connections wastes app + DB CPU
ScalingYou scale reads/writes for metadata, not for media bandwidth
ToolingNo built-in CDN integration, transcoding hooks, or lifecycle policies

The standard split

Database (Postgres):     video_id, title, owner_id, duration, s3_key, status
Object storage (S3):     actual bytes at key "videos/2026/07/abc.mp4"
CDN (CloudFront):        cached copies of abc.mp4 at edge locations worldwide

Rule of thumb: If a user would "download" or "stream" it, it probably belongs in object storage β€” not in a DB row.


Object storage basics

Object storage treats data as files addressed by a key, stored in a bucket (a namespace/container).

Examples: Amazon S3, Google Cloud Storage (GCS), Azure Blob Storage, MinIO (self-hosted).

s3://my-app-bucket/videos/2026/07/abc.mp4
     └─ bucket β”€β”˜ └────── object key β”€β”€β”€β”€β”€β”€β”˜

Properties that matter in interviews

PropertyWhat it meansInterview phrase
Virtually unlimited capacityNo "disk full" at app scale"We won't run out of space for user uploads"
DurabilityData replicated across disks/AZs"S3 gives 11 nines durability for the bytes"
Cheap at scalePennies per GB/month"Storage cost is negligible vs DB"
Key-value accessGET/PUT/DELETE by key"No SQL queries on file contents"
HTTP-friendlyREST API, presigned URLs"Clients upload directly without touching our API"

What object storage is NOT

  • Not a replacement for Postgres (no joins, no transactions across objects)
  • Not a filesystem with fast random writes (bad for constantly mutating small files)
  • Not automatically fast worldwide (that's what the CDN is for)

CDN (Content Delivery Network)

A CDN is a network of edge servers geographically distributed near users. They cache copies of static (or cacheable) content.

Cache hit vs cache miss

EventWhat happensLatencyOrigin load
Cache hitEdge already has the fileLow (~10–50 ms)None
Cache missEdge fetches from origin, stores copyHigher first timeOne origin read
Cache evictionEdge runs out of space; old files removedNext request may miss againOccasional origin read

Analogy: The kiosk ran out of shelf space and removed a less-popular book. Next person asking for it triggers another warehouse delivery.

TTL and cache control

CDNs respect HTTP headers like Cache-Control: max-age=3600. You control:

  • How long edges cache content
  • Whether content is public (cacheable) or private (user-specific)
Content typeTypical cache strategy
Public profile photoLong TTL (hours/days), immutable URL with hash in path
Video segment (HLS)Medium TTL, versioned paths
Private medical PDFNo public CDN; signed URLs with short expiry
HTML with user nameOften not CDN-cached (personalized)

What belongs on a CDN

Good candidates:

  • Images (avatars, product photos, thumbnails)
  • CSS, JavaScript, fonts (web app static assets)
  • Video/audio segments
  • Public downloadable files (PDFs, installers)
  • Some read-heavy API responses if they are identical for many users (public product catalog page JSON β€” use carefully)

Usually NOT on CDN:

  • Personalized API responses ("your feed")
  • Write operations (POST/PUT/DELETE)
  • Content that must never be cached without auth (bank balances)
  • Very large files that are downloaded once (direct S3 may be fine)

Upload patterns

Uploading files is where many beginners hurt their API servers.

Pattern 1: Simple upload (API as middleman)

ProsCons
Simple mental modelAPI server handles all bandwidth
Central validation in one placeTimeouts on large files
Hard to scale; expensive egress through app tier

When OK: Small files (< few MB), low volume, MVP prototypes.

Pattern 2: Presigned / direct upload (preferred for large media)

The client uploads directly to S3 using a temporary, scoped URL the API generates.

Analogy: Instead of mailing your package through the post office front desk clerk's desk (API), the clerk hands you a one-time gate pass (presigned URL) so you drive directly to the loading dock (S3).

StepWhy it matters
Init on APIAuth, quotas, virus-scan policy, metadata row
Direct PUT to S3Scales bandwidth without scaling app servers
Complete callbackConfirms upload finished; triggers async pipeline

Multipart upload (very large files)

For files > 100 MB (or GB-scale), S3 supports multipart upload: client splits file into chunks, uploads in parallel, S3 assembles. Same presigned pattern β€” API issues URLs per part.


Signed URLs & private content

Public buckets (s3://bucket/photo.jpg world-readable) are a common security mistake.

For private content:

  1. Bucket is private (no anonymous access)
  2. API checks authorization ("can user 42 view this video?")
  3. API returns a signed URL β€” temporary link with cryptographic signature
  4. Client downloads directly from S3/CDN using that URL
  5. URL expires (e.g., 15 minutes)
https://cdn.example.com/videos/abc.mp4
  ?X-Amz-Expires=900
  &X-Amz-Signature=...

Analogy: A concert venue doesn't leave all doors open. You show your ticket at the gate; they give you a wristband valid for tonight only (signed URL).

ApproachUse when
Public CDN URLContent is truly public (marketing images)
Signed S3 URLPrivate downloads, expiring access
Signed CDN URLPrivate content but still served from edge (CloudFront signed URLs/cookies)
Proxy through APISmall private files only; doesn't scale for video

Media pipeline (image/video processing)

Users upload a raw file; the app serves optimized versions (thumbnails, 720p, 1080p). This is CPU-heavy and slow β€” never block the HTTP upload response on transcoding.

Typical steps

StepActionStorage
1Client uploads originals3://bucket/originals/{id}.mp4
2API sets DB status = processingPostgres row
3Worker picks job from queueSQS / RabbitMQ
4Worker transcodes (FFmpeg)Writes 720p/{id}.mp4, thumb/{id}.jpg
5Worker updates DBstatus=ready, cdn_urls=[...]
6Client reads via CDNFast playback worldwide

Why async? A 10-minute video might take 5 minutes to transcode. The user shouldn't stare at a spinner β€” show "Processing…" and notify when ready (WebSocket, poll, push notification).


End-to-end HLD: Instagram-like photo app

Read path (viewing a friend's photo)

  1. Client: GET /feed β†’ API returns post metadata including cdn_url
  2. Client loads image from CDN edge (cache hit for popular content)
  3. API never streams image bytes

Write path (uploading a photo)

  1. Client: POST /photos/init β†’ presigned URL + photo_id
  2. Client: PUT to S3
  3. Client: POST /photos/{id}/complete
  4. Worker: resize to 1080p, 400px thumb, WebP variant β†’ S3
  5. DB updated; feed can show the post

Storage classes & lifecycle (bonus)

S3 offers tiers for cost optimization:

ClassUse caseTrade-off
StandardHot, frequently accessedHighest cost, lowest latency
Infrequent AccessBackups, old uploadsCheaper, retrieval fee
GlacierArchives, complianceCheapest, minutes–hours retrieval

Lifecycle rules: Automatically move objects older than 90 days to cheaper storage β€” like moving old warehouse boxes to a distant archive facility.


Common mistakes (and how to fix them)

MistakeWhy it's badFix
Storing videos in Postgres BLOBsExpensive, slow, doesn't CDN wellMetadata in DB, bytes in S3
Public S3 bucket for "private" appAnyone with URL accesses dataPrivate bucket + signed URLs
API proxies all downloadsBandwidth bottleneckCDN + direct/signed access
No complete step after presigned uploadOrphan files, broken metadataClient confirms; API verifies with HEAD
CDN-caching personalized responsesUser A sees User B's dataCache-Control: private or no CDN
Blocking upload response on transcodeTimeouts, bad UXQueue + async workers
Same key for updated fileStale CDN cacheVersion keys (photo_v2.jpg) or cache purge

Real-world examples

ProductObject storageCDNNotes
NetflixS3 (origin)Open Connect (custom CDN)Encoded segments, not raw uploads
InstagramS3/GCSMeta CDNPresigned uploads, async image processing
GitHubS3FastlyRelease assets, user attachments
NotionS3CloudFrontFile blocks, image previews

Interview talking points

When the prompt mentions images, video, or file uploads, say:

"I'll store metadata in Postgres and the actual bytes in S3. Uploads go through presigned URLs so our API isn't a bandwidth bottleneck. Processed derivatives are served via CDN for low latency globally. Private content uses short-lived signed URLs after auth checks."

That single paragraph signals senior awareness.


Check your understanding (Q&A)

1. Why store video in S3 instead of MySQL?

Answer

MySQL is optimized for structured, queryable rows β€” not streaming multi-megabyte blobs. S3 offers cheap durable storage, horizontal bandwidth scaling, and direct client uploads via presigned URLs. The database keeps metadata (title, owner, processing status, S3 key) where queries and indexes make sense.

2. What problem does a CDN solve?

Answer

Latency: Users fetch from nearby edge servers instead of a distant origin. Origin load: Popular content is served from cache, so S3/origin handles far fewer requests. Bandwidth cost: CDNs are designed for massive egress at the edge.

3. Why use presigned uploads?

Answer

The API server doesn't sit in the data path for large file bytes. Clients upload directly to S3 using a temporary scoped credential. This scales upload bandwidth independently of app server count and avoids timeout/memory issues on the API tier.

4. What's the difference between a presigned upload URL and a signed download URL?

Answer

Presigned upload (PUT): Grants temporary permission to write an object to a specific key β€” used during upload init. Signed download (GET): Grants temporary permission to read a private object β€” used after auth check so authorized users can stream/download without making the bucket public.

5. When would you NOT put content on a CDN?

Answer

When content is personalized per user (private feed HTML), frequently changing without cache invalidation, or highly sensitive and shouldn't be cached on shared edge infrastructure without encryption and short TTLs. Also when files are huge one-off downloads where CDN benefit is minimal.

6. Walk through what happens on a CDN cache miss.

Answer

User requests https://cdn.example.com/img/abc.jpg. Nearest edge doesn't have it. Edge fetches from origin (S3 or origin server), stores a copy locally, returns to user. Subsequent users in that region get a cache hit until TTL expires or the object is evicted.

7. Why enqueue a transcode job instead of transcoding in the API request?

Answer

Transcoding is CPU-intensive and slow (seconds to minutes). Blocking the HTTP request would cause timeouts and tie up API worker threads. A queue decouples acceptance from processing, allows retries, and lets you scale transcode workers independently.


Quick reference card

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  METADATA  β†’  Database (Postgres)                           β”‚
β”‚  BYTES     β†’  Object Storage (S3)                           β”‚
β”‚  FAST READ β†’  CDN (CloudFront)                              β”‚
β”‚  UPLOAD    β†’  Presigned URL (client β†’ S3 direct)            β”‚
β”‚  PRIVATE   β†’  Signed URL (short TTL after authz check)      β”‚
β”‚  PROCESS   β†’  Queue β†’ Workers β†’ S3 derivatives β†’ CDN        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Next: 14. Monolith vs Microservices β€” when to keep everything in one deployable vs split into separate services.