Design a Global Photo and Video Hosting Platform
System DesignModel answerLast updated
Architect a system that stores, processes, and serves user-generated photos and short videos at planetary scale with strong durability, low latency, and controlled cost.
The Problem
You're tasked with designing a platform where users can upload, manage, and share photos and short videos. The system must handle hundreds of millions of uploads per day, serve reads globally with low latency, and remain durable and cost-effective at exabyte scale.
Functional requirements
- Upload: support both single-file and multipart (resumable) uploads
- Retrieve/download: fetch originals and processed variants (thumbnails, transcoded renditions)
- Delete and list: soft-delete with owner-scoped listing and cursor-based pagination
- Processing pipeline: auto-generate thumbnails and transcode videos into adaptive formats
- Search: filter by owner, media type, upload date, and user-defined tags
- Secure access: generate short-lived signed URLs for both upload and download
- Quotas: enforce per-user storage limits with real-time reservation and usage tracking
Non-functional requirements
Address each of the following explicitly in your answer:
- Durability: target eleven nines (10^−11 annual loss probability)
- Availability SLOs: reads vs. writes, and what happens during a regional outage
- Multi-region layout: where data lives, how it replicates, and what consistency model applies to blobs vs. metadata
- CDN integration: caching strategy and how you invalidate or avoid stale content
- Encryption: in-transit and at-rest, envelope key management
- Access control: authentication and authorization, including third-party delegation
- Abuse prevention: rate limiting, content hashing for known-bad material, quota enforcement
- Cost model: storage tiering, lifecycle policies, cold storage, and egress optimization
- Background jobs: how you achieve effectively-once semantics across thumbnailing, transcoding, and moderation
- Metadata schema and indexing: what you store, how you shard it, and what the search latency tradeoff is
- Observability: metrics, distributed tracing, audit logs
- Migrations and backfill: how you evolve the schema or reprocess billions of existing objects
- Disaster recovery: RPO/RTO targets and how you test them
- Performance targets: p95 and p99 latency for reads and uploads
Deliverables
- A rough API sketch (endpoints, key request/response fields)
- A component diagram in text or ASCII form
- Storage technology choices with justification (object store vs. block vs. file, metadata store)
- Capacity estimates with back-of-envelope numbers
Scale hints to get you started
Assume roughly 2 billion registered users, 500 million photo uploads per day, and 50 million short-video uploads per day (clips up to 60 seconds). Read-to-write ratio is around 100:1, and reads are heavily skewed toward recent and popular content.
Hints
Hint 1
Start with capacity math before drawing any boxes. Nail down ingest volume in PB/day, raw storage footprint after redundancy, peak upload rate, peak read rate, and CDN egress in Tbps — interviewers will probe these numbers and they shape every architectural decision that follows.
Hint 2
The single most important design insight is separating the two data planes: blobs are large, immutable, and eventually replicated, while metadata is small, mutable, and must be strongly consistent. Sketch a data model that keeps these on different stores with different consistency and replication policies, and explain why that split is the right call.
Hint 3
Think through the upload commit protocol as a distributed transaction: how do you atomically finalize quota, flip the metadata state to READY, and trigger background jobs without double-charging or losing work if any step crashes? Idempotency keys, an outbox pattern, and a GC sweep for orphaned blobs are the building blocks.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core design insight is that this system has two fundamentally different data planes that must be handled separately: a blob plane (large, immutable, write-once, eventually replicated) and a metadata plane (small, mutable, strongly consistent, sharded). Every architectural decision flows from keeping these planes independent.
1. Capacity Estimates
State assumptions before drawing anything.
| Quantity | Estimate |
|---|---|
| Ingest per day | 500M × 2.5 MB (original + thumb) + 50M × 60 MB (original + HLS renditions) ≈ 4.3 PB/day logical |
| Annual raw footprint | ~1.5 EB logical. With erasure coding (RS 10/4, ~1.4× overhead) and one geo copy of originals (~2×), blended multiplier ≈ 2× → ~3 EB/year raw before tiering |
| Peak upload rate | 550M / 86,400 ≈ 6.4k/s average → ~20k/s at peak |
| Peak read rate | 100:1 ratio → ~2M req/s at peak |
| CDN egress | 2M/s × ~300 KB average ≈ ~5 Tbps — the dominant cost line |
| Metadata | ~550M rows/day × 1 KB ≈ 0.5 TB/day. Shardable, tiny next to blobs |
SLOs to commit to:
- Durability: 11 nines (erasure coding + geo replication + continuous scrubbing)
- Read availability: 99.99%; upload availability: 99.9%
- Latency: first-byte p95 < 100 ms, p99 < 300 ms from CDN; metadata API p99 < 50 ms
2. API Sketch
POST /v1/media/uploads {type, size, mime, idempotency_key}
-> {upload_id, media_id, part_urls[]}
PUT <signed-part-url> (client → storage edge directly; returns ETag)
POST /v1/media/uploads/{upload_id}/complete {parts: [{n, etag}]}
-> {media_id, status: "processing"}
DELETE /v1/media/uploads/{upload_id} (abort, releases quota reservation)
GET /v1/media/{media_id} -> metadata + signed URLs per rendition
GET /v1/media?owner=X&type=video&after=<ts>&cursor=<token>
PATCH /v1/media/{media_id} {caption, tags, visibility}
DELETE /v1/media/{media_id} (soft delete; hard delete after grace period)
Key design choices: every mutating call carries an Idempotency-Key; single-file upload is just the one-part case of the multipart flow; part size is 5–16 MB to handle mobile network interruptions.
3. Component Diagram
Client ──► Edge LB ──► Upload API ──► Metadata DB (sharded, leader in home region)
│ │ │ │ CDC / outbox
│ signed PUT parts │ └► Quota Svc ▼
└────────► Storage Edge ──┴──► Object Store (EC, multi-AZ) ──► Geo-replicator ──► Region B
│
Kafka ◄── outbox ──► Workers: thumbnail · transcode · moderation · search-indexer
Viewer ──► CDN PoPs ──► Regional cache ──► Origin Read Svc ──► Object Store
▲ auth: signed URL verified at edge ▲ KMS (envelope keys)
4. Storage Choices
Blobs — object store, not block or file storage.
At EB scale, block storage is cost-prohibitive and POSIX filesystems buckle under metadata ops. A Haystack/f4-style object store (or an S3-class managed service) with erasure coding across 3+ availability zones hits 11-nines durability. Small photos should be packed into large volume files to avoid per-file inode overhead (the Haystack insight). Blobs get content-addressed keys (/{shard}/{media_id}/{rendition}/{hash}) and are never overwritten.
Metadata — sharded strongly consistent store.
MySQL with a TAO-style sharding layer, or a globally distributed SQL system (Spanner/CockroachDB), sharded by owner_id. Schema:
media:owner_id, media_id (Snowflake), state {PENDING, PROCESSING, READY, DELETED}, mime, size, sha256, blob_key, renditions{spec→blob_key}, visibility, tags[], created_at, deleted_at, key_id, home_region- Primary index:
(owner_id, created_at DESC)for list queries - Secondary index:
media_id → owner_id - Tag/full-text search: async-indexed via CDC into an Elasticsearch cluster (seconds of lag is fine)
Quota store: (owner_id) → {used_bytes, reserved_bytes, limit_bytes}, strongly consistent, co-located with metadata shards.
5. Upload Commit Protocol
This is the hardest consistency problem in the design. The sequence:
init: reserve quota (reserved += size), write a PENDING metadata row- Client PUTs parts directly to storage edge via signed URLs
complete: storage verifies the end-to-end sha256, then in a single metadata transaction:state → PROCESSING,used += size,reserved -= size, write outbox event
If a session expires, the reservation is released. Blobs without a committed row are orphaned; a GC sweep hard-deletes them after 24 hours. This keeps quota accounting accurate without a distributed 2PC.
Consistency model:
- Metadata is linearizable per object; read-your-writes is guaranteed by routing the owner to their home region's leader.
- Blobs are immutable, so eventual geo-replication is safe. A reader in a remote region that gets a cache miss falls back to the home region.
6. Background Processing: Effectively-Once Semantics
Kafka delivers at-least-once, so workers must be idempotent:
- Task key:
(media_id, rendition_spec, version)— deduplication at the consumer - Each task writes to a deterministic blob key, then does a conditional metadata update (
SET status=READY WHERE status != READY); duplicate runs are harmless - Long videos are chunked so a single file parallelizes across workers
- Failures use exponential backoff; poison messages go to a DLQ with alerting
- Moderation (perceptual hash + CSAM check) gates the transition to
visibility=PUBLIC
7. CDN, Invalidation, and Cost
Blob URLs are versioned and immutable (/v/{hash}/...), so content caches with max-age=365d and there is nothing to invalidate. Metadata URLs for "get rendition list" are short-lived signed tokens (TTL 1 hour). CDN hit rate target: 95%+, which keeps origin load around 100k req/s.
Cost levers:
- Lifecycle tiering: move objects not accessed in 90 days to infrequent-access; move cold originals to archival after 1 year
- Derivatives are regenerable — archive or delete them; reconstruct on demand
- Negotiate CDN egress volume discounts; this is the single biggest monthly line item at 5 Tbps
- Soft-delete with a 30-day grace period before hard deletion protects against accidental loss without indefinite storage cost
8. Durability and Disaster Recovery
- RS(10,4) erasure coding tolerates 4 lost fragments within a region
- Continuous background scrubbing detects and repairs latent corruption; short repair windows are what actually deliver 11 nines
- Async geo-replication of originals with RPO < 15 min
- Metadata followers in the replica region can be promoted (RTO < 30 min) during a regional failure; DNS/anycast shifts upload traffic
- Quarterly game-day drills; chaos testing of storage node loss and regional partition
9. Observability
Metrics: ingest rate, upload success/failure, processing queue depth and lag, CDN hit ratio, p95/p99 latency per endpoint, storage utilization by tier.
Tracing: end-to-end trace ID from upload initiation through processing to first CDN hit.
Audit logs: all access-control changes, signed-URL issuances, and admin deletions written to an append-only log store (separate from operational metadata).
Common Mistakes to Avoid
- Storing blobs in a relational database. Even with BYTEA/BLOB columns, this kills your IOPS budget at petabyte scale.
- Strong consistency for blobs. Immutable objects don't need it; requiring linearizability here kills throughput and adds cross-region latency.
- Skipping the outbox pattern. Writing a Kafka event and updating the database as two separate operations means you'll drop events or double-process on any crash.
- Forgetting orphan GC. Crashed uploads leave unreferenced blobs indefinitely, which silently inflates storage cost.
- One global metadata shard. At 550M rows/day it becomes a hotspot immediately; shard by owner from day one.