📌Problem Statement
Design a photo-sharing social network like Instagram.
📌Requirements
Functional
Non-Functional
Capacity Estimation
📌High-Level Architecture
System Architecture
Live
Mobile/Web App
Load Balancer
Nginx
API Gateway
User Service
Post Service
Feed Service
User DB
Postgres
Post DB + S3
Feed Cache
Redis
CDN
CloudFront
⚡ High Availability🔄 Auto-scaling🛡️ Fault Tolerant
📌Component Design
1. Photo Upload Flow
public class PhotoUploadService { public UploadResponse upload(MultipartFile file, String userId) { String photoId = generateId(); String s3Key = userId + "/" + photoId; s3Client.putObject(BUCKET, s3Key, file.getInputStream()); List<String> thumbnails = imageProcessor.generateThumbnails( file, Arrays.asList(150, 320, 640, 1080) ); Post post = new Post(photoId, userId, s3Key, thumbnails); postRepository.save(post); fanoutService.publishToFollowers(userId, post); return new UploadResponse(post.getId(), getCdnUrl(s3Key)); }}2. News Feed Generation
Two approaches:
Push Model (Fan-out on Write)
Pull Model (Fan-out on Read)
Hybrid Approach (Best)
public class FeedService { private static final int CELEBRITY_THRESHOLD = 10000; public List<Post> getFeed(String userId, int limit) { List<Post> feed = new ArrayList<>(); feed.addAll(feedCache.get(userId)); List<String> celebrities = followService.getCelebritiesFollowed(userId); for (String celeb : celebrities) { feed.addAll(postService.getRecentPosts(celeb, 10)); } feed.sort(Comparator.comparing(Post::getCreatedAt).reversed()); return feed.stream().limit(limit).collect(Collectors.toList()); } public void fanout(String userId, Post post) { int followerCount = followService.getFollowerCount(userId); if (followerCount < CELEBRITY_THRESHOLD) { List<String> followers = followService.getFollowers(userId); for (String followerId : followers) { feedCache.prepend(followerId, post); } } }}3. Database Design
Users Table
CREATE TABLE users ( user_id BIGINT PRIMARY KEY, username VARCHAR(50) UNIQUE, email VARCHAR(100), profile_pic_url TEXT, bio TEXT, created_at TIMESTAMP);Posts Table (Cassandra for scale)
CREATE TABLE posts ( post_id UUID, user_id BIGINT, media_url TEXT, caption TEXT, location TEXT, created_at TIMESTAMP, PRIMARY KEY (user_id, created_at)) WITH CLUSTERING ORDER BY (created_at DESC);Follows Table
CREATE TABLE follows ( follower_id BIGINT, followee_id BIGINT, created_at TIMESTAMP, PRIMARY KEY (follower_id, followee_id));4. CDN and Image Serving
📌Scaling Strategies
Database Sharding
Caching Layers
Message Queue
📌Interview Questions
Q: How to handle celebrity posts? A: Pull model for celebrities, don't fan out
Q: How to rank feed? A: ML model considering recency, engagement, user interests
Q: How to handle stories? A: Separate service with TTL, store in Redis with 24h expiry
This is asked at Facebook, Google, and Instagram interviews.