Photo Library Backend: Safe Uploads, Dedup and Database Growth
System DesignModel answerLast updated
Design the storage backend for a photo-sharing service, covering upload consistency, instant visibility, duplicate prevention, and how to justify and scale the metadata database.
Design the backend for a photo library service. Users upload pictures, group them into albums, and browse them from any device. The focus is on infrastructure (storage, consistency, data modeling, scaling), not on UI or features such as editing or face search.
Expect the requirements to change mid-discussion. Revise your design when they do, rather than defending your first version. No traffic numbers are provided, so state your own assumptions and size the system from them.
Questions you may want to ask up front: Can a photo be in several albums? Does deleting an album delete its photos? Which derived sizes are needed and how quickly? Are albums private or shareable? Photos only, or video too? Is deletion permanent or recoverable?
Part 1: Requirements, API, data model. Separate functional from non-functional requirements and prioritize them. Propose an API for upload, album management and paginated browsing. Define a schema for users, photos, albums and the photo-to-album many-to-many link. Sketch the components and the request flow for upload and for viewing an album.
Part 2: The upload path.
- Image bytes go to blob storage and a record goes to the metadata database. How do you keep the two consistent, including failures and cleanup?
- Right after uploading, the user expects to see the photo immediately, even though thumbnail generation and other processing lag behind. How do you handle that?
Part 3: Duplicates. How do you stop the same user from uploading the same photo more than once? Consider exact-file versus visually similar duplicates, rejecting versus mapping to the existing photo, and two concurrent uploads of the same file.
Part 4: The database. You choose Postgres for metadata. Justify it against this schema's access patterns. At what scale does a relational database become the bottleneck, which signals tell you, and what is your staged scaling path, including a shard key and its costs?
Hints
Hint 1
Never let a metadata row point at bytes that do not exist: give each photo a state (for example pending, uploaded, ready) and only expose it once the bytes are confirmed. Also plan a sweeper for orphaned bytes and stale pending rows.
Hint 2
For instant visibility, serve the uploader from the original image (or a client-side local preview) and route that user's reads to the primary or by a session token until replicas catch up; swap in thumbnails when the async job finishes.
Hint 3
For dedup, combine an idempotency key per upload attempt with a content hash (such as SHA-256) under a unique constraint on (user_id, content_hash), so concurrent duplicates collide in the database rather than in application code.
Hint 4
For scaling, look at the numbers: write rate, working set versus RAM, replica lag and connection counts. Move through indexing and caching, then read replicas, then partitioning, then sharding by user_id, noting that cross-user features become harder.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Say these out loud and size from them: 50M users, 10M daily active, 5 uploads per active user per day gives about 50M uploads/day, roughly 600/s average and about 2,000/s at peak. Average original is 3 MB, so about 150 TB/day raw and tens of PB per year. Metadata is about 1 KB per photo, so about 50 GB/day. Reads outnumber writes by roughly 50:1. Photos are private by default, albums can contain many photos, and a photo can sit in many albums without being copied.
Part 1: Requirements, API, schema
Functional (must have): upload, create/rename/delete albums, add/remove photos in albums, list albums, list photos in an album with pagination, view and download, delete photos. Non-functional: durability of bytes (effectively never lose a photo), high availability for reads, upload latency dominated by network, strong consistency for a user's own writes, eventual consistency for derived data, cost efficiency (storage dominates).
API (REST, cursor pagination):
POST /uploadsreturns an upload ID and a pre-signed URL (or multipart URLs for large files). Takes a client-generated idempotency key and the content hash.POST /uploads/{id}/completefinalizes the upload.GET /albums,POST /albums,PUT /albums/{id},DELETE /albums/{id}PUT /albums/{id}/photos/{photoId},DELETEthe sameGET /albums/{id}/photos?cursor=...&limit=50GET /photos/{id}returns metadata and signed URLs for the available renditions.
Schema:
users(id, ...)photos(id, user_id, content_hash, blob_key, state, size, mime, width, height, taken_at, created_at), unique(user_id, content_hash)albums(id, user_id, name, created_at)album_photos(album_id, photo_id, added_at), primary key(album_id, photo_id), index(album_id, added_at DESC, photo_id)for keyset paginationrenditions(photo_id, kind, blob_key, state)
Components: clients, API gateway/auth, an upload service that issues signed URLs, blob storage with a CDN in front, metadata DB with replicas, a queue plus workers for thumbnails, and a cleanup sweeper. Clients upload bytes directly to blob storage so the API tier never proxies large files.
Part 2: Upload path
Consistency between blob store and DB. There is no distributed transaction across the two, so order the writes and use states.
POST /uploadsinserts aphotosrow in statependingwith a deterministicblob_key, and returns a signed URL.- The client uploads bytes to that key.
- On
complete(or via a blob-storage event notification, which is more robust against clients that disappear), the service verifies the object exists and its size/checksum matches, then flips the row touploadedand enqueues processing.
Invariant: readers only see rows in uploaded or ready, so a visible photo always has bytes. The opposite failure (bytes without a row) is impossible because the row is written first. What can occur is a pending row with no bytes, or with partial bytes. A sweeper deletes pending rows older than, say, 24 hours and removes their objects; a blob-store lifecycle rule aborts incomplete multipart uploads. A periodic reconciliation job lists blobs and compares to rows to catch any leaks.
Instant visibility. Processing is asynchronous: a queue triggers workers that produce thumbnails and previews and mark renditions ready. Meanwhile:
- The client shows a local preview of the file it just picked, and the API returns a signed URL for the original so the photo renders at once.
- Read-your-writes: after an upload, route that user's metadata reads to the primary for a short window, or pass a "minimum version/LSN" token that replicas must have reached. This avoids a photo missing from the list because of replica lag.
- The photo detail response lists only renditions that are ready; clients fall back to the original (downscaled by the CDN or client) and refresh when a "ready" event or poll arrives.
Workers are idempotent (output key derived from photo ID and kind), so retries are safe. Use a dead-letter queue for poison images.
Part 3: Duplicates
Distinguish two problems.
Retries (same request twice): the client sends an idempotency key with POST /uploads. The server stores it and returns the same upload on repeats.
Same content: the client computes SHA-256 before upload and sends it. The server checks (user_id, content_hash). If it exists in a finished state, it returns the existing photo ID and skips the upload; this also supports "add the existing photo to another album" with no new bytes. The server cannot trust the client hash, so on completion it recomputes or verifies the hash from the blob (or uses a blob-store checksum).
Concurrency: the unique constraint on (user_id, content_hash) is the enforcement point. Two simultaneous inserts: one wins, the other gets a conflict and returns the winner's photo ID, deleting its own stray blob. Never rely on check-then-insert in application code.
Near-duplicates (resized or re-encoded) need perceptual hashing (pHash/dHash) and a similarity lookup. It is probabilistic, so flag these for the user rather than rejecting them. State that exact-match dedup is the default and perceptual is an optional extension.
Cross-user dedup saves storage but leaks information (someone can probe whether a file exists) and complicates deletion, so per-user dedup is the safer default.
Part 4: Database choice and scaling
Why Postgres: the data is relational (users, albums, photos, many-to-many), needs transactions (move a photo between albums, delete an album atomically), unique constraints (dedup), and rich secondary indexes for keyset pagination. Metadata is small and the workload is modest compared to blob traffic, so one well-tuned instance goes far. Mature tooling, replicas and partitioning are available.
Bottleneck signals and the resource behind each:
- Working set exceeds RAM and the cache hit ratio drops: memory/IO.
- Write throughput or WAL volume saturates disk: IO (say, sustained thousands of writes/s).
- Replica lag grows or read QPS saturates CPU: read capacity.
- Connection exhaustion: fix with a pooler first.
- Table/index size reaching hundreds of GB to TB makes vacuum, migrations and backups painful.
Staged path:
- Tune queries and indexes, add a connection pooler, cache hot reads (album lists, signed URL metadata).
- Add read replicas, with read-your-writes handled as above.
- Partition large tables (
album_photos,photos) by time or hash for maintenance and index locality. - Shard by
user_id(hash or consistent hashing with a directory service). Almost every query is scoped to one user, so nearly all queries and transactions stay on one shard, and albums live with their owner.
Costs of sharding: cross-shard queries (shared albums across users, global analytics) need fan-out or a separate denormalized/search store; resharding requires data migration (mitigate with many logical shards mapped to few physical hosts); hot users (very large libraries) can skew shards; operational complexity rises. Sharing could be handled by a separate shared-album table keyed by album, or by replicating references.
Common mistakes
- Proxying uploads through app servers.
- Writing the DB row after the blob with no cleanup, leaving orphans.
- Doing dedup by check-then-insert without a unique constraint.
- Jumping to sharding or NoSQL before showing the numbers.
- Defending the first design when requirements change instead of adapting it.