Design a News Feed

How to design a social news feed, including fan-out on write versus on read, the hybrid approach for huge accounts, and what interviewers ask.

Case study32 minLesson 4 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions
  10. What to practise next

A news feed shows each user a list of recent posts from the accounts they follow, newest or most relevant first, and lets them scroll back through older posts. Interviewers ask for it because the feed is read far more often than it is written, and because the two obvious designs, building each feed when a post is published or building it when the feed is opened, both fail at scale in different ways.

The central decision is when to collect posts into a feed, and a good answer justifies a hybrid with numbers. The design follows A Framework for Any Design.

Clarify the problem

Find out what the feed contains, how it is ordered, and how follower counts are distributed, because the distribution decides the design.

The first five minutes
Interviewer

Design the news feed for a social app.

You

Does the feed contain only posts from accounts the user follows, or also recommendations and ads? And is it ordered by time or ranked?

Interviewer

Only accounts you follow. It should be ranked eventually, but start with newest first.

You

How many daily users are there, how often does each one open the feed, and how many posts are written per day?

Interviewer

There are 100 million daily users, and each opens the feed about 10 times a day. About 10 million posts are written per day.

You

How are follower counts distributed? Can a single account have tens of millions of followers?

Interviewer

The average is about 200 followers, but some accounts have 50 million.

You

Then reading the feed is the hot path. I will assume that a new post may take a few seconds to appear and that a feed may briefly miss a post. Accounts with millions of followers will need special handling.

  • Functional: a user can publish a post, can see posts from the accounts they follow (newest first at launch, ranked later), and can scroll back through older posts.
  • Non-functional: the feed responds in under 200 ms at the 99th percentile, the service stays available when individual components fail, a new post reaches followers' feeds within about 5 seconds, and feeds may be eventually consistent.
  • Out of scope: media upload, search, notifications, ads and recommendations.

Estimate the scale

  • Feed reads: 100 million users × 10 opens is 109 reads a day. Dividing by 86,400 seconds gives about 12,000 reads a second on average, and about 36,000 at a peak of three times the average.
  • Posts: 10 million posts a day is about 116 posts a second, and about 350 at peak. Reads outnumber writes about 100 to 1.
  • Feed memory: keeping the newest 500 entries of 16 bytes (a post id and an author id) for each of 100 million users takes 500 × 16 B = 8 KB per user, or about 800 GB in total. Storing ids instead of whole posts keeps it this small.
Estimate: Fan-out writes

If every post is copied into each follower's feed, how many feed inserts per second is that on average?

You know
  • 10 million posts a day
  • 200 followers per account on average
  • A day is 86,400 seconds

Show the working
  1. Inserts a day: 107 × 200 = 2 × 109
  2. 2 × 109 ÷ 86,400 ≈ 23,000 a second
  3. At a 3x peak: about 69,000 a second

Estimate 23 thousand/s (anything from 8 thousand/s to 70 thousand/s is a good answer)

This load is manageable. The average hides the real problem, which is that one post from an account with 50 million followers means 50 million inserts.

Your turn: Define the API

Write the endpoints for publishing a post and for reading the feed. How does the client ask for the next page?

Compare with a model answer

The endpoints are POST /v1/posts and GET /v1/feed, and the read takes a limit and a cursor. The client sends the cursor from the previous response to get the next page, because page numbers return duplicates when new posts keep arriving at the top.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /v1/posts
  body: { "text": "...", "media_ids": ["m_91"]? }
  201 Created   { "post_id": "7311045529", "created_at": "..." }
  400 Bad Request          empty or too long
  429 Too Many Requests    posting too fast
 
GET /v1/feed?limit=20&cursor=opaque-string
  200 OK  { "posts": [ { "post_id", "author", "text", "media_urls", "created_at", "like_count" } ],
            "next_cursor": "opaque-string" or null }
  400 Bad Request          cursor expired or invalid: start again from the top
 
POST   /v1/users/{id}/follow
DELETE /v1/users/{id}/follow

The API decision worth arguing is cursor pagination. A cursor means "continue after this exact item", so new posts arriving at the top cannot shift the next page the way ?page=2 does. The cursor is an opaque string, so its contents can change when ranking is added.

Your turn: Model the data

For posts, follows and the feed itself, what is the main lookup for each, and what kind of store fits?

Compare with a model answer

Posts are looked up by id. Follows are looked up in both directions: "who follows X" is needed for fan-out and "whom does Y follow" is needed for reads. Each feed is a short in-memory list of post ids per user.

Model the data

Records
posts           post_id    BIGINT PRIMARY KEY   -- time-sortable id
                author_id  BIGINT
                text       VARCHAR(2000)
                media_ids  LIST
                created_at TIMESTAMP
                deleted    BOOLEAN
 
followers       (author_id, follower_id)        -- "who follows X": fan-out
following       (follower_id, author_id)        -- "whom does Y follow": reads
 
author_posts    author_id -> newest post ids    -- for pull and rebuilds
 
feed            user_id -> set of (post_id, author_id), sorted by post_id, max 500
  • Posts are written once, read by id and partitioned by post_id, so a wide-column or key-value store with a cache for hot posts fits. A time-sortable id (see Unique IDs) lets a feed be ordered by id alone.
  • The follow graph is stored once per direction, and each copy is partitioned by its first column, so both lookups read a single partition. The cost is that two copies must be kept in step: a follow writes both.
  • Feed lists live in a replicated in-memory store such as Redis. They hold only ids, so editing or deleting a post never has to touch 50 million feeds. They are also derived data, so a lost list can be rebuilt from following and author_posts.
Your turn: High-level design

Sketch the write path, where a post reaches followers' feeds, and the read path, where a feed page reaches the app. Which steps are synchronous?

Compare with a model answer

Storing the post is synchronous. A queue and fan-out workers then copy it into feeds asynchronously. A feed read takes one feed list from the cache and fills in the post bodies.

High-level design

The post service stores the post and publishes an event, and fan-out workers do the slow work of copying the post id into feeds. The feed service reads one list, adds the posts of the few very large accounts the user follows, and fills in the post bodies from the post cache.

Posting is fast because fan-out happens in workers behind a queue, and reading a feed normally touches only caches.Mobile app to Feed service (GET /feed); Mobile app to Post service (POST /posts); Feed service to Feed cache (read list); Feed service to Post store + cache (fill in posts); Post service to Post store + cache (insert); Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph (followers); Fan-out workers to Feed cache (push ids).Mobile appFeed servicePost serviceFeed cachePost store +cacheNew-post eventsFan-out workersFollow graphGET /feedPOST /postsread listfill in postsinsertfollowerspush ids

request and replyasynchronous message

Posting is fast because fan-out happens in workers behind a queue, and reading a feed normally touches only caches.
A post reaches its followers, then a feed is readUse the arrows or ← → keys
  1. A post reaches its followers, then a feed is read, step 1Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cacheinsert p_901New-post eventsFan-out workersFollow graph

    1Maya, who has 200 followers, publishes a post. The post service gives it a time-sortable id and stores it.

  2. A post reaches its followers, then a feed is read, step 2Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cacheNew-post eventsFan-out workersFollow graph

    2The post service publishes a new-post event and replies 201 immediately.

  3. A post reaches its followers, then a feed is read, step 3Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cacheNew-post eventsFan-out workersFollow graph200 followers
    followers
    200
    active
    170

    3A fan-out worker reads Maya's 200 followers and skips the 30 who have been inactive for a month.

  4. A post reaches its followers, then a feed is read, step 4Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cache+p_901 ×170Post store +cacheNew-post eventsFan-out workersFollow graph
    followers
    200
    active
    170
    inserts
    170

    4The worker adds p_901 to the 170 feed lists in batches. Followers see it about 2 seconds later.

  5. A post reaches its followers, then a feed is read, step 5Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cache20 idsPost store +cacheNew-post eventsFan-out workersFollow graph
    page
    1
    ids
    20

    5Leo, one of the followers, opens the app. The feed service reads the first 20 ids of his feed list and his cached list of followed accounts.

  6. A post reaches its followers, then a feed is read, step 6Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cache3 big accountsNew-post eventsFan-out workersFollow graph
    page
    1
    ids
    20
    merged from
    1 + 3 lists

    6Leo follows 3 very large accounts. The feed service reads their cached newest post ids and merges them into the list by id.

  7. A post reaches its followers, then a feed is read, step 7Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cachemulti-get 20New-post eventsFan-out workersFollow graph
    page
    1
    ids
    20
    cache hits
    20

    7The feed service fetches the 20 post bodies from the post cache in one batch, drops any that are deleted, and builds the page.

  8. A post reaches its followers, then a feed is read, step 8Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cacheNew-post eventsFan-out workersFollow graph
    page
    1
    returned
    20
    next_cursor
    after p_655

    8Leo receives 20 posts and a cursor. It needed only cache reads, so it finishes well under 200 ms.

  9. A post reaches its followers, then a feed is read, step 9Mobile app to Feed service; Mobile app to Post service; Feed service to Feed cache; Feed service to Post store + cache; Post service to Post store + cache; Post service to New-post events, asynchronous; New-post events to Fan-out workers, asynchronous; Fan-out workers to Follow graph; Fan-out workers to Feed cache.Mobile appFeed servicePost serviceFeed cachePost store +cacheNew-post eventsbacklogFan-out workersbehindFollow graph

    9Now the fan-out workers fall behind and the queue backs up. Reading feeds and publishing posts still work, but new posts appear in feeds late.

1 / 9

Deep dives

Fan-out on write, fan-out on read, or both

This is the question interviewers care about most: when is the work of collecting posts into a feed done? Each of the two basic choices fails in a different place.

Fan-out on write, also called push, copies the id of each new post into the feed list of every follower at the moment it is published. A feed read is then a single list lookup, and the cost of a post is paid once, in the background. The cost is write amplification: a post by an account with 50 million followers causes 50 million inserts, many for people who will not open the app soon. If the fan-out fleet can do 200,000 inserts a second, that one post takes 5 × 107 ÷ 2 × 105 = 250 seconds, and every post queued behind it is delayed by the same amount.

Fan-out on read, also called pull, stores nothing per reader. When a user opens the app, the feed service fetches the newest posts of every account they follow and merges them. Publishing is one write, and nothing is spent on inactive users or on large accounts. The cost moves to the read path: each feed open reads about 200 author lists, so the peak of 36,000 opens a second becomes 36,000 × 200 = 7.2 million list reads a second.

The hybrid uses push for ordinary accounts and pull for accounts above a follower threshold. A feed read takes one pushed list and merges in the cached recent posts of the large accounts the user follows.

Summary of how posts get into feeds
OptionGood atBad atPick it when
Fan-out on write (push)A feed read is one list lookup, and the work is done once per post.A post from a huge account causes tens of millions of writes, many for followers who never open the app.Follower counts are small and capped, as in a private friends network.
Fan-out on read (pull)Posting is one write, and no work is wasted on inactive users or huge accounts.Every feed open merges hundreds of lists, and reads are 100 times more frequent than writes.Feeds are opened rarely, or users follow very few accounts.
Hybrid Usual defaultBoth the write cost and the read cost are bounded.There are two code paths and a threshold to tune.Follower counts are heavily skewed, which is the case for almost every social network.

Choose the threshold from the cost of a push. With a threshold of 100,000 followers, one post costs at most 100,000 inserts, which is half a second of the fleet's capacity, and a pull covers only the few large accounts a user follows.

Two refinements matter in practice. A user who has been inactive for 30 days gets no inserts, and their feed is built once by pull when they return.

Feed storage and pagination

Each feed holds up to 500 ids in a set sorted by post id. Fan-out workers can finish out of order and a queue redelivers events after a crash, and a sorted set puts a late post in the right position and ignores a repeated insert, which makes fan-out safe to retry (see Idempotency and Retries). When a user scrolls past the 500 stored ids, the feed service falls back to pulling from author_posts.

Page numbers fail because the feed changes while the user reads it, as the following trace shows.

Page numbers versus a cursorUse the arrows or ← → keys
  1. feed
    090
    188
    285
    381
    477
    574
    670
    766
    page
    1
    shown
    90 88 85 81

    1Leo's feed is shown newest first with a page size of 4. Page 1 is positions 0 to 3, which hold posts 90, 88, 85 and 81.

  2. feed
    095
    193
    290
    388
    485
    581
    677
    774
    870
    966
    page
    1
    shown
    90 88 85 81

    2While Leo reads, posts 95 and 93 arrive at the top, and every older post moves down by 2 positions.

  3. feed
    095
    193
    290
    388
    485
    581
    677
    774
    870
    966
    page
    2
    shown
    85 81 77 74
    duplicates
    2

    3The request ?page=2 skips 4 posts and returns positions 4 to 7, which are 85, 81, 77 and 74. Leo sees 85 and 81 twice.

  4. feed
    095
    193
    290
    388
    485
    581
    677
    774
    870
    966
    cursor
    after 81
    shown
    77 74 70 66
    duplicates
    0

    4With a cursor, page 1 ended with the cursor "after 81". The server returns the next 4 ids below 81, which are 77, 74, 70 and 66, so there are no duplicates.

1 / 4

A cursor holding the last post id works while ids sort by time. Ranked order depends on scores that change as posts receive likes, so the feed service ranks once per session and caches the order for about 10 minutes, and the cursor becomes a snapshot id plus a position. If the snapshot has expired, the server returns 400 and the app starts again from the top.

Ranking

Ranking is one stage of the read path with a budget of about 50 ms of the 200 ms. It takes the roughly 500 candidate ids, removes deleted posts, blocked authors and posts already seen, scores each remaining post with a model that predicts engagement, and limits any one author to 2 posts in a row. If the ranking service is down, the feed service returns the chronological feed.

What to cache

Feed lists take about 800 GB and are replicated. The last two days of post objects, about 2 × 10 GB = 20 GB, serve most reads through cache-aside, with the entry deleted on edit or delete. The recent posts of huge accounts are also copied into each feed server's memory for a few seconds, so that one cache node does not take every read.

Bottlenecks and failures

What breaks first at 10x

At ten times the load there are 360,000 feed reads and about 690,000 fan-out inserts a second at peak, and the feed data grows to about 8 TB. The feed cache is partitioned by user id with consistent hashing, and the fan-out queue is partitioned by author so that more workers can be added. The first things to fail are the hot keys of huge accounts, fixed with local copies, and the fan-out fleet, relieved by lowering the threshold.

A feed cache node fails

The feed lists on that node are lost, and its replica takes over automatically. If both are lost, the affected feeds are rebuilt by pull from following and author_posts.

Fan-out workers fall behind or fail

New posts stop appearing in feeds and the queue grows, but reading feeds and publishing posts continue to work because they do not depend on the workers. When the workers recover they process the backlog oldest first.

The post store, the ranking service or the follow graph is unavailable

If the post store is down, publishing fails and the client retries, while feed reads return the posts that are in the post cache and leave out the rest. If the ranking service is down, the feed service stops calling it after a short timeout and returns the chronological feed. If the follow graph is down, cached follower lists let fan-out continue for recently seen accounts, and the other events wait in the queue.

What a strong answer sounds like

LevelWhat the answer does
JuniorThe answer queries the posts of followed users when the feed is opened, and needs a hint to see that this means millions of list reads a second.
Mid-levelThe answer uses fan-out on write with a feed cache, a queue and cursor pagination.
SeniorThe answer asks about the distribution of follower counts and puts numbers on both fan-out options. It justifies a hybrid threshold, skips inactive users, stores ids, and covers each failure.
The celebrity questionStrong answer
Interviewer

An account with 50 million followers publishes a post. Walk me through what happens.

You

Pure push would mean 50 million inserts. At 200,000 inserts a second that takes about four minutes, and every other post would wait behind it. So accounts above 100,000 followers are not pushed. The post is stored and added to that account's cached recent-posts list, and followers' feeds merge that list in when they are read.

Interviewer

What does that cost on the read side?

You

Each feed open makes a few extra cached list reads, one for each large account the user follows. If a user followed hundreds of such accounts, I would cap the pulled lists per read and push the rest.

Follow-up questions

What happens when a user unfollows an account, or a post is deleted?

On an unfollow, the feed service removes that author's ids from the user's feed list, and the read path also drops ids from authors the user no longer follows, in case a fan-out in flight adds one afterwards. A deleted post is marked as deleted and its cache entry is removed. The id stays in the feed lists and is dropped when post bodies are filled in, so a delete never touches millions of feeds.

How would you run this in two regions?

Each region serves feeds from its own caches and runs its own fan-out, and posts and follows are replicated asynchronously. A post reaches the other region a second or two later, which fits eventual consistency.

What does a user see when they follow nobody, or have just signed up?

The feed list is empty, so the feed service falls back to pulling. For a new user it shows recent posts from a default set of popular accounts, or from accounts suggested during sign-up. When the user follows an account, its recent post ids are added to the feed list at once.

How do you show like counts without slowing the feed down?

The counts are kept in a separate counter store and are not part of the post object, so a like never invalidates a cached post. The count may lag by a few seconds, which fits eventual consistency.

An account crosses the follower threshold. What changes?

New posts from that account switch from push to pull. Older posts are already in the followers' feed lists and stay there, so no data has to be moved. During the transition the read path merges both sources and drops duplicate ids.

Self-review: news feed0 of 14

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure

What to practise next

The fan-out queue is a partitioned stream, which Message Queues and Streams explains. For instant delivery instead of a feed that is read on demand, try Design a Chat App.