AI Hints
Home›System Design Tutorial›Case Study: Feeds and Notifications
System Design · Lesson 100 of 120

News Feed: Fan-Out

Push or pull.

⏱ 2 min read▶ Video at 2:01:22🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

There are two ways to build feeds. Do the work when someone posts, called fan out on write, or push. Or do the work when someone reads, called fan out on read, or pull.

News Feed: Fan-Out
From the video: News Feed: Fan-Out
  • Work when posting?
  • Or when reading?
  • Push or pull

Push vs pull

With push, when Sam posts, the post ID is added to every follower's feed list, ahead of time. Reading a feed is then instant. But a celebrity with fifty million followers creates fifty million writes per post. With pull, nothing happens on post. Each reader collects posts when they open the app. Writes are cheap, but reads are slow.

Push: fan-out on write

  • Feeds pre-builtReads instantCelebrities are costly

Pull: fan-out on read

  • Nothing pre-builtWrites cheapReads slow

The hybrid approach

Most big feeds use a hybrid. Posts from normal users are pushed into followers' feeds. Posts from celebrities are pulled, and mixed in at read time. Here, Priya follows Sam, Alex, and a celebrity. Run it. Her pre built feed holds Sam and Alex's posts, the celebrity's posts are merged in when she reads, and everything is sorted by time.

hybrid.pypython
CELEBS = {"star"}
posts = {"sam": [(5, "sam: lunch!")], "alex": [(3, "alex: new job")],
         "star": [(6, "star: tour dates"), (2, "star: hello fans")]}
follows = {"priya": ["sam", "alex", "star"]}

# push: written into priya's feed when each post was made
prebuilt = [p for u in follows["priya"] if u not in CELEBS for p in posts[u]]

# pull: celebrity posts fetched at read time
pulled = [p for u in follows["priya"] if u in CELEBS for p in posts[u]]

for t, text in sorted(prebuilt + pulled, reverse=True):
    print(t, text)
Output
6 star: tour dates
5 sam: lunch!
3 alex: new job
2 star: hello fans

Summary

Push pre builds feeds for fast reads, pull builds them at read time, and the hybrid pushes normal posts and pulls celebrity posts. Next, ranking and caching the feed.

Key takeaways
  • Push: fast reads
  • Pull: cheap writes
  • Hybrid for celebrities
Next up: News Feed: Ranking and Cache — the final feed