Day 12 B-Building blocks 2026-10-08 ← All lessons

Design a news feed: push vs pull, fan‑out on write vs read

One person posts a photo. Hundreds or thousands of friends should see it at the top of their home page, newest first. The post has to be copied into all of those feeds at some point. You can do the copying when the post is written, or when each friend opens the app. That one choice decides where your system strains.

10Mpeople open the app every day in this design
5,000friends a single user is allowed to have
1 → 5,000copies one post can turn into if you copy it into every friend's feed
5separate caches the finished design leans on

Key points

Outcomes

01State the six scoped requirements and point at the one that makes publishing expensive.
02Trace a post from the publish request to a friend's feed cache, naming each service and what it owns.
03Predict the write cost and wasted work of push and pull for a given follower count, then choose between them.
04Break down a feed read into the ID lookup and the hydration step, and say why the feed cache holds only IDs.
05Write a fan-out worker that skips high-follower authors and merges their posts in at read time.
01

The problem: one post, thousands of readers


Ch. 11 starts the way a real interview starts: with questions before boxes. The interviewer's answers become the requirements. They are numbered here so later sections can say exactly which one a design choice is fighting.

Requirement (4) is the one that hurts. Storing a post is one write. Getting it in front of every friend can mean up to 5,000 more, one per friend, because each friend's feed is a separate list. Requirement (5) multiplies that by every post published across 10 million daily users.

Requirement (3) helps. With no ranking model, a feed is just "posts from my friends, newest first." That keeps the whole problem about moving data, not scoring it.

The API surface is small. Ch. 11 names two HTTP endpoints:

ActionRequestParams
Publish a postPOST /v1/me/feedcontent (the post text), auth_token
Read your feedGET /v1/me/feedauth_token
02

The mental model: deliver to every mailbox, or let readers come and get it


Picture a club newsletter. One way to run it: the moment an issue is printed, you stuff a copy into every member's mailbox. Members get it instantly when they check their mail. But you printed and delivered copies for members who are away for months and will never look.

The other way: you pin one copy on the clubhouse board. Nothing is delivered. Each member who wants news walks over and reads every board they care about. No wasted copies, but every member spends time gathering, every single time.

The first is fan-out on write, also called push. The second is fan-out on read, also called pull. Fan-out just means one thing spreading to many places: one post, many feeds.

Say it this wayPush does the work at write time so reads are cheap. Pull does the work at read time so writes are cheap. The design question is never "which is better," it is "who can afford to pay."
03

Publishing, step by step: persist once, then spread


Here is the publish path from Ch. 11's detailed design. The important split: the post service stores the post exactly once, and the fan-out service is the only part that knows about friends.

How to use: press Next to move one hop at a time, or Play to run it. Lit boxes and moving arrows are the work on that step. Follow post p_9012 from one write to three feeds.

Clientweb or mobile Web serversauth + rate limit Post servicestores the post Post cache + DBthe one real copy Graph DBfriend IDs Fan-out serviceknows about friends User cachemutes, settings Notification servicetells friends Message queuejobs waiting Fan-out workersdo the copying News feed cache amy p_9012 cy p_9012 dee p_9012 eli muted p_9012: Hello response amy, cy, dee, eli eli muted: drop job: p_9012 for amy, cy, dee sync: the author waitsasync: the author already has a response Clientweb or mobile Web serversauth + rate limit Post cache + DBthe one real copy Post servicestores the post Graph DBfriend IDs Fan-out serviceknows about friends User cachemutes, settings Notificationstells friends Message queuejobs waiting Fan-out workersdo the copying amy p_9012 cy p_9012 dee p_9012 eli muted News feed cache: one ID list per user p_9012: Hello amy, cy, dee, eli eli muted: drop job: p_9012 for amy, cy, dee sync: the author waitsasync: after the response
  1. The client sends POST /v1/me/feed with content=Hello and an auth token.
  2. Web servers reject anyone without a valid token, then rate-limit how many posts a user can make in a period. That limit is the spam and abuse guard.
  3. The post service writes the post into the post database and post cache. This is the only full copy of the post that will ever exist.
  4. The fan-out service fetches the author's friend IDs from a graph database, a store built for relationship lookups like this one.
  5. It loads those friends from the user cache and filters some out. If a friend muted the author, or the author shared the post with only some friends, those people are dropped. Here, eli muted the author.
  6. The filtered friend list and the new post ID go onto a message queue. The publish request can return now.
  7. Fan-out workers pull jobs off the queue and write the post ID into each friend's list in the news feed cache. Here that is three writes: amy, cy, and dee.
  8. The notification service tells friends there is something new and sends push notifications.
Proves: the post is stored once, and the expensive one-to-many copy happens behind a queue, after the author already got a response.

Two details are easy to skip and worth saying out loud in an interview.

The queue. Without it, the author's request would wait while thousands of feed writes finish. With it, the web tier returns as soon as the job is queued, and a burst of posts piles up in the queue instead of stalling the servers people talk to.

What gets copied. Workers do not copy the post. They copy its ID. Ch. 11 describes the news feed cache as a table of <post_id, user_id> pairs, appended to on every new post:

user_id (whose feed)post_id
amyp_9012
amyp_8840
cyp_9012
deep_9012

Illustrative rows. Post p_9012 appears three times, but it is three short IDs, not three copies of the text and photo. Ch. 11 also caps how many IDs each feed keeps, because almost nobody scrolls back through thousands of posts. The cap keeps memory small and the miss rate stays low.

04

Push vs pull, live: what one post costs


The publish path above is push. Now compare it against pull on the same post. Change who is posting and watch where the cost lands.

How to use: pick a model, then drag the follower slider from a normal user toward a celebrity. Drag the second slider to change how many followers actually open the app today. Watch the three counters and the dot grid.

Feed writes at publish

work done before anyone reads

Wasted writes

copies for people who never look

Pulls at read time

page loads that must fetch this author

written, then read written, never read pulled at read time no work

Proves: push cost grows with the author's follower count no matter who reads, and pull cost grows with how many followers actually show up. Each dot is 1% of followers. The hybrid cutoff of 10,000 followers is illustrative: Ch. 11 says "celebrities or users who have many friends" without naming a number.

Three things to notice while you play with it:

05

The tradeoff, and the hybrid that fixes it


Push

Fan-out on write

  • Feed is ready before the reader asks, so reads are fast.
  • New posts reach friends in near real time.
  • An author with a huge following triggers a huge burst of writes: the hotkey problem.
  • Feeds get built for people who rarely log in.
Pull

Fan-out on read

  • Nothing is spent on inactive users.
  • No hotkey problem: posting is the same cost for everyone.
  • Every page load gathers posts from scratch, so reads are slow.
  • The slow part sits on the path the user is staring at.

Ch. 11 picks a hybrid, and the reasoning is the part to repeat: fetching the feed fast matters most, so most users get push. For celebrities and users with very large followings, followers pull that author's posts on demand, so one post cannot overload the system.

At read time, a reader's feed becomes: the pushed IDs already in their cache, merged with recent posts pulled from the few high-follower accounts they follow, sorted newest first.

Ch. 11 also names consistent hashing as a help for the hotkey problem: it spreads cached data and requests more evenly across cache servers, so no single box takes all the load.

Where the hybrid still lies

06

Reading the feed: fetch IDs, then fill them in


The read path never touches the fan-out machinery. It reads a short list of IDs and then turns each ID into something a person can look at. That second step is hydration, and it is where most candidates go quiet.

How to use: press Next to walk one GET /v1/me/feed through the system.

Clientrenders JSON
Load balancerspreads requests
Web serversauth + rate limit
News feed servicebuilds the page
News feed cacheyour post IDs
User cachenames, pictures
Post cachepost content
CDNimages and video
  1. The client sends GET /v1/me/feed with its auth token.
  2. The load balancer hands the request to a web server.
  3. The web server calls the news feed service.
  4. The service reads this user's list of post IDs from the news feed cache. That is all the cache holds.
  5. It hydrates: author name and profile picture from the user cache, post text and image references from the post cache.
  6. The fully hydrated feed goes back as JSON. The client loads images and video straight from the CDN, which is where media lives for fast delivery.
Proves: the feed cache answers "which posts," and two other caches answer "what is in them." Keeping those apart is what keeps the feed cache small.
The trapStoring whole user and post objects in the feed cache to skip hydration. A popular post would be copied in full into thousands of feeds, and memory would explode. Ch. 11 stores IDs only for exactly this reason.

Five cache layers, five jobs

Ch. 11 calls the cache tier extremely important and splits it into five layers. Each one holds a different kind of data with a different read pattern.

LayerWhat it storesWhich path leans on it
News feedIDs of news feed postsevery feed read, step 4
Contentevery post's data; popular posts in a hot cachehydration, step 5
Social graphfollower and following relationshipsevery publish, when fan-out looks up friends
Actionwhether a user liked, replied to, or acted on a postrendering each post's state for this reader
Counterslike, reply, follower, following countsrendering, and updated on every action
07

The code: a fan-out worker with a celebrity escape hatch


A complete, runnable Python 3 model of the hybrid. Publishing enqueues and returns. A worker copies IDs into followers' capped feeds. Authors above a follower threshold skip the queue, and readers pull their posts at read time. The threshold is set tiny so the demo shows both paths.

fanout.py · python 3, no dependencies
# fanout.py: hybrid news feed in one process
from collections import defaultdict, deque
import itertools

FEED_CAP = 3          # IDs kept per feed (Ch. 11: a configurable limit)
CELEB_THRESHOLD = 3   # more followers than this: pulled, not pushed

clock = itertools.count(1)       # increasing id doubles as "newer"
posts = {}                       # post_id -> (author, text): the one real copy
by_author = defaultdict(list)    # author -> post ids, oldest first
followers = defaultdict(set)     # author -> users who follow them
feed_cache = defaultdict(deque)  # user -> post ids, newest first
queue = deque()                  # fan-out jobs: (post_id, author)

def follow(user, author):
    followers[author].add(user)

def is_celebrity(author):
    return len(followers[author]) > CELEB_THRESHOLD

def publish(author, text):
    pid = next(clock)
    posts[pid] = (author, text)
    by_author[author].append(pid)
    if not is_celebrity(author):
        queue.append((pid, author))   # enqueue, return right away
    return pid

def fanout_worker():
    while queue:
        pid, author = queue.popleft()
        for user in followers[author]:
            feed = feed_cache[user]
            feed.appendleft(pid)       # copy the ID, never the post
            while len(feed) > FEED_CAP:
                feed.pop()             # the cap keeps memory bounded

def read_feed(user):
    ids = set(feed_cache[user])        # pushed IDs, already waiting
    for author, fans in followers.items():
        if user in fans and is_celebrity(author):
            ids.update(by_author[author][-FEED_CAP:])   # pull at read time
    newest = sorted(ids, reverse=True)[:FEED_CAP]
    return [f"{posts[p][0]}: {posts[p][1]}" for p in newest]   # hydrate

# bo is an ordinary user; star has 4 followers, over the threshold
follow("amy", "bo")
for fan in ("amy", "cy", "dee", "eli"):
    follow(fan, "star")

publish("bo", "lunch?")
publish("star", "tour dates are out")
publish("bo", "never mind, ate already")
fanout_worker()

print("amy sees:", read_feed("amy"))
print("feed entries holding star's post:",
      sum(2 in f for f in feed_cache.values()))

Output

amy sees: ['bo: never mind, ate already', 'star: tour dates are out', 'bo: lunch?']
feed entries holding star's post: 0

The lines that matter:

08

Field guide: where this question shows up


Ch. 11 lists the common variants of this interview question. They share the same skeleton but stress different requirements, so the push and pull balance shifts.

PromptWhy it is the same problemWhat to emphasize
Facebook news feedThe source of Ch. 11's definition: status updates, photos, videos, links, and likes from people, pages, and groups you follow.Mutual friendships with a cap, so most authors are safely pushable. Pages are where large followings appear.
Instagram feedSame two flows: publish a post, read a feed of people you follow.Requirement (6) dominates. Media goes to a CDN; the feed only carries references.
Twitter timelineSame fan-out decision: copy each tweet to followers or gather at read time.Following is one-directional, so follower counts are not capped the way friends are. The celebrity path matters more.
09

Interview ears: the follow-ups you will hear


Q&A

Check your judgment


Q1Under pure push, an author with 2 million followers posts once. Only 5% of those followers open the app that day. What did that post cost?

Push writes to every follower at publish time, whether or not they show up. 95% of 2 million is about 1.9 million wasted copies.

Q2A teammate wants to store full post objects in the news feed cache so reads skip hydration. What breaks first?

The cap limits how many entries each feed keeps, not how big each entry is. IDs keep every entry tiny.

Q3Feed reads are fine for most users but slow for people who follow dozens of celebrities. Which part of the hybrid explains it?

Celebrity posts are never pushed. Their followers pay for them on every read, so the more celebrities you follow, the more each read gathers.

Q4The web tier stalls during a spike of new posts, even though the feed cache is healthy. What is the most likely missing piece?

Without the queue, each publish request waits for all its feed writes to finish, so a burst of posts ties up web servers.

Sources: Alex Xu, System Design Interview Vol. 1, Ch. 11: Design a news feed system (pp. 166-177). Ch. 11 reference [1]: Facebook help page, How News Feed Works.