Design Photo Sharing

How to design a photo sharing app, from direct uploads and CDN delivery to partitioning and viral posts, and what interviewers ask about it.

Case study30 minLesson 1 of 10
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A photo sharing app lets users upload photos with a caption, follow other users, and scroll a feed of the newest photos from the people they follow. It also shows a profile grid for each user and lets people like posts. Instagram is the usual example.

The design is hard because the system stores two very different kinds of data. Photos are large, never change and are read constantly, so they belong in object storage behind a CDN. Metadata such as posts, follows and likes is tiny and changes constantly, and accounts with millions of followers create hot spots. Interviewers ask this to see whether you keep the two apart. The steps follow A Framework for Any Design, and the feed itself is covered in Design a News Feed.

Clarify the problem

The first five minutes
Interviewer

Design a photo sharing app.

You

I'll assume users can upload a photo with a caption, follow people, see a feed, view a profile grid, and like posts. Are comments, stories, video or direct messages in scope?

Interviewer

Leave out stories, video and messages. Likes are in scope.

You

How many users are there, and how uneven are the follower counts?

Interviewer

Assume 200 million daily users and about 50 million new photos a day. Most people have a few hundred followers, but some accounts have 50 million.

You

Then almost all of the bytes are images. I'll treat a posted photo as something we must never lose, and I'll allow the feed to be a few seconds stale and the like counts to be approximate.

  • Functional: upload a photo with a caption, follow and unfollow users, show a home feed with the newest posts first, show a profile grid, and like and unlike posts.
  • Non-functional: a photo is never lost once the user has posted it, the feed loads in under 200 ms, images appear within about a second, a post reaches followers within 10 seconds, and reads stay available when parts of the system fail.
  • Out of scope: video, stories, messages, search, ads and feed ranking.

Estimate the scale

The estimates use 86,400 seconds a day and a peak of three times the average.

  • Uploads: 50 million photos a day is about 580 photos a second on average and about 1,700 at peak.
  • Feed loads: at 10 app opens per user per day, 2 billion feed loads a day is about 23,000 a second.
  • Bytes per photo: a 2 MB original plus three resized copies of 30 KB, 120 KB and 250 KB, which is 2.4 MB in total.
Estimate: Photo storage per year

How much photo storage does one year of uploads add, before replication?

You know
  • 50 million new photos a day
  • 2 MB original plus 400 KB of resized copies per photo
  • Nothing is deleted

Show the working
  1. Per day: 50 × 106 × 2.4 MB = 120 TB
  2. Per year: 120 TB × 365 ≈ 44 PB
  3. The originals are 2 of every 2.4 MB, which is about 36.5 PB

Estimate 44 PB (anything from 15 PB to 150 PB is a good answer)

Originals are rarely read after processing, so they can move to colder storage after a month.

Estimate: Image bandwidth to viewers

Each feed load shows about 10 photos at the 120 KB feed size. What is the average outgoing image bandwidth?

You know
  • 23,000 feed loads a second
  • 10 photos per load
  • 120 KB per photo

Show the working
  1. Per load: 10 × 120 KB = 1.2 MB
  2. 23,000 × 1.2 MB ≈ 28 GB/s on average, and about 83 GB/s at peak

Estimate 28 GB/s (anything from 9 GB/s to 90 GB/s is a good answer)

Only a CDN can serve this much. Even if 95% of requests are CDN hits, the photo store still has to send about 1.4 GB/s.

Your turn: Define the API

Write the endpoints for uploading and posting a photo, reading the feed, following a user and liking a post. Say where the image bytes travel.

Compare with a model answer

The client asks the API for a signed URL, sends the bytes directly to object storage, and then creates the post. The feed returns metadata with CDN URLs, so image bytes never pass through the API servers.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /v1/uploads                  body: { "content_type": "image/jpeg", "bytes": 2048000 }
  201 { "photo_id": "p7001", "upload_url": "https://store.../p7001/original?sig=...",
        "expires_in": 900 }
  413 Payload Too Large   over the 20 MB limit
 
PUT  {upload_url}                 the raw bytes, straight to the photo store
 
POST /v1/posts    Idempotency-Key: (client-generated)
  body: { "photo_id": "p7001", "caption": "Harbour at dusk" }
  202 { "post_id": "1849...", "status": "processing" }
  409 Conflict      photo already used by another post
 
GET  /v1/feed?cursor=...&limit=10
  200 { "posts": [ { "post_id", "author", "caption", "likes": 12400,
        "images": { "thumb": "https://cdn.../p7001/t.v1.jpg", "feed": "...", "full": "..." } } ],
        "next_cursor": "..." }
 
GET  /v1/users/{id}/posts?cursor=...      profile grid, newest first
PUT  /v1/users/{id}/followers/me          follow (DELETE to unfollow)
PUT  /v1/posts/{id}/likes/me              like (DELETE to unlike)

The decision worth arguing is that creating a post returns 202 with the status processing. The API servers never saw the image bytes, so no post is usable until a worker has checked the file and produced the resized copies. Follow and like are PUT requests, so repeating one after a timeout has no extra effect.

Your turn: Model the data

Sketch the records for posts, follows and likes. Choose a partition key for each one and say which reads it serves.

Compare with a model answer

Posts are partitioned by author and sorted by a time-ordered id. Follows are stored in both directions, and likes are partitioned by the user who liked, with a separate count per post.

Model the data

Metadata tables (wide-column store)
posts               PRIMARY KEY ((author_id), post_id)   -- post_id DESC
  author_id   BIGINT
  post_id     BIGINT      -- 64-bit, time-ordered
  photo_id    VARCHAR(16)
  caption     TEXT        -- up to 2,200 chars
  status      VARCHAR(10) -- processing | ready | failed | deleted
  width, height, image_version INT
 
followers           PRIMARY KEY ((followee_id, bucket), follower_id)
following           PRIMARY KEY ((follower_id), followee_id)
 
photos              PRIMARY KEY (photo_id)
  post_id     BIGINT NULL, processed BOOLEAN           -- see "upload"
 
likes               PRIMARY KEY ((user_id), post_id)     -- did I like it?
like_counts         PRIMARY KEY (post_id)
  count BIGINT,  last_offset BIGINT                     -- see "hot posts"

Every read asks for the rows under one key, newest first, and no query joins tables. That access pattern fits a wide-column store such as Cassandra, which partitions data by key, keeps the rows of a partition sorted, and handles a high write rate.

Post ids come from a time-ordered ID generator, so sorting by id is the same as sorting by time and a cursor simply means "posts older than this id". The store keeps 3 replicas and uses a quorum of 2 for reads and writes, so every read overlaps with the latest acknowledged write.

Your turn: High-level design

Sketch the boxes. Where do the bytes go on upload, what makes the three sizes, where are images served from, and when does a post reach followers?

Compare with a model answer

Bytes go to a photo store, and its upload event wakes resize workers, which mark the post ready and trigger fan-out. A CDN serves the images and the API serves only metadata.

High-level design

Image bytes go straight from the phone to the photo store and come back through the CDN. The API handles only metadata, and a post reaches followers once the resize workers mark it ready.Phone app to CDN (GET image); Phone app to Photo store (PUT, signed URL); Phone app to API servers (post, feed, follow); CDN to Photo store (on miss); Photo store to Upload events (object created), asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store (3 sizes); Resize workers to Metadata store (mark ready); Resize workers to Feed service (fan out), asynchronous; API servers to Metadata store (posts, likes); API servers to Feed service (feed ids).Phone appCDNAPI serversPhoto storeFeed serviceUpload eventsResize workersMetadata storeGET imagePUT, signed URLpost, feed, followon missobject created3 sizesmark readyfan outposts, likesfeed ids

request and replyasynchronous message

Image bytes go straight from the phone to the photo store and come back through the CDN. The API handles only metadata, and a post reaches followers once the resize workers mark it ready.
Upload, process, view, and a worker failureUse the arrows or ← → keys
  1. Upload, process, view, and a worker failure, step 1Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversp7001Photo storeFeed serviceUpload eventsResize workersMetadata store

    1Mia picks a 2 MB photo. The API reserves the id p7001 and returns a URL that is signed for one upload of at most 20 MB and is valid for 15 minutes.

  2. Upload, process, view, and a worker failure, step 2Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storep7001 originalFeed serviceUpload eventsResize workersMetadata store

    2The app sends the bytes straight to the photo store, so the API servers never carry them.

  3. Upload, process, view, and a worker failure, step 3Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storeFeed serviceUpload eventsResize workersMetadata storeprocessing

    3The app creates the post. The API stores it with the status processing and answers 202.

  4. Upload, process, view, and a worker failure, step 4Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storeFeed serviceUpload eventsResize workersMetadata store
    attempt
    1

    4The store publishes an "object created" event. A resize worker decodes the file to prove that it is an image and strips the location data from it.

  5. Upload, process, view, and a worker failure, step 5Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storeFeed serviceUpload eventsredeliverResize workersdownMetadata store
    attempt
    2

    5The worker crashes before it acknowledges the event, so after a 60-second visibility timeout the queue delivers the event again.

  6. Upload, process, view, and a worker failure, step 6Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storeFeed serviceUpload eventsResize workersMetadata storeready
    attempt
    2

    6A second worker writes the 3 sizes to keys that are fixed by photo id and size, which overwrites any half-written file, and then marks the post ready.

  7. Upload, process, view, and a worker failure, step 7Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storeFeed service400 insertsUpload eventsResize workersMetadata store

    7Only now does fan-out start. The pair (Mia, post id) is added to the feeds of her 400 followers, so no follower sees a post without its picture.

  8. Upload, process, view, and a worker failure, step 8Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNAPI serversPhoto storeFeed serviceUpload eventsResize workersMetadata store

    8Leo opens his feed. The API gets 10 (author, post) pairs from the feed service and reads each post from its author's partition.

  9. Upload, process, view, and a worker failure, step 9Phone app to CDN; Phone app to Photo store; Phone app to API servers; CDN to Photo store; Photo store to Upload events, asynchronous; Upload events to Resize workers, asynchronous; Resize workers to Photo store; Resize workers to Metadata store; Resize workers to Feed service, asynchronous; API servers to Metadata store; API servers to Feed service.Phone appCDNmiss, cachedAPI serversPhoto storeFeed serviceUpload eventsResize workersMetadata store

    9His app fetches each 120 KB image from the CDN. The first request that misses at this edge loads the image from the store once, and later viewers get it from the CDN.

1 / 9

Deep dives

Uploading photos safely

Sending photos through the API servers ties up a connection for as long as a slow mobile network takes and makes the API fleet carry every image byte. A signed URL avoids that: the API checks the request and returns a URL that allows one upload to one key, with a maximum size and content type, for a short time, and the phone sends the bytes directly to the photo store. See Blob Storage.

Those bytes skipped your code, so the client could upload something that is not an image. The post therefore stays in the status processing until a worker has decoded the file. A file that does not decode is deleted and the post is marked failed. A cleanup job deletes posts that stay in processing for 24 hours.

The worker can also finish before the post request arrives and find no post to mark as ready. To handle this, both sides write to the photo's row in the photos table with a compare-and-set. The post request sets post_id only if it is empty, which also produces the 409 for a reused photo, and the worker sets processed. Whichever write lands second marks the post ready and starts fan-out, so fan-out runs exactly once.

Creating the resized copies

Phones need small images, so each photo is stored in several sizes, and the question is when to create them. Creating every size eagerly after upload means each size exists before anyone views the photo, but the post is delayed by a few seconds and adding a size later means reprocessing every photo. Creating sizes on demand at the edge allows any size and wastes nothing on unviewed photos, but the first viewer waits and a viral post sends a burst of resize work to the origin. Shrinking on the phone saves server CPU, but the server cannot trust the result, so it only supplements server-side processing.

When to make the resized copies
OptionGood atBad atPick it when
Eagerly, after upload Usual defaultEvery size exists before anyone views the photo, so serving is a plain file read.The post is not ready for a few seconds, and adding a size later means reprocessing every photo.You have a small, fixed set of sizes. This is the usual choice.
On demand at the edgeAny size or format is possible, and nothing is made for photos nobody views.The first viewer waits for the resize, and a viral post sends a burst of resize work to the origin.You need many sizes and most photos are never viewed.
On the phoneIt uses no server CPU and makes uploads smaller.The server cannot trust or control the result.As an extra step that shrinks uploads, never as the only step.

Serving images from the CDN

Each image URL contains the photo id, the size and a version, for example /p7001/t.v1.jpg. The content behind a URL never changes, so the CDN can cache it for a year. If a photo is processed again, the worker writes v2 and the post points to the new URL, so nothing has to be purged. A regional origin shield, a CDN layer in front of the store, turns hundreds of edge locations missing on a new photo into one request to the store. See CDNs.

Choosing the partition key for posts

The key has to serve a profile grid (one author's posts, newest first) and a feed page (10 posts from different authors).

Partition by post id. Posts spread evenly across the cluster, and a feed page takes 10 direct lookups. However, one author's posts end up on many partitions, so a profile grid needs a second table that is kept in step with the first.

Partition by author, sorted by post id. A profile grid is one read of one partition, and a feed entry that stores the author id as well as the post id still needs only 10 lookups. The cost is heavy read traffic on the partition of a famous author, which is a caching problem because posts never change.

Partition by day. Archiving old posts is easy, but every write and every read of a fresh post goes to today's partition, which becomes a hot spot.

Follows are written twice, in followers and following, because the two questions need different partitions. Fan-out asks who follows Mia, and pulling posts from big accounts asks whom Leo follows. A follower list of 50 million entries at 16 bytes each is 800 MB, which is too large for one partition. The followers table therefore adds a bucket number for every 1 million followers.

Hot posts and like counts

When an account with 50 million followers posts, the image, the fan-out, the post record and the likes all become hot. The CDN handles the image, so three problems remain.

Fan-out. Writing 50 million feed entries at 200,000 inserts a second takes 250 seconds, which is far over the 10-second goal. Use the hybrid from Design a News Feed: for accounts above about 100,000 followers, do not push the post into feeds, and let each follower's feed fetch it at read time.

The post record. If 20% of the followers open the post within an hour, that is 10 million reads over 3,600 seconds, or about 2,800 reads a second for one key. The post never changes, so cache it.

Likes. If 5% of the followers like the post within 10 minutes, that is 2.5 million likes over 600 seconds, or about 4,200 likes a second on one post.

The simplest design runs count = count + 1 on the post row for every like, so all 4,200 writes a second compete for one row. Splitting the counter into several rows spreads the writes, but every read must then sum them.

The third option is to batch the updates. The likes table is partitioned by the user who liked, so those writes spread evenly. Each like is also sent to a stream partitioned by post id. The aggregator that owns a partition counts the likes it receives for one post over one second and then writes count = count + n once, so 4,200 updates a second become one update a second. This is the design to propose, because the like records stay exact and only the displayed count lags by about a second.

The stream delivers each event at least once, so after a crash the aggregator may see the same events again. To avoid counting them twice, the aggregator stores the stream offset of the last event it applied in the same row and in the same write as the count, and it ignores any event at or below that offset.

Bottlenecks and failures

At 10 times the load (500 million photos a day) the problems are bytes and cost. Storage grows by about 440 PB a year, so originals move to cold storage after 30 days. Image traffic averages 280 GB/s, which makes the CDN the largest cost.

When this failsWhat happensWhat you do
An API serverThe requests it was handling fail.The app retries the request, which is safe because post creation is idempotent.
The upload event queueNew posts stay in the status processing.A job re-enqueues posts that are still processing after 10 minutes, so no photo is lost.
The resize workersPosts become ready later than usual.Autoscale the workers on queue depth, which is what delays posts.
A metadata replicaOne of the three copies of the data is gone.Quorum reads and writes (2 of 3) continue, and you rebuild the replica.
The feed serviceThe prepared feeds are lost.Fetch the recent posts of the followed authors at read time, which is slower but works.
The CDNImages stop loading, and the store cannot serve 28 GB/s.Switch the image host name to a second CDN.

What a strong answer sounds like

Interviewers watch whether image bytes stay out of the API servers, whether the partition key follows from the access patterns, and what you say about a viral post.

LevelWhat the answer does
JuniorStores images in object storage and metadata in a database, adds a CDN, and describes a basic feed only after the interviewer asks for it.
Mid-levelEstimates storage and bandwidth, uses signed URLs and a resize queue, and justifies push or pull for the feed.
SeniorSeparates media from metadata using the numbers, holds posts until they are processed, derives the partition keys from the access patterns, and handles a celebrity post on every axis.
The partition keyStrong answer
Interviewer

Why partition posts by author? Doesn't that create hot spots?

You

Partitioning by author makes a profile grid one sorted partition read, and because feed entries carry the author, a feed page can still fetch its posts directly. The hot spot is reads of a famous author's posts, but those posts never change, so caches absorb the reads. Likes are partitioned by the user who liked, and the counts are updated in batches.

Follow-up questions

A user deletes a photo. What has to happen?

First mark the post deleted, so that every read skips it immediately. Then delete the stored objects and purge the CDN in the background.

The phone retries a post after a timeout. Do you get two posts?

No. The client sends an idempotency key with the request, so the second request returns the post that the first one created.

How do private accounts change the design?

The feed and the profile grid must check that the viewer is an approved follower before they return a post. Private images should be served through short-lived signed CDN URLs, which lowers the CDN hit rate for them.

Do the like counts have to be exact?

The records in the likes table must be exact, because they decide whether a user sees a post as liked. The displayed count can lag by a second or so and does not have to be exact at any moment. A nightly recount from the likes table removes any drift.

Self-review: photo sharing0 of 13

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure