Hello! Welcome to our lesson on designing a news feed system.
In our last lesson, we architected a complete ride-sharing system, focusing on Uber's challenges. We tackled real-time logistics, geospatial indexing for proximity search, dynamic pricing via stream processing, and ensuring transactional consistency with distributed locks.
Today, we shift our focus from real-time logistics to large-scale content delivery, a problem domain mastered by companies like Meta. Our goal is to design a news feed system, discussing the critical trade-offs around ranking, fan-out strategies, and real-time updates. While the chronological feed is a good starting point, a Staff-level design for Meta must address the enormous scale and personalization required to serve billions of users.
1. Laying the Foundation: Requirements and a Naive Approach
As always, we begin by defining the problem scope. A news feed is a seemingly simple product, but its implementation at scale is one of the classic, challenging system design problems.
Design FB News Feed System Design Interview w/ ex: Meta Senior Manager
To start, let's watch this segment from a mock interview with an ex-Meta Senior Manager. It clearly outlines the functional and non-functional requirements for a chronological news feed, which serves as our V1.
Please watch from 02:51 to 09:22. Focus on how the problem is framed: Functional Requirements (02:51 - 04:16): Defining the core actions: creating posts, following users, and viewing a paginated feed. Non-Functional Requirements (04:16 - 05:53): Quantifying system goals like eventual consistency (a 1-minute staleness tolerance), latency (< 500ms), and massive scale (2 billion users). API Design (05:53 - 09:22): Translating these requirements into a clear API contract, including the use of cursors for pagination.
Let's summarize the core requirements for our initial, simplified version:
- Functional:
- Users can create posts.
- Users can follow other users (unidirectional relationship).
- Users can view a reverse-chronologically sorted feed of posts from people they follow.
- The feed supports infinite scroll through pagination.
- Non-Functional:
- High Availability: The system must be always on.
- Eventual Consistency: It's acceptable for a new post to take up to a minute to appear in followers' feeds. Strict consistency is not required.
- Low Latency: Feed generation should feel instantaneous (< 500ms).
- Massive Scale: The system supports billions of users.
The Naive "Fan-out on Read" Design
The most straightforward way to implement this is to generate the feed on-demand when a user requests it.
Design FB News Feed System Design Interview w/ ex: Meta Senior Manager
This next clip outlines the initial high-level design that directly implements our requirements. Pay close attention to the feed generation logic, as this is where the primary bottleneck will appear.
Watch from 09:22 to 16:12. This covers: Post and Follow Services (09:22 - 13:17): Simple CRUD services for storing posts and follow relationships. Note the use of a key-value store like DynamoDB and Global Secondary Indexes (GSIs) to support the necessary query patterns (e.g., find all users someone is following). Naive Feed Service (13:17 - 16:12): This is the crucial part. The service implements the "fan-out on read" logic: get all followed users, fetch recent posts for each of them, then merge and sort. The presenter explicitly calls out that this is problematic, which is a key interview strategy.
This on-demand approach, known as fan-out on read, involves the following steps at read time:
- A user requests their feed.
- The
Feed Servicequeries aFollowtable to get the list of alluser_idsthe user follows. - For each
user_idin that list, the service queries aPosttable to get their recent posts. - The service then merges all these sets of posts, sorts them by timestamp, and returns the top
Nto the user.
While this works for users following a handful of people, it collapses at scale. Imagine a user following 1,000 people. The Feed Service would have to make ~1,001 database queries, merge potentially tens of thousands of posts, and sort them, all within a few hundred milliseconds. This is not a viable solution.
2. Deep Dive: Solving the Fan-out Problem
The core challenge of a news feed system is managing this fan-out. Since fan-out on read is too slow, the logical alternative is to do the work ahead of time.
Shifting the Burden: Fan-out on Write
This approach, called fan-out on write, shifts the computational load from read time to write time. Instead of pulling posts when a feed is viewed, we push posts into feeds when they are created.
The architecture involves pre-computing a feed for each user and storing it in a cache.
Design Facebook's News Feed - Potential Deep Dives
The article 'Design Facebook's News Feed' explains this shift from read-time to write-time computation. It introduces a pre-computed feed table and discusses the implementation details.
Read the section titled '1) How do we handle users who are following a large number of users?'. It introduces the concept of a PrecomputedFeed table and why this is a better approach for scaling reads.
The fan-out on write workflow looks like this:
- A user creates a new post.
- The
Post Servicesaves the post and publishes an event (e.g., to a Kafka topic). - A
Feed Workerservice consumes this event. - The worker looks up all the followers of the post's author.
- For each follower, the worker appends the new
post_idto a list in a cache (e.g., Redis) that represents that follower's feed. For a chronological feed, this is typically aZSETin Redis, with the timestamp as the score and thepost_idas the value. - When a user requests their feed, the
Feed Servicesimply reads this pre-computed list ofpost_idsfrom the cache, fetches the full post objects, and returns them. This is incredibly fast.
But we've only traded one problem for another. What happens when a celebrity with 100 million followers posts? The Feed Worker now has to perform 100 million cache writes. This is the celebrity problem, or fan-out on write bottleneck.
The Staff-Level Solution: A Hybrid Approach
A one-size-fits-all solution is inefficient. The key insight is that most users are not celebrities, and most users don't follow celebrities. We can combine both strategies.
Design Facebook's News Feed - Potential Deep Dives
This is a classic Staff-level trade-off. The 'Hello Interview' article provides an excellent explanation of a hybrid fan-out model.
Please read the section '2) How do we handle users with a large number of followers?'. It details how to use async workers and, more importantly, the hybrid approach where you fan-out on write for normal users but fan-out on read for celebrities, merging the results at request time.
The hybrid model works as follows:
- For most users (< N followers): Use fan-out on write. When they post, their content is pushed to their followers' cached feeds. This optimizes the read path for the vast majority of user interactions.
- For celebrities (> N followers): Use fan-out on read. When they post, we do not push the update to millions of feeds. Instead, we flag these users as "celebrities."
- At read time: When a user requests their feed, the
Feed Serviceperforms two actions:- Retrieves the pre-computed feed from the cache (containing posts from non-celebrities they follow).
- Identifies the handful of celebrities the user follows, fetches their latest posts directly from the
Posttable, and merges them with the cached feed before returning the result.
This hybrid strategy intelligently balances write-time and read-time costs, providing a scalable solution that handles both common and edge cases efficiently.
3. Deep Dive: Real-time Updates and ML-Powered Ranking
So far, we've designed a scalable chronological feed. But the core of Meta's News Feed is personalization and ranking. The goal is not to show you what's newest, but what's most valuable to you.
This requires a fundamental shift from simple sorting to predictive modeling.
News Feed ranking, powered by machine learning
This official blog post from Meta's engineering team is the best possible resource for understanding how their ranking system works. It describes the theory and the architecture.
Please read the entire article. It's dense but packed with Staff-level details. Focus on: Objective Function: Understanding that ranking optimizes for a complex value function (Vijt), not just a single signal like 'likes'. System Architecture: The multi-pass ranking process is key. A lightweight model filters thousands of posts down to ~500 (Pass 0), a more powerful neural net scores these (Pass 1), and a final pass applies contextual rules like diversity (Pass 2). Real-time Scoring: How the system incorporates fresh signals in real-time.

Here's how ranking fits into our architecture:
- Inventory Gathering: Instead of just grabbing posts chronologically, the system gathers a large pool of candidate posts for a user from various sources (friends, groups, pages).
- Feature Engineering: For each post, the system gathers hundreds or thousands of features: Who posted it? What's your relationship with them? Is it a photo or video? What time of day is it? Have you liked similar posts before?
- Prediction: A set of machine learning models (deep neural networks) take these features as input and predict the probability of various positive interactions (e.g., probability you will like, comment, share, or even find the post "worth your time").
- Scoring & Ranking: The probabilities are combined into a single score that represents the overall predicted value of that post to you.
- Multi-Pass Ranking: To do this efficiently for thousands of candidate posts, a multi-pass system is used:
- Pass 0 (Lightweight): A simple, fast model prunes the inventory from thousands of posts down to the top ~500 candidates.
- Pass 1 (Heavy): A complex, computationally expensive neural network scores these ~500 posts to get a precise ranking.
- Pass 2 (Contextual): Business logic and diversity rules are applied. For example, to avoid showing five videos in a row, the system might down-rank a video if the previous two items in the feed were also videos.
The fan-out on write mechanism still plays a role. Instead of just pushing a post_id, the Feed Worker can pre-compute some initial features or a lightweight score. However, the final, highly personalized ranking happens at read time on a candidate set, making it another example of a hybrid approach.
Real-time Infrastructure
To power this, we need a robust real-time data pipeline.
Design Scalable News Feed System Similar to Instagram, Facebook & Twitter | System Design
The 'Code with Irtiza' video provides a clear walkthrough of an architecture using a Change Data Capture (CDC) stream to drive real-time updates.
Watch from 04:49 to 12:28 and 20:20 to 25:50. These segments explain: How creating a post in a database can trigger an event in a Kafka topic using CDC. How multiple asynchronous 'stream processors' can consume these events to perform actions like content moderation, enrichment, and, most importantly, feed generation (the fan-out on write). The dual approach of having a real-time stream processor for fresh content and an offline batch job for periodic full re-ranking.
This pipeline, often built with technologies like Kafka and Flink/Spark Streaming, is the central nervous system that connects post creation to feed updates and ranking model inputs.
4. Handling Hot Spots
One final challenge: when a post goes viral, millions of users will need to fetch its content (the image, video, text) at roughly the same time. Even if the post_id is in a cached feed, the subsequent call to fetch the post data can create a massive "hot key" problem on your post database or cache.
Design Facebook's News Feed - Potential Deep Dives
A naive sharded cache will still suffer from hot spots. This last reading details a more robust caching strategy for handling viral content.
Read section '3) How can we handle uneven reads of Posts?'. It explains the difference between a standard distributed/sharded cache and a replicated cache for mitigating hot keys.
The solution is to use replicated, non-sharded cache instances. Instead of having one specific server responsible for post_viral, you have multiple cache servers that can all serve it. A load balancer distributes requests randomly among them. If a cache instance misses, it fetches the data from the database. This effectively spreads the read load for a single hot item across multiple machines.
Conclusion
Designing a news feed system is a journey through fundamental distributed systems trade-offs. While we started with a simple chronological feed, a Staff-level design requires a deep understanding of how to evolve it into a scalable, personalized, and real-time system.
Key Takeaways:
- Fan-out Management: The core problem is managing fan-out. A hybrid approach, using fan-out-on-write for most users and fan-out-on-read for celebrities, provides the best balance of read and write performance.
- Ranking over Sorting: Modern feeds are not sorted; they are ranked by ML models to maximize user value. This involves a complex, multi-pass ranking architecture to balance precision and performance.
- Real-time Architecture: An event-driven architecture using CDC and message queues (like Kafka) is essential for propagating updates asynchronously and powering both feed generation and real-time ranking features.
- Hot Key Mitigation: Viral content creates read hot spots, which are best handled by a replicated caching layer rather than a standard sharded cache.
Preview of the Next Lesson:
We've now covered systems for Google (Web Crawler), Uber (Ride-Sharing), and Meta (News Feed). In our next lesson, we will tackle your final requested company-specific design: a food delivery service, with a focus on DoorDash. This will blend the logistical challenges we saw with Uber and the marketplace dynamics of a three-sided platform (restaurants, dashers, and customers).