Design a Photo-Sharing Platform with Social Feed and Discovery
System DesignModel answerLast updated
Build a scalable backend for uploading images, following users, generating personalized feeds, and suggesting new connections to follow.
Problem
You need to architect the backend for a photo-sharing social platform. Users upload images with text descriptions, build a network by following others, browse a personalized stream showing recent content from their connections, and receive suggestions for new accounts to follow.
Core Capabilities
What Users Can Do
- Upload images along with descriptive text
- Build their network by following and unfollowing other accounts
- Browse a personalized stream displaying recent content from accounts they follow
- Receive algorithmically generated suggestions for new accounts to follow
Performance Targets
- Availability: Prioritize system uptime for browsing and viewing; temporary inconsistencies are acceptable
- Speed: Stream retrieval should complete in under 200ms at the 99th percentile; uploads should feel instant to users
- Scale: The system must gracefully handle accounts with millions of connections without degrading performance for others
Traffic Characteristics
- Active users daily: 500 million people
- Image uploads daily: 100 million photos (~1,150/sec average, peaking at ~3,000/sec)
- Stream requests daily: 5 billion queries (~58,000/sec average, peaking at ~150,000/sec)
- Typical image size: 2 MB including metadata
Your Task
Design a complete system architecture covering:
- Service interfaces: Key endpoints for media upload, network building, stream retrieval, and discovery
- Storage strategy: How you'll store content metadata, network connections, and media files; justify database technology choices
- Stream generation: Explain your approach to building personalized feeds, comparing different strategies and addressing the challenge of high-follower accounts
- Discovery system: Architecture for generating follow suggestions using network topology and user behavior
- Performance optimization: Caching layers, data partitioning, and handling uneven load distribution
Focus on concrete technical decisions with quantitative reasoning where applicable.
Hints
Hint 1
Calculate storage and throughput numbers to understand system pressure
Hint 2
Consider whether feeds should be pre-built or assembled on-demand, and what breaks at the extremes
Hint 3
Think about how to handle accounts with vastly different follower counts using different strategies
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Photo-Sharing Platform Architecture
1. Requirement Analysis and Scale Estimation
Start by converting business requirements into concrete technical constraints:
Storage pressure:
- 100M photos/day × 2 MB = 200 TB daily ingestion, roughly 73 PB annually before accounting for redundancy
- This volume demands object storage rather than database blobs
Write throughput:
- Peak upload rate of 3,000/sec is manageable for metadata writes
- If each author has 200 followers on average: 100M posts × 200 = 20 billion feed updates daily (~230K/sec)
- High-follower accounts create amplification: one post from a 50M-follower account triggers 50M writes
Read throughput:
- 150K requests/sec at peak with sub-200ms latency requirement
- Cannot perform live graph queries; feeds need precomputation or aggressive caching
Memory for caching:
- 500M users × 500 cached post identifiers × 16 bytes ≈ 4 TB total
- Feasible with distributed cache clusters
Scope boundaries: Focus on photo posts, social graph, feeds, and recommendations. Exclude ephemeral content, messaging, search, and comments.
2. API Surface
POST /v1/media/prepare -> {media_id, upload_url}
POST /v1/posts {media_ids, caption} -> {post_id}
DELETE /v1/posts/{post_id}
PUT /v1/follows/{user_id} # establish connection
DELETE /v1/follows/{user_id} # remove connection
GET /v1/timeline?cursor=&limit=20 -> {posts[], next_cursor}
GET /v1/suggestions?limit=20 -> {users[], scores}
Key decisions:
- Presigned upload URLs let clients write directly to object storage, keeping media bytes off application servers
- Cursor-based pagination using
(timestamp, post_id)tuples handles shifting feed state better than numeric offsets
3. Storage Architecture
| Data Type | Technology | Rationale |
|---|---|---|
| User profiles | Partitioned PostgreSQL | Small records, need strong consistency for authentication and settings |
| Post metadata | Cassandra | Partition by author_id, cluster by timestamp DESC; optimized for author-timeline queries |
| Social graph | Bidirectional graph store | Maintain both following(user_id → list) and followers(user_id → list) with denormalized counts |
| Media files | S3 + CloudFront CDN | Immutable objects with multiple resolution variants generated asynchronously |
| Feed cache | Redis sorted sets | timeline:{user_id} maps to scored post IDs, capped at ~500 entries per user |
| Suggestions | Wide-column store | Precomputed user_id → [(candidate_id, score)] mappings |
Identifier strategy: Use 64-bit time-ordered IDs (timestamp + shard + sequence) that naturally sort chronologically.
Technology justification: Wide-column stores excel at single-partition range scans, matching both post-timeline and social-graph access patterns.
4. Feed Generation Strategy
Write Flow
- Client uploads media to object storage via presigned URL
- Client calls post-creation endpoint
- Service writes post metadata and publishes event to message queue
- Asynchronous workers generate image variants (thumbnails, optimized sizes)
- Feed-distribution workers propagate post to follower timelines
Strategy Comparison
Pre-built (push) approach:
- Write cost: O(follower count)
- Read cost: O(1) - single cache lookup
- Advantage: Extremely fast reads suitable for read-heavy workload
- Problem: Accounts with millions of followers cause write amplification
On-demand (pull) approach:
- Write cost: O(1)
- Read cost: O(following count) - query multiple author timelines and merge
- Advantage: No write amplification
- Problem: Slow for users following hundreds of accounts
Hybrid Implementation
For typical accounts (< 100K followers):
- Use push strategy
- Workers iterate through
followers(author)and insert into eachtimeline:{follower} - Trim each timeline to maintain only 500 most recent entries
- Skip dormant accounts (no activity in 30+ days) to reduce wasted writes
For high-follower accounts:
- Do not push to follower timelines
- Maintain small, heavily replicated
recent_posts:{author_id}caches - These are fetched and merged at read time
Read Flow
- Retrieve
timeline:{user}from cache (contains pushed posts) - Fetch user's list of high-follower accounts they follow (typically < 50, cached)
- Retrieve
recent_posts:for each of those accounts - Perform k-way merge by timestamp
- Batch-fetch post metadata using multi-get
- Filter deleted posts, blocked users, and privacy changes
- Return page with continuation cursor
Fallback: On cache miss, execute pull-based logic: query recent posts from all followed accounts, merge, and backfill the cache.
Network updates:
- New follow: Asynchronously insert followee's recent ~20 posts into follower's timeline
- Unfollow: Filter at read time; lazy cleanup prevents race conditions
5. Discovery Engine
Batch Processing (Daily)
Run large-scale graph analysis on historical data:
Candidate generation:
- Network proximity: Second-degree connections weighted by mutual-follow count; limit high-degree vertices to prevent celebrity contamination
- Address book: Match uploaded contact lists to existing accounts
- Behavioral similarity: Users who engage with similar content
- Embedding space: Train graph neural network on follow and engagement graphs; find nearest neighbors in learned embedding space
Ranking model:
- Predict probability of (follow AND not-dismiss)
- Features: mutual connection count, engagement overlap, geographic proximity, account age, content-creator signals
- Store top ~200 candidates per user with scores
Real-time Processing
Stream processor on follow/engagement events:
- When user A follows user B, immediately inject B's top connections as candidates for A
- Provides responsive suggestions right after onboarding or network expansion
- Prevents waiting for next batch cycle
Serving path: Retrieve precomputed list, filter already-followed and blocked accounts, apply diversity reranking, return results. No live graph traversals.
6. Caching and Scalability Patterns
Cache Layers
- CDN: Serves 95%+ of media requests with immutable URLs and long TTLs
- Distributed cache (Redis): Holds timelines and recent-post lists
- Application cache (Memcached): Post metadata and profile data
- Process-local cache: Hottest celebrity content
Partitioning Strategy
- Hash-partition all data by
user_idusing consistent hashing - Posts partitioned by
author_idto colocate author content - Social graph partitioned bidirectionally for efficient lookups in both directions
Hot-key Mitigation
- Viral content: Replicate hot post metadata across multiple cache keys (
post:{id}#0throughpost:{id}#N), read from random replica - Request coalescing: Single-flight pattern prevents cache stampedes
- Celebrity timelines: Maintain high replication factor with geographic distribution
Resilience Patterns
- Fan-out uses partitioned message queues with autoscaling consumers; backlog causes latency, not failures
- Timeline reads degrade gracefully: if celebrity-cache fetch fails, omit that content rather than failing entire request
- Circuit breakers around recommendation service prevent cascade failures
Monitoring: Track feed-generation lag, cache hit rates, p99 latencies per endpoint, and follower-count distribution to detect skew.
Common Pitfalls
- Using offset pagination instead of cursors causes inconsistent results as feed shifts
- Forgetting to filter deleted/private content at read time after caching post IDs
- Not accounting for write amplification from high-follower accounts
- Synchronous feed fan-out blocking post creation
- Failing to cap second-degree connections when generating candidates, causing celebrity accounts to dominate suggestions