Build a photo-sharing platform architecture
System DesignModel answerLast updated
Architect a distributed system for uploading photos, following users, and serving personalized image feeds at scale with low latency.
You're tasked with architecting a photo-sharing platform that lets users post images, build a following, and browse a personalized stream of content from accounts they follow.
Core Capabilities
Your system must support:
- Photo publishing: Users upload images with text descriptions
- Social graph: Users establish and break follow relationships
- Personalized stream: Users see recent images from accounts they follow
- User galleries: Each profile displays all images posted by that account
Performance & Scale Targets
- Availability: Individual service failures shouldn't bring down the platform
- Throughput: Support millions of simultaneous users with high request volumes
- Speed: Photo uploads must be reliable; stream loads should complete in under 200ms
- Data integrity: User profiles require strong consistency; streams can tolerate brief staleness
Design Scope
Provide:
- Architecture overview describing major components and their interactions
- Core API contracts for the main features
- Database choices and schema structure (explain SQL vs. NoSQL trade-offs)
- Image storage and content delivery strategy
Scale Parameters
Work with these assumptions:
- 100 million users active daily
- 5 million photos published each day
- Workload heavily skewed toward reads over writes
Focus on the stream and upload flows. Reactions, nested replies, ephemeral content, and direct messaging are out of scope.
Hints
Hint 1
Start with capacity math—calculate average and peak requests per second for uploads, stream views, and image fetches to drive storage and caching decisions
Hint 2
The read-to-write ratio matters: decide whether to compute streams at write time (fan-out on write) or read time (fan-out on read), and consider a hybrid for accounts with massive followings
Hint 3
Separate binary data from metadata—store image files in object storage with CDN delivery, and use different databases for structured data like posts, relationships, and precomputed streams
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Scope and Capacity Planning
Begin by confirming what's in and out of scope. The interviewer wants upload, follow relationships, personalized stream, and profile gallery. Reactions, comments, and messaging are deferred unless explicitly added.
Next, translate scale assumptions into concrete numbers to guide architecture decisions.
Request rates
- Photo uploads: 5M per day ≈ 58/sec average, peaking around 290/sec (assume 5× multiplier for peak)
- Stream fetches: estimate 10 opens per user daily = 1B per day ≈ 11,600/sec average, about 58,000/sec peak
- Image file requests: roughly 20 images per stream page → 1.16M requests/sec peak
- This yields roughly a 200:1 read-to-write ratio, which strongly favors read optimization
Storage requirements
- Each photo with original plus resized variants (thumbnail, medium, high-res): ~3 MB total
- Daily image storage: 5M × 3 MB = 15 TB/day or 5.5 PB annually—blob storage is mandatory
- Post metadata (caption, timestamps, dimensions): ~500 bytes per post = 2.5 GB/day, trivial compared to image bytes
- Stream precomputation: average 200 followers per user × 5M posts = 1B stream writes daily (~12K/sec), manageable for write-time fan-out
These calculations immediately tell you: images go to object storage + CDN, not databases; optimize for reads; and stream precomputation is viable.
API Surface
POST /v1/uploads/signed-url → { uploadUrl, mediaId }
POST /v1/posts { mediaId, caption } → { postId }
GET /v1/users/{userId}/posts?cursor=&limit=20
GET /v1/stream?cursor=&limit=20
POST /v1/relationships/{userId}
DELETE /v1/relationships/{userId}
GET /v1/users/{userId}/followers?cursor=
GET /v1/users/{userId}/following?cursor=
Key design choices:
- Presigned upload URLs: Clients upload directly to object storage, avoiding API server bandwidth and latency
- Cursor-based pagination: Use the last seen
postIdor timestamp as cursor—offset pagination breaks when new content arrives - Idempotency: Accept idempotency keys on
POST /poststo make retries safe
Data Modeling
Separate binary assets from structured metadata, and choose storage engines based on access patterns.
| Data Type | Storage | Rationale |
|---|---|---|
| Image files | Object store (S3) + CDN | Cheap, durable (99.999999999%), unlimited scale |
| User accounts | Sharded relational DB | Small dataset, needs ACID, unique constraints on usernames |
| Posts | Wide-column store (Cassandra) or sharded SQL by user_id | Profile queries hit one partition, sorted by time |
| Follow graph | Wide-column store with dual tables | Fast bidirectional lookups |
| Streams | Redis (hot tier) + Cassandra (cold tier) | Precomputed, append-heavy, evictable |
Schema examples:
users(user_id PK, username UNIQUE, display_name, bio, avatar_url, created_at)
posts(user_id PARTITION, post_id CLUSTERING DESC, caption,
media_key, dimensions, created_at)
following(follower_id PK, followee_id CK, created_at)
followers(followee_id PK, follower_id CK, created_at)
user_stream(user_id PK, post_id CK DESC, author_id) -- capped at ~500 entries
Use time-ordered IDs (Snowflake-style: timestamp + machine ID + sequence) for post_id so sorting by ID naturally gives chronological order without additional timestamp columns.
Consistency model: Profile fetches use quorum reads or SQL primary for strong consistency. Streams accept eventual consistency—posts may appear seconds late, which users tolerate.
Architecture Overview
Client → DNS/GeoDNS → API Gateway (auth, rate limiting)
│
├─ Upload Service → presigned URLs → S3
│ └─ S3 event → Image Processor workers → variants → S3
│
├─ Post Service → Posts DB → publish event → Kafka
│
├─ Graph Service → Follow DB (+ cache layer)
│
├─ Fan-out Workers (Kafka consumers) → Stream Cache (Redis) / Stream DB
│
└─ Stream Service → Stream Cache → hydrate from Post cache → response
CDN ← S3 (all image reads go through edge caches)
All services are stateless, horizontally scaled behind load balancers, deployed across multiple availability zones. Datastores use replication (RF=3 for Cassandra, replicas + automatic failover for SQL).
Deep Dive: Stream Generation Strategy
Push model (fan-out on write):
When a post is created, write its post_id into every follower's stream. Reads become a single sorted set fetch from Redis—fast and predictable, easily meeting the 200ms target. The cost is write amplification.
Pull model (fan-out on read): At stream fetch time, query recent posts from each followed account and merge-sort them. Cheap writes, but reads become expensive when users follow thousands of accounts.
Hybrid approach (recommended):
- Push for normal users: Fan out to all followers below a threshold (e.g., 100K followers)
- Pull for high-profile accounts: Don't fan out for accounts with massive followings
- Merge at read time: Combine precomputed stream with recent posts from high-profile accounts the user follows (these are cached hot and shared across many users)
- Active users only: Only fan out to users active in the last 30 days; rebuild stale streams lazily on login
This balances write costs against read latency and handles the celebrity problem without fan-out explosion.
Deep Dive: Upload and Processing Pipeline
- Client requests signed URL from Upload Service
- Client uploads directly to S3 using multipart upload (resumable)
- S3 event triggers Image Processor workers that:
- Strip privacy-sensitive metadata (EXIF GPS, device info)
- Scan for policy violations
- Generate multiple format variants (WebP, AVIF) and sizes (thumbnail, 640px, 1080px)
- Write variants to S3 with content-addressed keys
- Client calls
POST /postswithmediaIdand caption - Post Service writes metadata to Posts DB and publishes event to Kafka
- Fan-out Workers consume events and asynchronously update streams
This pipeline is reliable because S3 supports resumable uploads, Kafka provides durable event delivery, and upload acknowledgment happens before expensive fan-out.
Deep Dive: Stream Read Path
- Fetch post IDs from Redis using
ZREVRANGE user_stream:{user_id}with cursor and limit - Merge in recent posts from any high-profile accounts the user follows (cached hot)
- Batch-hydrate post metadata from Post cache (Redis/Memcached in front of Posts DB)
- Return JSON with CDN URLs for images
Target server-side latency: 20–50ms. Keep only ~500 most recent entries per stream; if a user scrolls past that, fall back to pull model.
Deep Dive: Image Delivery
- CDN everywhere: Every image request goes through edge caches with long TTLs (1 year+)
- Content addressing: Image keys never change, making long caching safe
- Responsive variants: Clients request the size matching their screen, reducing bandwidth
- Cache hit rate >95% keeps origin load minimal
- Lifecycle policies: Move old originals to infrequent-access tiers after 90 days
Sharding and Caching Strategy
- Shard by
user_id: A user's posts and stream live on the same shard, minimizing cross-shard queries - Consistent hashing for Redis clusters to distribute load evenly
- Replicate hot keys: Celebrity posts get copied to multiple cache nodes to avoid hotspots
- Cache-aside pattern: Check cache, miss → fetch from DB → populate cache
Trade-offs and Discussion Points
- Push vs. pull for streams: Push trades storage and write amplification for read speed—justified by 200:1 read:write ratio
- Eventual consistency in streams: Posts may appear seconds late; users accept this, and it enables async fan-out without blocking uploads
- NoSQL for posts and graph: Horizontal scale and predictable single-partition queries, sacrificing joins (which we don't need on the hot path)
- Unfollow handling: Filter unfollowed authors at read time rather than synchronously purging all streams—simpler and faster
- Active user filtering: Writing to inactive users wastes resources; lazy rebuilds save ~70% of fan-out writes
What Strong Candidates Demonstrate
- Quantitative reasoning: Derive request rates and storage needs from scale assumptions, then use those numbers to justify architectural choices
- Access pattern awareness: Recognize read-heavy workloads and choose strategies (caching, precomputation) accordingly
- Practical trade-offs: Explain why eventual consistency is acceptable for streams but not profiles; why push works for normal users but not celebrities
- Operational concerns: Discuss monitoring (stream lag, cache hit rates), failure modes (what happens if Redis dies?), and deployment strategies (blue-green for stateless services, rolling upgrades for datastores)
- Follow-up readiness: Be prepared to discuss ranking algorithms, spam prevention, image moderation, or geographic distribution