Course contents

17. Real-World System Design Lesson 12 of 20

Photo Sharing Platform

Design a photo-sharing service end to end: estimates, presigned uploads to object storage, async thumbnails, metadata sharded by user, and a CDN for reads.

25 minAdvanced12 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Reads outnumber writes by orders of magnitude and bytes dwarf metadata: they get separate paths and stores.
  • Presigned URLs let phones upload straight to object storage; the API only signs and records.
  • Thumbnails are made asynchronously; workers must exceed the average upload rate, and the queue buffers bursts.
  • Metadata is sharded by user id so profile queries touch one shard; cross-user queries need a separate index.
  • Immutable photos and Zipf popularity let a small CDN cache answer most views; a cold or lost cache sends that load to the origin.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A photo-sharing platform lets people upload photos from their phones and lets everyone else view them in feeds, on profiles and through shared links. Under the product sit four distinct jobs: accepting large uploads durably, producing derived images (thumbnails and resized versions), storing metadata about every photo, and serving an enormous number of reads quickly all over the world. This case study designs each of them and simulates the parts where load decides the outcome.

Why it exists

As a design exercise it is the classic example of a system whose read path and write path have completely different shapes. Uploads are relatively rare but large and slow; views are tiny per request but outnumber uploads by two or three orders of magnitude; metadata is small but queried constantly. A design that treats all three alike, for example one API that receives bytes, stores them and serves them back, fails on every axis at once.

How it works

Requirements and estimates. Functional: upload a photo, view photos (feed, profile, link), generate thumbnails. Non-functional: never lose an accepted photo, fast views worldwide, a new photo may take a few seconds to appear. Illustrative numbers used in the lesson: 50 M daily users, one in ten uploads one photo a day → 5 M uploads/day ≈ 58/s on average and ~150/s at peak. With 2 MB per original and ~300 KB of thumbnails that is ~11.5 TB of new data per day, ~4 PB per year. At 30 views per user per day, 1.5 B views/day ≈ 17,000/s on average: a read-to-write ratio of ~300:1. Metadata at ~1 KB per photo is ~5 GB/day.

Uploads with presigned URLs. The phone asks the Upload API for permission to upload. The API authenticates the user, picks an object key (for example photos/{user}/{photo_id}) and returns a presigned URL: a URL carrying a signature made with the service’s credentials that permits one operation (a PUT of that key, often with a size and content-type constraint) for a short time. The phone uploads the bytes directly to object storage, then tells the API the upload is complete (or storage emits an event when the object lands). Large files use multipart upload so a dropped connection resumes instead of restarting. The API never touches the bytes, so its workers are busy for milliseconds, not for the seconds a mobile upload takes.

Metadata. On completion the API writes a row: photo id, owner, object key, dimensions, caption, timestamps, visibility. The dominant queries are “this user’s photos, newest first” and “this photo’s details”, so the store is sharded by user id (hash of the id, with consistent hashing or a directory so shards can be added). A profile page then reads one shard. Photo ids should embed the owner’s shard or be looked up through a small mapping, so a direct link can find its row.

Thumbnails asynchronously. The API also enqueues a job (or object storage publishes an “object created” event). Workers fetch the original, produce a few sizes and formats, write them back under keys derived from the photo id and size, and mark the row ready. The upload request does not wait for any of this. Workers must keep up with the average upload rate; the queue absorbs bursts. Jobs are delivered at least once, so they are idempotent: re-running a job overwrites the same keys with the same bytes.

Reads through a CDN. Photos are immutable once uploaded (an edit creates a new key), so they can be cached aggressively with long TTLs. Viewers fetch image URLs from a CDN; the edge serves hits and fetches misses from object storage (the origin), usually through an origin shield, a mid-tier cache that collapses misses from many edges into one origin fetch. Popularity is heavily skewed, roughly Zipf: a small fraction of photos (new posts from popular accounts) gets most views, so an edge cache holding a small fraction of the catalogue answers most requests. The long tail of old photos misses and sets the tail latency. Private photos use signed CDN URLs or cookies with short expiry.

When to use it

This shape fits any service built around user-uploaded media: photos, documents, audio, short videos, attachments in chat or email. Whenever blobs are large, immutable and read far more often than written, separate the bytes (object storage + CDN) from the metadata (database) and do derived work asynchronously.

When not to

  • Small internal tools with a handful of users: storing files through the app server is simpler and the problems above never appear.
  • Data that changes in place frequently (collaborative documents): immutability and long CDN TTLs no longer hold; you need versioning and invalidation designed in.
  • Strictly private content where every read must be authorised against live permissions: CDN caching still works with signed URLs, but revocation is delayed until they expire.

Trade-offs

Choice You gain You pay
Presigned direct upload API stays small and fast; storage scales the bytes Two-step protocol; orphaned objects from abandoned uploads need cleanup (lifecycle rules)
Async thumbnails Fast uploads; processing scales separately; bursts buffered A photo can be visible before its thumbnails exist; idempotency and monitoring of backlog
Shard metadata by user id Profile reads and writes touch one shard Cross-user queries need a separate index; very active accounts make hot shards
CDN with long TTLs Most reads never reach the origin; low latency worldwide Deletes and privacy changes are delayed until purge or expiry; the cache becomes load-bearing
Several stored sizes Small downloads for small screens More storage and processing per upload; on-the-fly resizing at the edge is the alternative

Alternatives

  • On-the-fly image resizing at the CDN or an image service, caching each requested size, instead of precomputing thumbnails. Less storage and no fixed size list; the first request for a size is slow and the resizer needs protection from arbitrary-size abuse.
  • Upload through an edge or upload service that terminates connections close to users and streams to storage, when clients cannot use presigned URLs or content must be scanned before it is stored.
  • A wide-column or key-value store for metadata (partition key = user id, clustering by time) instead of sharded relational databases; it gives the same access pattern with built-in partitioning.

Failure modes

  • Proxying uploads through application servers: slow clients hold workers for seconds, concurrency runs out and uploads are rejected even though the servers are idle in CPU terms.
  • Worker capacity below the average rate: the queue grows without bound and thumbnails arrive later and later; alert on queue age, not just depth.
  • Non-idempotent jobs: at-least-once delivery after a worker crash runs the job twice; side effects (counters, notifications) are duplicated.
  • Cold or wiped cache: a global purge, a cache fleet restart or a new region sends all views to the origin, which may throttle or fail. Mitigate with an origin shield, request coalescing, targeted purges and origin headroom.
  • Hot shard: a very popular account concentrates writes and reads on one metadata shard; cache its profile and spread its reads.
  • Orphaned objects: uploads that never call “complete” leave bytes without metadata; lifecycle rules or a reconciliation job clean them up.

In production

Object stores offer very high durability by replicating or erasure-coding data across devices and zones; cross-region replication is extra and has its own cost. Lifecycle policies move old, rarely viewed originals to cheaper storage classes, which matters because storage grows forever. Uploads are scanned (malware, abuse) and stripped of sensitive EXIF data such as GPS location before thumbnails are published. Monitor upload success rate, queue age, CDN hit ratio and origin request rate; the hit ratio dropping is often the first sign of a coming origin overload. Feed generation (which photos a user sees) is its own problem; see the social media feed case study.

Common misconceptions

  • “The API should receive the upload so it can validate it.” Validation (size, type, owner) is enforced in the presigned URL’s conditions and after upload by workers; the API does not need the bytes.
  • “A queue fixes slow processing.” It fixes bursts. Sustained arrival above processing capacity only makes the backlog longer.
  • “A cache holding 10% of the data serves 10% of the requests.” With skewed popularity it serves far more, often most of them.
  • “Deleting the object deletes the photo.” Copies remain in CDN caches until they expire or are purged.

Interview angle

Start with requirements and numbers, and say what they imply: “300:1 reads, 11 TB/day of bytes, metadata is small”. Then draw the upload path with presigned URLs, the async pipeline with a queue and idempotent workers, the metadata store with its shard key justified by the main query, and the read path through a CDN. Interviewers often probe: how a new photo appears before thumbnails exist, how you handle deletes and private photos with a CDN, what happens when the cache is cold, how you find a photo’s row from its id, and how storage cost is controlled. Quantify worker counts against the upload rate and origin load against the hit ratio.

Model assumptions

The simulation is a simplified, scaled-down model, not a benchmark: 40 uploads/s and 1,200 views/s instead of the estimate’s peak rates. The Upload API has 64 workers; proxying an upload holds a worker for ~8 s, a control call takes ~15 ms. Object storage is modelled as a store serving 48 requests at once at ~60 ms per read and ~100 ms per write (about 800 reads/s). The direct upload from the phone to storage via a presigned URL is a scripted illustration (packets drawn on the stage, not simulated load); thumbnail workers writing results back to storage are not modelled. Thumbnail workers have 4 slots each at ~300 ms per photo, with a 5 s visibility timeout. Metadata writes go through a consistent-hash router to three shards keyed by a Zipf-distributed user id. Views pick one of 20,000 photos with Zipf(1) popularity; the CDN edge cache is an LRU of 2,000 photos; one-way latencies are 80 ms to the origin, 10 ms to the edge and 60 ms from the edge to the origin. Arrivals are Poisson, service times lognormal. Utilisation is busy-slot fraction, not CPU. All numbers are illustrative orders of magnitude.

The lesson as textEvery step of the simulation, written out.
  1. 1. What are we building?

    A photo-sharing app: users upload photos from their phones, everyone views them in feeds and on profiles, and every photo needs thumbnails in a few sizes.

    The non-functional requirements decide the design: uploaded photos must never be lost (durability), viewing must be fast everywhere in the world, and an upload may take a few seconds to show up for others. Nothing moves yet: this is the starting sketch, a phone talking to an Upload API that stores the file.

    Scene: Three nodes and no traffic yet: Uploaders connected to an Upload API, which is connected to Object Storage. Annotations list the requirements: upload and view, durability, and a few seconds of delay being acceptable.

    Key idea: Write down what must be durable, what must be fast and what may be eventually consistent before drawing boxes.

  2. 2. Back-of-the-envelope numbers

    Illustrative numbers: 50 M daily users, one in ten uploads one photo a day → 5 M uploads/day ≈ 58/s on average, ~150/s at peak. A 2 MB original plus ~300 KB of thumbnails is about 11.5 TB of new storage per day, ~4 PB a year.

    If each user views 30 photos a day that is 1.5 B views/day ≈ 17,000/s, several times that at peak: reads outnumber writes about 300 to 1. Metadata is tiny by comparison: ~1 KB per photo, about 5 GB/day.

    Three conclusions: bytes and metadata go to different stores, the read path needs a cache close to users, and storage growth is the long-term cost.

    Scene: Same three nodes with the estimates as annotations: about 58 uploads per second on average, 11.5 TB of new storage per day, about 17,000 views per second, a read-to-write ratio of about 300 to 1.

    Key idea: Reads ≫ writes, bytes ≫ metadata: they get different paths and different stores.

  3. 3. Streaming bytes through the API

    The first design streams every photo through the Upload API into storage. Uploads start at a scaled-down 40 per second.

    A 2 MB photo over a slow mobile link takes seconds, and the API worker is held for all of it (~8 s here). 40 uploads/s × 8 s means ~320 uploads in progress, but the API has 64 workers. They are all busy, the waiting line fills and most uploads are rejected, although the API does almost no real work: it just copies bytes.

    Scene: Uploads flow through the Upload API into storage. Every API worker is busy copying bytes, its queue is full and most uploads fail with 503.

    Key idea: Long, slow transfers through application servers waste their concurrency on waiting for the network.

  4. 4. Upload straight to object storage

    Now the phone asks the API for a presigned URL: a short-lived URL signed with the API’s credentials that allows exactly one PUT of one object key. The phone uploads the bytes directly to object storage (the long amber hop, scripted), then calls the API once more to say the upload is complete.

    The API only signs and records: ~15 ms per call. The rejections stop and the API is nearly idle. Bytes never pass through our servers; storage, which is built for exactly this, absorbs them.

    Scene: The phone gets a signed URL from the Upload API, uploads the bytes directly to Object Storage, then tells the API the upload is complete. The API is almost idle and no upload fails.

    Key idea: Let clients send large blobs directly to object storage with a presigned URL; the API handles only small control calls.

  5. 5. Thumbnails, asynchronously

    When an upload completes, the API writes a metadata row and puts a thumbnail job on a queue, then answers the phone at once. Thumbnailer workers take jobs, resize the photo into three sizes and write them back to storage.

    But two workers manage only ~27 photos per second and uploads arrive at 40. Watch the queue’s message count grow steadily. The upload itself stays fast, because nobody waits for thumbnails, yet new photos take longer and longer to get them.

    Scene: The API writes metadata and enqueues a thumbnail job per upload. Two thumbnail workers are fully busy and the queue keeps growing, while uploads still complete quickly.

    Key idea: A queue decouples the upload from slow processing, but workers must still keep up with the average arrival rate.

  6. 6. Size workers for the rate, the queue for bursts

    Four workers handle ~53 photos/s, comfortably above the 40/s average. The queue stays near empty.

    One second in, a burst doubles uploads to 80/s for two seconds. The queue absorbs it: the backlog climbs while the burst lasts and drains afterwards, and not a single upload fails. That is the queue’s job: capacity for the average, a buffer for the peaks.

    Scene: Four thumbnail workers keep up with 40 uploads per second. A two-second burst at 80 per second builds a backlog in the queue, which drains after the burst; no upload fails.

    Key idea: Workers ≥ average rate; the queue’s depth buys time during bursts instead of failed uploads.

  7. 7. Metadata sharded by user

    Photo bytes live in object storage; the database holds the small rows: owner, object key, caption, timestamps. At ~5 M rows a day it outgrows one machine within a few years, so we shard by user id behind a router that hashes the id (consistent hashing).

    The main queries are “this user’s photos, newest first” for the profile page and the write on upload: with a user-id key both touch one shard. The simulated writes spread over all three shards. The price: queries across users (a global “most liked” list) must ask every shard, so they are built elsewhere, from events.

    Scene: The Upload API writes metadata through a shard router that hashes the user id to one of three metadata shards. Writes are spread over all three shards.

    Key idea: Pick the shard key from the dominant query: by user id, a profile page reads one shard.

  8. 8. Serving photos from the origin

    Now the side that matters most: views. Viewers request photos through an Image API that reads them from object storage, the origin. At a scaled-down 1,200 views/s that is more than the ~800 reads/s our simulated storage can serve.

    Storage is saturated. The Image API’s workers all sit waiting on it, the API’s queue fills and about a third of the views are rejected. Even a successful view is slow: viewers are far away (80 ms each way), so the network alone costs 160 ms before any work.

    Scene: Viewers send 1,200 requests per second to an Image API that reads every photo from Object Storage. Storage is saturated, many views fail and even successful ones take over 200 ms.

    Key idea: At 300:1 read-to-write, the read path sets the architecture: serving every view from the origin fails on both load and distance.

  9. 9. A CDN in front of storage

    Photos never change once uploaded (an edit creates a new object key), which makes them ideal for a CDN. Viewers now hit an edge 10 ms away. The edge keeps the 2,000 most recently viewed photos, 10% of the catalogue, and fetches a miss from storage.

    Popularity is skewed (Zipf): a few photos get most views. So that 10% answers well over half of the views (watch the hit ratio), storage gets only the misses and drops below capacity, the errors stop and a typical view is now ~20 ms. The misses, a long trip to the origin, set the tail latency.

    Scene: Viewers request photos from a nearby CDN edge. Its cache answers most views; misses are fetched from Object Storage, which is no longer saturated. No views fail and typical latency is about 20 ms.

    Key idea: Immutable objects plus skewed popularity: a small edge cache absorbs most reads; misses set P95.

  10. 10. The edge cache is wiped

    One second in, the edge cache goes down (a bad deploy, or a purge of everything). For two seconds every view becomes a miss: 1,200 reads/s land on storage, which can do ~800. Storage saturates and views fail, exactly like before the CDN.

    At three seconds the cache is back, but empty. It refills from the misses, the hit ratio climbs, and within about a second storage falls below capacity again and the errors stop. The cache had become load-bearing capacity.

    Defences: an origin shield (a second cache tier so edges don’t all hit storage), request coalescing at the edge, purging by key instead of everything, and origin headroom.

    Scene: The edge cache fails for two seconds. Every view goes to Object Storage, which saturates and views fail. The cache comes back empty, refills, and the errors stop.

    Key idea: When a cache carries most of the load, losing it sends that load to the origin: plan for the cold cache.

  11. 11. A thumbnailer crashes mid-job

    One second in, Thumbnailer 2 crashes with jobs in progress. Those jobs were never acknowledged, so when the queue’s 5 s visibility timeout runs out (counted from when each job was handed out) it delivers them again to another worker. No thumbnail is lost and no upload fails. The three survivors run exactly at the upload rate, so the backlog creeps up until Thumbnailer 2 is back.

    This is at-least-once delivery, so a job can run twice (for example if a worker finishes just after its timeout). Make the job idempotent: the thumbnail’s key is derived from the photo id and size, so a second run overwrites the same object with the same bytes.

    Scene: Thumbnailer 2 crashes. Its unacknowledged jobs reappear in the queue within five seconds, once their visibility timeout runs out, and are processed by the other workers; uploads keep succeeding.

    Key idea: Unacknowledged jobs come back after the visibility timeout; idempotent jobs make the duplicates harmless.

  12. 12. The design and its trade-offs

    Bytes go phone → object storage via presigned URL; the API only signs and records. Thumbnails are made asynchronously by workers sized for the average rate, with the queue buffering bursts. Metadata is sharded by user. Views come from a CDN; storage serves only misses.

    Trade-offs: a new photo is visible before its thumbnails exist (show a placeholder or the original); cross-user queries need a separate index; CDN caching means a deleted photo can stay reachable until it expires or is purged; and storage, ~4 PB a year here, is the bill that keeps growing, so tiering old photos to colder storage classes matters.

    Scene: The full design runs healthy: uploads through presigned URLs, metadata on three shards, four thumbnail workers behind a queue, and views served by a CDN edge with storage behind it.

    Key idea: Separate paths for bytes, metadata, processing and reads, each sized by its own numbers.