InterviewDryRun
Lesson 7 · 20 min video · free

Design a News Feed

The news feed is the classic question about read-heavy social systems: users follow each other, post, and open a ranked feed that must load in a fraction of a second. The heart of the answer is the choice between building feeds when posts are written or when feeds are read, and the hybrid that handles accounts with millions of followers. This lesson covers the full 45-minute answer.

What you will learn

  • Feeds are read far more than posts are written, so do work at write time where you can.
  • Fan-out on write pushes post ids into followers' feed caches; it breaks for huge accounts.
  • Use a hybrid: push for normal accounts, pull for celebrities at read time, then merge.
  • Store only post ids in feed caches and hydrate them from a post cache.
  • Rank in two stages: gather candidates cheaply, then score a few hundred with a model.
  • Paginate with a cursor, not an offset, so new posts do not shift the page.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API
  5. Step 4: The data model
  6. Step 5: Fan-out on write or on read?
  7. Step 6: Reading the feed
  8. Step 7: Ranking
  9. Step 8: Pagination and freshness
  10. Step 9: Writing a post, end to end
  11. Step 10: Scaling and failures
  12. Step 11: The follow-up questions
  13. Recap

Short on time? Read the answer outline for design a News Feed.

Practice this question with Max

The question

Welcome to lesson seven of the InterviewDryRun system design course. Today we design a news feed: the endless, ranked list of posts from the people you follow, which is the first screen of almost every social app.

It is one of the most frequently asked system design questions, and for good reason. It looks like a simple query, show me recent posts from people I follow, but at scale that simple query becomes impossibly expensive, and the way you fix it reveals whether you understand the difference between doing work when data is written and doing it when data is read. That one idea, and its trade-offs, is the core of today's lesson.

Max asks

“Design the feed for a social app: users follow others, post text and images, and open a ranked feed.”

That is how Max, our AI interviewer, asks it. Notice the three verbs: follow, post and open. Those are our three main operations. And notice the word ranked: the feed is not simply in time order, so we will need to say something sensible about ranking without turning the interview into a machine learning lecture.

The plan: requirements and numbers first, then the API and the data model. Then the key decision, fan-out on write or fan-out on read, and the hybrid that real systems use. Then caching, ranking, media, pagination, and the failure cases. And as always, we finish with the follow-up questions interviewers like to ask.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    PostText and up to a few images
  2. 02
    FollowOne-way, like most modern social apps
  3. 03
    Open the feedPosts from people you follow, ranked
  4. 04
    ScrollLoad more, page after page
  5. 05
    Likes and commentsCounts shown on each post

Start with questions. The feed has many possible features, so agree on a core and say what you are leaving out of scope, like stories, ads, or direct messages.

Users create posts with text and a few images. They follow other users, and we assume following is one-way, so you can follow someone without them following you back. That matters, because one-way follows allow a single account to have millions of followers, which will be the hardest part of the design.

The feed shows posts from people you follow, ranked, and you can keep scrolling to load more. Each post shows its like and comment counts. Ask whether the feed should include posts from accounts you do not follow, like recommendations. Say you will design for followed accounts first and show where recommendations would plug in.

Likes and comments are part of the product, but the interactions themselves are a separate design. For the feed, we just need their counts to show on each post, and we can accept those counts being slightly behind.

Non-functional requirements
  1. 01
    Fast feedFirst page under 200 ms at the 99th percentile
  2. 02
    Highly availableA stale feed is better than an error
  3. 03
    Eventually consistentA new post can take a few seconds to show
  4. 04
    Read heavyFeeds are opened far more often than posts are written

The qualities. The feed must load fast, a couple of hundred milliseconds for the first page, because it is the first thing users see. And it must be highly available: if something is wrong, showing a slightly old feed is much better than an error screen.

Then the trade-off to say out loud. We accept eventual consistency: a new post may take a few seconds to reach followers' feeds. Nobody notices a few seconds. And the system is extremely read heavy: people open their feed many times a day, but post rarely. When reads vastly outnumber writes, it is usually worth doing extra work at write time to make reads cheap. Keep that principle in mind, because it drives the main decision of this design.

Step 2: Back-of-the-envelope estimates

Sizing the feed
Daily active users300 millioneach opens the feed about 10 times
Feed reads3 billion / dayabout 35,000 a second, 100,000 at peak
New posts100 million / dayabout 1,200 a second
Average followersabout 200some have tens of millions
Feed inserts20 billion / dayposts x followers, if we push
Mediamost of the bytesimages go to object storage and a CDN

Let us size it, because the numbers will make the key decision for us.

Say three hundred million daily active users, each opening the feed about ten times a day. That is three billion feed reads a day, about thirty-five thousand a second on average, and say a hundred thousand at peak.

New posts are far fewer: say a hundred million a day, about twelve hundred a second. So feed reads outnumber posts by around thirty to one, and each feed read shows many posts, so the real ratio of reading posts to writing them is much larger.

Now the critical number. The average user has a couple of hundred followers. If every post is copied into each follower's feed, that is a hundred million posts times two hundred, twenty billion feed inserts a day. That is a lot, but it is spread out and each insert is tiny, just a post id. The problem is not the average. It is the account with fifty million followers, where one post means fifty million inserts at once. Remember this: averages are fine, outliers are the design problem.

And media: images are most of the bytes by far. They go to object storage and are served through a content delivery network, never through our feed servers. The feed only carries links to them. Say that early, so the interviewer knows you will not push images through the database.

Step 3: The API

API
POST /v1/posts
  { "text": "...", "mediaIds": ["m_31", "m_32"] }
→ 201 { "postId": "p_8812" }

POST /v1/users/{id}/follow      DELETE to unfollow

GET /v1/feed?cursor=eyJ0Ijo...&limit=20
→ { "posts": [ { "id", "author", "text",
               "media", "likes", "comments" } ],
    "nextCursor": "eyJ0Ijo..." }

The API is small. Creating a post sends the text and the ids of media that the client already uploaded. Uploading images is a separate step: the client asks for an upload URL, sends the image straight to object storage, and then references it. That keeps big uploads away from our application servers.

Follow and unfollow are simple calls. And the feed is one GET with a cursor and a page size. The response contains fully assembled posts, author name and picture, text, media links and counts, so the client can render the screen with one request. A mobile app on a slow network should never need twenty round trips to show one screen.

Note the cursor rather than a page number. We will come back to why, but the short version is that the feed changes while you scroll, and page numbers would show duplicates or skip posts. Mentioning it in the API already signals that you have built paginated feeds before.

Step 4: The data model

Core tables
TableKeyHolds
usersuser_idname, picture, follower count
postspost_id (time-ordered)author_id, text, media ids, created_at
followsfollower_id, followee_idwho follows whom, both directions
feed (cache)user_idlist of post ids, newest first
counterspost_idlikes, comments, approximate

Now the data model. There are a few core tables, and one important cached structure.

Users and posts are straightforward. Give posts time-ordered ids, like the generator from lesson three, so sorting by id is sorting by time. The posts table is large and append-mostly, and is partitioned by post id.

The follows table is the social graph. We need it in both directions: who does this user follow, to build their feed, and who follows this user, to deliver their posts. So store it twice, partitioned once by follower and once by followee, so that each question is a single partition read. Duplicating data to make each query cheap is a normal and good choice here.

Then the feed itself. For each user, a list of the post ids that should appear in their feed, newest first, capped at a few hundred. It lives in an in-memory store, because it is read on every feed open. Notice it holds ids, not whole posts. We will see why that matters in a moment.

And counters for likes and comments, kept separately from posts, because they change constantly, and updating the post row on every like would create hot spots on popular posts. Counts can be approximate and slightly delayed.

Step 5: Fan-out on write or on read?

The central decision
Fan-out on read (pull)Fan-out on write (push)
When postingjust store the postcopy post id to every follower's feed
When readingfetch from everyone you follow, mergeread your precomputed list
Read costhigh: hundreds of querieslow: one list
Write costlowhigh for big accounts
Problemslow feeds for everyonecelebrity posts: millions of inserts

This is the heart of the question, so slow down and lay out both options clearly.

Option one, fan-out on read, also called pull. When you post, we just store the post. When someone opens their feed, we look up everyone they follow, fetch each one's recent posts, merge them, rank them, and return the top. Writing is cheap. But reading is expensive: following five hundred accounts means five hundred lookups on every feed open, a hundred thousand times a second. The feed would be slow and the databases overloaded.

Option two, fan-out on write, also called push. When you post, we look up all your followers and insert your post id at the top of each of their feed lists. When someone opens their feed, we just read their list. Reading is one fast lookup. Given how read-heavy the system is, this is clearly the better default.

But push has a famous problem. An account with fifty million followers posts. We must now insert into fifty million feed lists. Even at a million inserts a second, that takes nearly a minute, and a few such accounts posting at once would swamp the fan-out workers. Worse, most of those followers will not open the app before the post is old, so much of that work is wasted.

The hybrid
new postpush idbig accountsCLIENTAuthor postsSERVICEPost servicestores the postQUEUEFan-out queueWORKERFan-out workersnormal accounts onlyCACHEFeed cachepost ids per userSTORECelebrity postspulled at read time

So the real answer, and the one interviewers are waiting for, is a hybrid. Treat accounts differently depending on their number of followers.

For normal accounts, which is almost everyone, use push. A new post goes onto a queue, and fan-out workers insert its id into each follower's feed list. With a couple of hundred followers, that is a couple of hundred tiny writes, done in the background within seconds.

For accounts above a threshold, say a hundred thousand followers, skip the fan-out. Their posts are stored as usual. When a user opens their feed, we read their precomputed list, and also pull the recent posts from the handful of big accounts they follow, and merge the two. Most users follow only a few such accounts, so the pull part adds only a few cheap lookups, and those posts are extremely cacheable because millions of people read the same ones.

Two refinements are worth a sentence each. First, skip fan-out for inactive users. If someone has not opened the app in a month, do not maintain their feed; build it on demand with pull when they come back. That removes a large share of all fan-out work. Second, the threshold is not just about follower count. An account with many followers that posts once a year is cheap; one that posts every minute is expensive. Base the decision on follower count times posting rate, and say that it can be tuned.

Step 6: Reading the feed

The read path
1. ids2. order3. hydratemissCLIENTAppSERVICEFeed serviceassemble a pageCACHEFeed cachepost idsCACHEPost cachepost bodiesSERVICERanking serviceSTOREPost storeon cache miss

Now let us trace a feed open, step by step. The app asks the feed service for the first page.

Step one: read the user's list of post ids from the feed cache, a few hundred ids, and merge in recent posts from any big accounts they follow.

Step two: rank those candidates, which we will discuss in detail in a minute, and pick the top twenty for this page.

Step three, hydration: turn the twenty ids into full posts. Fetch the post bodies from a post cache in one multi-get, along with author names and pictures from a user cache, and current counts from the counters. Cache misses fall through to the post store.

This is why feed lists store ids, not full posts. If we copied the whole post into fifty million feeds, an edit or a deletion would mean fifty million updates, and memory use would explode. With ids, a post exists once in the post cache, popular posts stay hot there because everybody reads them, and an edit takes effect everywhere immediately. Interviewers often ask this, so say it before they do.

And measure the result against the latency budget. One feed cache read, one ranking call, and one multi-get to the post cache, each a few milliseconds and some of them in parallel. We land comfortably under our two hundred millisecond target, with room for the network to the user's phone.

Step 7: Ranking

Two-stage ranking
  1. 01
    CandidatesA few hundred recent posts from people you follow
  2. 02
    FeaturesYour affinity to the author, post age, engagement so far
  3. 03
    ScoreA model predicts how likely you are to engage
  4. 04
    RulesDiversity, no five posts in a row from one author
  5. 05
    FallbackReverse chronological if ranking is down

The question said ranked, so we need a sensible ranking story, without becoming a machine learning interview. The standard shape has two stages. First, gather a few hundred candidates cheaply: that is exactly the feed list we just built.

Second, score each candidate. Features include how often you interact with this author, how old the post is, and how much engagement it is already getting. A model, trained on past behaviour, predicts how likely you are to like, comment or spend time on each post, and we sort by that score. Scoring a few hundred posts with a lightweight model takes milliseconds.

On top of the score, apply rules: do not show five posts in a row from the same author, mix in different kinds of content, and push down posts the user has already seen. These rules matter a lot to how the feed feels.

And always have a fallback. If the ranking service is slow or down, show the candidates in reverse time order. It is a worse feed, but it is a feed, which matches our requirement that availability beats perfection.

If the interviewer wants recommendations, posts from accounts you do not follow, this is where they plug in: another candidate source, from a recommendation system, mixed into the same ranking stage. The architecture does not change. That is a good sign the design is right.

One practical detail about features. The ranking model needs numbers like your affinity with each author, which come from your history of likes, comments and profile visits. Computing those at request time would be far too slow. So they are computed in the background, by batch and streaming jobs, and stored in a feature store keyed by user, ready to be read in one call when the feed is ranked. Precomputing again, because reads must be cheap.

Step 8: Pagination and freshness

Why a cursor, not an offset
page 1: offset 0, limit 20   → posts 1-20
   ... 3 new posts arrive at the top ...
page 2: offset 20, limit 20  → posts 18-37
                               (18, 19, 20 shown twice)

cursor: "after score 0.83, post p_8812"
page 2: posts ranked below the cursor → no repeats

Now scrolling. If page two means skip the first twenty posts, then any new posts that arrive at the top while you read page one shift everything down, and page two repeats posts you just saw. With a ranked feed it is even worse, because scores change.

The fix is a cursor. When we build the first page, we take a snapshot of the ranked list for this session and keep it briefly in a cache, and the cursor says where in that snapshot you are. Page two continues from that point. New posts do not shift anything; they show up the next time you pull to refresh, as a fresh first page.

And freshness while the app is open. We do not need to push every new post to the open app in real time. A simple approach is to show a small banner, new posts, when a light check finds new items at the top of the feed list. The user taps it to refresh. It keeps the feed stable while reading, which users prefer to posts jumping around under their finger.

Step 9: Writing a post, end to end

What happens when someone posts
  1. 01
    1. Upload media firstStraight to object storage with a signed URL
  2. 02
    2. Create the postValidate, store, return the id at once
  3. 03
    3. Publish an eventNew post, author id, follower count
  4. 04
    4. Fan out in batchesPage through followers, a thousand at a time
  5. 05
    5. Side jobsSafety checks, search index, notifications

We have looked at reading in detail. Let us also trace a post from the author's side, because the write path has its own subtleties. First, the images. The app asks for a signed upload link, uploads each image straight to object storage, and gets back media ids. Image processing, resizing into several sizes for different screens, happens asynchronously after upload.

Then the app creates the post with its text and media ids. The post service validates it, stores it in the post store, and returns the post id immediately. The author sees their post at once, because the app inserts it at the top of their own feed locally. That small trick hides all the fan-out delay from the one person most likely to notice it.

The post service publishes a new post event to a queue. Fan-out workers pick it up, page through the author's followers a thousand at a time, and append the post id to each follower's feed list, trimming the list to its maximum length. Batching matters: one worker writing a thousand feed updates in a pipeline is far faster than a thousand separate calls. If a worker crashes halfway, the event is redelivered, and because adding the same id twice to a list can be made harmless by checking the top of the list, the retry is safe.

The same event feeds other consumers: content safety checks, the search index, and notifications to close friends. This is a nice moment to say that the event is the integration point. New features subscribe to new post events instead of being bolted into the post service, so the post path stays fast and simple no matter how many features are built on top of it.

Step 10: Scaling and failures

What breaks, and what we do
  1. 01
    Celebrity postsPulled at read time, served from a hot cache
  2. 02
    Fan-out backlogQueue absorbs it; posts arrive a little later
  3. 03
    Feed cache node lostRebuild a user's feed on demand by pulling
  4. 04
    Viral postOne post body read by millions: replicate the hot key
  5. 05
    Deleted postFilter at hydration; no need to touch feed lists

Let us walk through what breaks. Celebrity posts are handled by the hybrid, and because millions of users pull the same celebrity posts, those sit in the hottest part of the post cache, with copies in each app server for a few seconds.

If many accounts post at once, say during a big sports final, the fan-out queue grows. That is fine: posts reach feeds a little later, and nothing fails. Monitor the queue's age, and add fan-out workers automatically when it grows.

If a feed cache node dies, the users whose feed lists lived there lose their precomputed feed. We do not need to restore it from a backup. The feed can be rebuilt on demand, by pulling recent posts from everyone the user follows, which is slow once, then cached again. So the feed cache is disposable, and we can say so with confidence.

A viral post means one post body read by millions of users, which makes one key hot in the post cache. The hot key techniques from the cache lesson apply: local copies in each feed server, or several copies of the key. And deletes: when a post is deleted, we do not remove it from millions of feed lists. Hydration simply finds it marked deleted and skips it. Lazy cleanup like this is a common, powerful pattern.

Unfollow works the same way. Rather than scrubbing the unfollowed author's posts out of the feed list immediately, filter them out at read time by checking the follow graph for the authors on the page, and let them age out of the list. The user sees the right result immediately, and the expensive cleanup never has to happen.

Step 11: The follow-up questions

Max asks

“A user follows someone new. When do that person's posts appear in their feed?”

New posts arrive through normal fan-out from then on. For existing posts, we can backfill: fetch the new followee's last few posts and merge them into the user's feed list right away, so the feed changes the moment they follow. It is a small, one-time pull, and it makes the product feel responsive.

Max asks

“How would you show accurate like counts on a post that is getting ten thousand likes a second?”

Do not update one counter row ten thousand times a second. Write like events to a log, aggregate them every second or so in a stream processor, and update the counter in batches. Or split the counter into many shards and sum them on read. Show the count as approximate, like twelve thousand, which hides the small delay. The exact list of who liked it lives elsewhere and can be eventually consistent.

Max asks

“How big is the feed cache, and do you really need every user's feed in memory?”

Three hundred million active users times a few hundred ids at eight bytes is a few hundred gigabytes, plus overhead, so roughly a terabyte across the cluster. That is fine. But we only keep feeds for active users; inactive users' feeds are dropped and rebuilt on demand. Most of the memory then goes to people who actually open the app.

Max asks

“How would you test a change to the ranking model safely?”

With an experiment. Route a small percentage of users to the new model and compare engagement, time spent and complaint signals against the current model, over a week or so. Log the features and scores served, so you can debug. And keep the reverse chronological fallback and the old model ready, so a bad model can be switched off in seconds.

Max asks

“A user reports that a post from a friend never showed up. How would you debug it?”

Follow the post through each stage. Was the post stored, and was the new post event published? Did the fan-out workers process it, and was the user in the follower list at that moment? Is the post id in the user's feed list now, or was it trimmed? Was it filtered at hydration, by a safety check or a block, or ranked so low it never reached the first pages? Logging the post id at each stage, with sampling, makes this a five-minute investigation instead of a mystery.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsPost, follow, ranked feed; fast, available, eventually consistent
  2. 02
    5 to 10: estimates100,000 feed reads a second; 20 billion inserts a day if we push
  3. 03
    10 to 20: API and dataGraph stored both ways; feed cache of ids
  4. 04
    20 to 35: fan-outPush for most, pull for celebrities, merge; ids then hydrate
  5. 05
    35 to 45: ranking and scaleTwo-stage ranking, cursors, hot posts, lazy deletes

Let us put it on the clock. Five minutes of requirements, landing on fast and available with eventual consistency. Five minutes of numbers, which show that reads dominate and that big accounts are the outlier that breaks naive designs.

Ten minutes on the API and data model: the follow graph stored in both directions, posts with time-ordered ids, and a feed cache that holds only ids.

Fifteen minutes on the central decision: fan-out on write for most accounts, fan-out on read for celebrities, merged at read time, followed by hydration. And the last ten on ranking, cursor pagination, and what breaks. If you explain the hybrid with the numbers behind it, you have given the answer interviewers are listening for.

Push versus pull is easy to describe and surprisingly easy to fumble under pressure, especially when the interviewer asks about the celebrity case. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson eight.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.