Design a Feed App (Like Twitter)

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-05-21

Problem Statement

Design a feed-based social media platform similar to Twitter (X), where users can:


•Post short text updates (tweets/posts)
•Follow other users
•See a real-time feed composed of posts from the people they follow
•Like, comment, and retweet/repost content


The system should support millions of active users, low-latency feed generation, and scalable content storage and retrieval.


🎯 Core Requirements


Functional Requirements


User Management

•Users can register, login, and manage their profile.
•Users can follow or unfollow other users.

Post Management

•Users can create text-based posts (tweets).
•Each post has metadata like author, timestamp, and engagement metrics.
•Users can like, comment, or repost.

Feed Generation

•Each user sees a personalized feed showing posts from people they follow.
•Feed should show the most recent and relevant posts.
•Support pagination and infinite scroll.

Real-Time Updates

•When someone a user follows posts a new tweet, it should appear in their feed in near real-time.

Trending Topics (Optional)

•Identify and display trending hashtags or topics.

Search

•Search posts, hashtags, or users.

Notifications (Optional)

•Notify users when someone likes or comments on their post.


Non-Functional Requirements


Attribute with Target


Availability


99.9%


Latency


Feed generation < 200ms


Scalability


100M+ users, millions of posts/day


Consistency


Eventual consistency acceptable for feed updates


Durability


No loss of posts or user relationships


Security


Authentication & authorization for all actions


🧩 Core Components


Component with Description


User Service

Manages user accounts, profiles, and relationships (follow/unfollow).


Post Service

Handles creation, storage, and retrieval of posts (tweets).


Feed Service

Generates and serves personalized feeds for users.


Fan-out Service

Pushes new posts to followers’ feeds (fan-out on write).


Timeline Store

Stores precomputed or dynamically generated user feeds.


Search Service

Enables searching posts, hashtags, and users.


Notification Service

Sends alerts for interactions (likes, comments).


Media Service

(Optional) Handles attachments like images or videos.


Cache Layer (Redis)

Caches hot feeds and posts for low-latency retrieval.


Analytics / Trending Service

Tracks engagement and trending topics.


🧱 High-Level Architecture

1 2 +-------------------------+ 3 | API Gateway | 4 +-----------+--------------+ 5 | 6 +----------------------------------------+ 7 | Application Layer | 8 +----------------------------------------+ 9 | User Svc | Post Svc | Feed Svc | Auth Svc| 10 +----------------------------------------+ 11 | 12 +---------------+ 13 | Message Queue | 14 | (Kafka / SQS) | 15 +-------+-------+ 16 | 17 +----------------+----------------+ 18 | | 19 +-------v--------+ +-------v--------+ 20 | Fan-out Svc | | Feed Generator | 21 | (Push tweets | | (Pull timeline) | 22 | to followers) | | dynamically) | 23 +----------------+ +----------------+ 24 | 25 +--------------------------------------+ 26 | Data & Storage Layer | 27 +--------------------------------------+ 28 | Posts DB | User Graph DB | 29 | Feed Cache | Search Index (ES) | 30 | Blob Store | Analytics Store | 31 +--------------------------------------+ 32 | 33 +--------------------------------------+ 34 | Client Layer (UI/Apps) | 35 +--------------------------------------+


🧱 Data Model (Simplified)


User

1 2{ 3 "user_id": "u123", 4 "username": "sahil", 5 "name": "Sahil Batra", 6 "followers": ["u321", "u456"], 7 "following": ["u789"], 8 "created_at": "timestamp" 9}


Post

1 2{ 3 "post_id": "p567", 4 "author_id": "u123", 5 "content": "Excited to start learning system design!", 6 "timestamp": "timestamp", 7 "likes": 100, 8 "comments": 15, 9 "reposts": 10, 10 "hashtags": ["#systemdesign", "#learning"] 11}


FeedEntry

1 2{ 3 "user_id": "u321", 4 "post_id": "p567", 5 "timestamp": "timestamp" 6}


⚙️ Feed Generation Models


🅰️ Fan-out on Write (Push Model)


•When a user posts, the system pushes that post into all followers’ timelines.
•Fast reads, slow writes.
•Ideal for users with a moderate number of followers.


🅱️ Fan-out on Read (Pull Model)


•When a user opens their feed, fetch posts dynamically from people they follow.
•Fast writes, slow reads.
•Used for users with very high follower counts (e.g., celebrities).


🧠 Hybrid Approach


•Use push model for normal users.
•Use pull model for users with massive followings (to avoid overload).


⚡ Key Workflows


1. Posting a Tweet


1.User calls POST /tweet API.
2.Post Service stores the tweet in the Posts DB.
3.Fan-out Service reads followers from User Graph DB.
4.Pushes the post ID into each follower’s Feed Cache (via Kafka).
5.Notification Service triggers alerts for followers.


2. Reading the Feed


1.User calls GET /feed/{user_id} API.
2.Feed Service fetches post IDs from Feed Cache or Feed DB.
3.For each post ID, Post Service fetches details.
4.Response sent to client with latest posts.


3. Following a User


1.POST /follow updates the User Graph DB.
2.On next feed generation, new followee’s posts are included.


🧱 Storage Design


| Data | Storage | Rationale |

| ------------------ | ------------------------------------------ | ---------------------------- |

| User Profiles | Relational DB (PostgreSQL) | Strong consistency |

| User Relationships | Graph DB (Neo4j / DynamoDB adjacency list) | Efficient follower lookups |

| Posts | NoSQL (Cassandra / DynamoDB) | High write throughput |

| Feeds | Redis / Cassandra | Fast reads |

| Media | Blob Storage (S3 / GCS) | Durable large object storage |

| Search | Elasticsearch | Text and hashtag search |

| Analytics | ClickHouse / BigQuery | Real-time metrics and trends |


📡 APIs


| Method | Endpoint | Description |

| ------ | -------------------- | ----------------------- |

| `POST` | `/users/{id}/follow` | Follow another user |

| `POST` | `/posts` | Create a new post |

| `GET` | `/users/{id}/feed` | Retrieve user’s feed |

| `GET` | `/posts/{id}` | Get post details |

| `POST` | `/posts/{id}/like` | Like a post |

| `GET` | `/trending` | Fetch trending hashtags |


⚙️ Scaling & Optimization

Caching:

•Store hot feeds in Redis.
•Use CDN for static content (images/videos).

Sharding:

•Partition users/posts by user_id modulo N.

Async Processing:

•Queue heavy tasks (fan-out, notifications) via Kafka/SQS.

Rate Limiting:

•Prevent spam posts and abuse.

Indexing:

•Maintain secondary indexes on hashtags, timestamps.

Eventual Consistency:

•Allow feeds to be slightly delayed for scale.

Follower Graph Optimization:

•Maintain adjacency lists in memory for hot users.


🚨 Challenges & Trade-offs


| Challenge | Solution |

| ------------------------------------------ | ---------------------------------------- |

| Celebrity users with millions of followers | Use **fan-out on read** for such users |

| Large feed size | Pagination + lazy loading |

| Feed freshness vs cost | Hybrid push/pull model |

| Duplicate delivery | Use unique message IDs in queues |

| Consistency | Eventual consistency using async updates |


✅ Goal:

Design a scalable, low-latency social feed system that supports millions of users, combines push and pull-based feed delivery, ensures real-time updates, and provides extensibility for future features like trending topics, rich media, and recommendations.

Solution

Comments