Design a User Photo Library and Album Service
System DesignModel answerLast updated
Design a scalable backend for storing, organizing, and retrieving user photos and albums, covering API design, storage, data modeling, and reliability.
Problem
Build the backend for a personal photo library product. Users need to upload photos, browse their collection, and keep things organized with named albums.
Core features your design must support
- Upload a photo (JPEG, HEIC, or PNG, up to ~50 MB per file).
- View a photo in its original form as well as smaller resized versions, along with its metadata: dimensions, file size, capture timestamp, camera model, and GPS coordinates.
- Create, rename, and delete albums. Deleting an album does not delete the photos inside it.
- Add and remove photos from albums. One photo can appear in multiple albums (many-to-many relationship).
- List photos in an album, or browse the full personal library, in reverse chronological order with pagination.
- Delete a photo. It must disappear from every album it belongs to.
What to cover in your answer
- Requirements and scale — state your assumptions, then derive rough numbers for upload rate, storage growth, and read throughput.
- API design — endpoints, request/response shapes, and any important protocol choices.
- Data model — tables or collections, primary keys, indexes, and how you handle the many-to-many relationship between photos and albums.
- High-level architecture — how the components fit together from upload to delivery.
- Two or more deep dives — pick the areas with the most interesting trade-offs, for example: durability guarantees, consistency after writes, media processing pipeline, storage cost at scale, or CDN caching strategy.
Explicit constraints
- Losing a user's photo is unacceptable. Durability is the highest priority.
- Library and album listings should be fast: target p99 under 200 ms.
- After a user uploads a photo or adds it to an album, that user must see the change immediately (read-after-write consistency for the owner).
- Photo content is private by default. Sharing, search, and face recognition are out of scope, but briefly note how you would extend toward them.
Hints
Hint 1
Blob bytes and metadata have very different access patterns and scale characteristics — split them into different storage systems from the start, and think about what each one is optimized for.
Hint 2
Almost every query is scoped to a single user (list my photos, list my album). That constraint should directly inform how you partition or shard the metadata store.
Hint 3
A pre-signed URL pattern lets clients upload directly to object storage, keeping large binary data off your application servers entirely — think through what the client and server each do in that flow, and what happens if the client never finishes the upload.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale
Functional scope (stated assumptions)
- Upload photos up to 50 MB; support JPEG, HEIC, PNG.
- Serve originals and at least two derivative sizes (thumbnail ~256 px, medium ~1080 px).
- Metadata per photo: dimensions, file size, capture time, EXIF (camera, GPS).
- Albums: create, rename, delete, list. One photo can belong to many albums.
- Photo delete is a hard delete from the library and all albums.
- Listing is paginated, newest first. Out of scope: sharing, search, ML features.
Back-of-envelope estimates
| Metric | Assumption | Result |
|---|---|---|
| Total / daily active users | 500 M / 50 M | — |
| Uploads | 2 per DAU per day | ~1,200/s avg, ~5,000/s peak |
| Average original size | 3 MB | ~300 TB/day → ~110 PB/year |
| Derivatives (thumb + medium) | ~10% of original | +11 PB/year |
| Metadata | ~1 KB/photo | ~100 GB/day |
| Reads | ~20 views per upload, mostly thumbnails | ~25,000/s avg |
Two things follow: blob bytes dominate and belong in object storage behind a CDN; metadata fits in a relational or wide-column store sharded by user.
2. API Design
All endpoints require authentication. IDs are opaque time-sortable strings (ULID or Snowflake).
# Photo lifecycle
POST /v1/uploads # request a presigned URL
body: { filename, content_type, size_bytes, sha256 }
-> { photo_id, upload_url, expires_at }
POST /v1/photos/{photo_id}/complete # signal upload finished -> 202
GET /v1/photos/{photo_id} # metadata + signed CDN URLs per size
GET /v1/photos?cursor=&limit=50 # user library, newest first
DELETE /v1/photos/{photo_id}
# Albums
POST /v1/albums body: { name }
PATCH /v1/albums/{album_id} body: { name?, cover_photo_id? }
DELETE /v1/albums/{album_id}
GET /v1/albums?cursor=
# Album membership
PUT /v1/albums/{album_id}/photos body: { photo_ids: [...] } # batch add
DELETE /v1/albums/{album_id}/photos body: { photo_ids: [...] }
GET /v1/albums/{album_id}/photos?cursor=&limit=50
Key design choices:
- Presigned upload URLs. The client PUT goes directly to object storage. The API tier never proxies binary data, which caps memory and bandwidth requirements on application servers.
- Cursor pagination, not offset. The cursor encodes
(sort_key, photo_id), so results remain stable even as new photos are inserted. - Batch membership operations. Users routinely select hundreds of photos at once; a single round trip beats N individual calls.
- Idempotency keys on upload initiation protect against duplicate photo rows if the client retries.
3. Data Model
Shard the metadata store by user_id. Nearly every query is scoped to one user, so library and album listings touch a single shard, enabling single-shard transactions. Good options are Vitess (sharded MySQL), CockroachDB, or DynamoDB.
-- Core photo record
photos
(user_id, photo_id) PK
storage_key, content_type, size_bytes
width, height, sha256
taken_at, uploaded_at, exif_json
status ENUM(PENDING, READY, DELETED)
INDEX (user_id, taken_at DESC, photo_id) -- library listing
-- Album header
albums
(user_id, album_id) PK
name, cover_photo_id, photo_count
created_at, updated_at
-- Many-to-many: ordered by insertion time
album_photos
(user_id, album_id, added_at, photo_id) PK
UNIQUE (user_id, album_id, photo_id) -- deduplicate
-- Reverse index: "which albums contain this photo?"
photo_albums
(user_id, photo_id, album_id) PK -- used during delete
Using user_id as the leftmost key component co-locates every row for a user on one shard, making "add photo to album + increment photo_count" a single local transaction. The reverse index photo_albums makes photo deletion efficient: instead of scanning every album, fetch the album list in O(albums containing that photo) and remove each entry.
4. High-Level Architecture
Client
│ metadata requests │ PUT bytes via presigned URL
v v
API Gateway ──> Photo/Album Service Object Storage (S3/GCS, multi-AZ)
(auth, rate limit) │ │ event notification
│ v
│ Message Queue
│ │
v v
Metadata DB Media Workers
(sharded by (validate checksum,
user_id) extract EXIF,
+ Redis cache generate derivatives,
mark row READY)
│
v
Object Storage
(derivatives)
│
CDN <─┘
(signed URL reads)
Upload flow:
- Client requests an upload slot; service writes a
PENDINGrow and returns a presigned URL. - Client PUTs bytes directly to object storage under
originals/{user_id}/{photo_id}. - A storage event (or the
/completecall) enqueues a processing job. - A worker verifies the checksum, extracts EXIF, generates thumbnail and medium derivatives (WebP/AVIF), and marks the row
READY. - The client shows a local preview instantly; the server-confirmed version appears once the row turns
READY.
Read flow: The service returns metadata plus short-lived signed CDN URLs. Thumbnail keys are immutable (keyed by photo_id), so they cache indefinitely at the edge.
5. Deep Dives
Durability and reliability
Object storage provides multi-AZ replication by default. Add cross-region replication for originals, plus versioning with a 30-day soft-delete window before permanent removal. The metadata DB uses a synchronous replica with point-in-time recovery.
Workers must be idempotent because the queue delivers at-least-once. Derivative keys are deterministic (thumb/{photo_id}.webp), so reprocessing is safe. A daily reconciliation job scans for PENDING rows older than 24 hours and for objects with no matching metadata row, cleaning up abandoned uploads and orphans.
Consistency for the uploading user
Route the photo owner's read requests to the shard primary, or use session-pinned routing. This gives read-after-write without requiring synchronous replication to every replica before the response is returned. Other users tolerate eventual consistency (their latency budget is different).
Photo deletion
Mark the row DELETED immediately (hides the photo from all listings at once). Use the photo_albums reverse index to remove membership rows transactionally on the same shard. Delete the cover reference on any albums pointing at this photo. Schedule blob deletion and CDN invalidation asynchronously; issuing a purge synchronously on every delete adds latency and is not necessary for correctness, since a signed URL for a deleted photo will simply return 403.
Storage cost at scale
At 110 PB/year, tiering matters. Originals not accessed in 90 days move to infrequent-access storage (roughly 40% cost reduction); cold archives move to Glacier-class storage after 365 days (another 70% reduction on top of that). Derivatives are cheaper to regenerate than to store forever, so they can be evicted and re-created on cache miss for very old photos rather than retained indefinitely.
Common Mistakes to Avoid
- Storing blobs in the database. Even with BLOB columns, the DB becomes the bottleneck for large binary data.
- Offset-based pagination. Inserting a photo shifts every subsequent offset, causing duplicates or gaps across pages.
- Scanning albums on photo delete. Without the reverse index, deleting one photo requires reading every album the user owns.
- Synchronous thumbnail generation in the upload request path. This adds seconds of latency and ties up API threads; always do it asynchronously.
- Ignoring the PENDING → READY gap. If the client shows "upload complete" before the worker finishes, users will see a broken thumbnail. Either poll for status or push a notification when processing is done.