Design a News Feed system

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-04-29

Problem Statement

Design a scalable and low-latency News Feed System that displays a personalized and real-time feed of posts (text, images, videos, or links) to users.


The feed should be dynamically updated based on:


•The users they follow or are friends with.
•Post recency, relevance, and engagement (likes, comments, shares).
•Optional recommendation or ranking algorithms.


The system must support billions of users, millions of posts per second, and real-time updates.


🎯 Objective


Build a highly scalable, personalized, and real-time feed delivery system where users can:


•View a ranked list of posts from friends/followed accounts.
•Create and publish posts.
•Like, comment, and share content.
•Get new posts reflected in near real-time.


The system should handle massive read traffic, frequent writes, and ensure freshness of the feed.


✅ Functional Requirements


1. Post Creation


•Users can create posts with text, photos, or videos.
•Each post has:
•Content, Author ID, Timestamp, Media URL(s), Metadata.
•Posts are stored durably and become visible to followers.


2. Feed Generation


•For each user, the system should:
•Fetch posts from people they follow.
•Rank and order them (by time, engagement, or relevance).
•Display a feed of top N posts.


3. Reactions and Engagement


•Users can like, comment, or share posts.
•The system tracks engagement metrics for ranking.


4. Real-Time Updates


•When a user posts something, their followers’ feeds should update quickly (within a few seconds).
•Support notifications for new posts from followed users.


5. Pagination and Infinite Scroll


•Support APIs for incremental feed loading (e.g., 20 posts at a time).


6. Optional Features


•Trending or recommended posts.
•Push notifications for new activity.
•Hashtags or topic-based feeds.


⚙️ Non-Functional Requirements


| Attribute | Goal |

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

| **Scalability** | Support hundreds of millions of users and billions of posts |

| **Latency** | Feed generation < 100 ms (read) |

| **Availability** | ≥ 99.99% uptime |

| **Consistency** | Eventual consistency acceptable |

| **Durability** | No data loss for posts or engagements |

| **Throughput** | Handle millions of writes and billions of reads per day |

| **Freshness** | Posts visible to followers within a few seconds |



🧩 Core Components


| Component | Responsibility |

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

| **User Service** | Manages user profiles and relationships (follow/friend). |

| **Post Service** | Handles post creation, storage, and retrieval. |

| **Feed Generation Service** | Builds and ranks the feed for users. |

| **Feed Cache / Timeline Store** | Stores precomputed feeds for fast retrieval. |

| **Fanout Service** | Distributes new posts to followers’ feeds. |

| **Engagement Service** | Tracks likes, comments, shares. |

| **Notification Service** | Sends real-time alerts for new posts or interactions. |

| **Ranking/Recommendation Engine** | Ranks feed items using relevance and engagement scores. |

| **CDN / Media Store** | Serves images and videos efficiently. |

| **Analytics/Monitoring** | Tracks metrics for usage and ranking performance. |


🧱 High-Level Architecture

1 2 +------------------------+ 3 | Client App | 4 | (Web / Mobile / API) | 5 +-----------+------------+ 6 | 7 v 8 +----------+-----------+ 9 | API Gateway | 10 +----------+-----------+ 11 | 12 +------------------------------------------+ 13 | | 14 v v 15+-----------+ +--------------+ 16| Post | | Feed Service | 17| Service |<------> Cache/DB ---------->| (Read Feed) | 18+-----------+ +--------------+ 19 | ^ 20 | | 21 v | 22+------------+ +---------------+ | 23| Fanout |--------->| Timeline Store|-------+ 24| Service | | (Redis/Cassandra) | 25+------------+ +---------------+ 26 | 27 v 28+----------------+ 29| Notification | 30| Service | 31+----------------+


⚡ Feed Generation Strategies


There are two main approaches to building user feeds:


| Strategy | Description | Pros | Cons |


| **Push Model (Fanout-on-write)** | When a user posts, the post is *pushed* to all followers’ feeds immediately. | Fast reads | Expensive writes (esp. for users with millions of followers) |

| **Pull Model (Fanout-on-read)** | When a user opens their feed, the system *pulls* recent posts from all followed users. | Cheaper writes | Slower reads, more computation on read |

| **Hybrid** | Combine both: push for normal users, pull for high-fanout users. | Balanced | More complex architecture |


🧾 Data Model (Simplified)


User Table

| Field | Description |


| user_id | Unique identifier |

| name | User name |

| following | List of user IDs followed |



Post Table


| Field | Description |


| post_id | Unique ID |

| user_id | Author ID |

| content | Text or media |

| media_url | Optional image/video |

| timestamp | Creation time |

| engagement_score | Computed ranking factor |


Feed Table (for fanout-on-write)

| Field | Description |


| user_id | Feed owner |

| post_ids | Ordered list of visible posts |


🔒 Security & Privacy


•Users can set visibility: public, friends-only, private.
•Access tokens (JWT) for authenticated APIs.
•Rate limiting to prevent spam.
•Audit logs for content moderation.


🧠 Scalability & Performance Considerations


| Challenge | Solution |

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

| **High Write Volume** | Use Kafka for async fanout and message queuing. |

| **Hot Users (millions of followers)** | Use pull-based feed generation. |

| **Feed Ranking** | Precompute top-ranked posts per user segment. |

| **Low Latency** | Cache feeds in Redis / Memcached. |

| **Data Explosion** | Use sharded, time-partitioned storage (Cassandra, DynamoDB). |

| **Realtime Updates** | Use WebSockets or push notifications. |

| **Media Load** | Serve via CDN. |

| **Eventual Consistency** | Use background sync jobs for feed reconciliation. |



⚙️ Tech Stack (Example)


| Layer | Technology |

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

| **Frontend** | React / Flutter |

| **Backend Services** | Go / Java / Node.js |

| **Message Queue** | Kafka / RabbitMQ |

| **Datastore (Posts)** | Cassandra / DynamoDB |

| **Cache** | Redis / Aerospike |

| **Search** | Elasticsearch |

| **Media Store** | S3 / GCS + CDN |

| **Auth** | OAuth2 / JWT |

| **Ranking** | ML models (TensorFlow / Scikit-learn) |

| **Monitoring** | Prometheus + Grafana |



📊 Observability & Metrics


•Average feed generation latency.
•Post fanout delay.
•Feed freshness (how recent posts appear).
•Cache hit ratio.
•DB read/write QPS.
•Engagement CTR, dwell time.


🚨 Failure Handling


| Failure | Mitigation |

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

| **Fanout queue lag** | Scale consumers horizontally |

| **Feed cache miss** | Fall back to recompute feed on-demand |

| **DB node down** | Replication and sharding |

| **Service overload** | Implement circuit breakers and rate limiting |


🧩 Possible Extensions

•Personalized ranking using ML (user behavior, content type).
•Topic or hashtag-based feed.
•Content moderation and spam detection.
•Notifications for trending posts or mentions.
•Offline sync and caching on mobile.


✅ End Goal

Design a real-time, personalized, and scalable News Feed System that:

•Efficiently delivers relevant posts to each user.
•Handles billions of reads and writes with low latency.
•Balances freshness, ranking, and performance at scale.


Solution

Comments