Fan-Out and the Twitter Timeline Problem

Build a feed by merging at read time or by copying each post to followers at write time; how Twitter chose between them in 2012, and why accounts with huge followings need a hybrid.

Overview

Fan-out means one event has to reach many places. In a social app, one post has to appear in the home timeline of every follower. You can do that work when someone reads a timeline, or when someone posts. Which is cheaper depends on the load parameters, mainly how often people read compared with how often they post, and how many followers each poster has.

Twitter's home timeline is the classic worked example. In a 2012 talk, Twitter's slides gave about 400 million tweets a day, which is about 5,000 new tweets a second on an average day (over 12,000 during big events), against more than 300,000 home timeline queries a second. Reads outnumbered writes by roughly 60 to 1.

Two ways to build a home timeline

With fan-out on read (pull), a post is written once, to the posts store. When a user opens their timeline, the system looks up everyone they follow, fetches their recent posts from the posts store and merges them by time, all while the user waits. With fan-out on write (push), each new post goes onto a fan-out queue, and background workers insert its ID into a precomputed timeline list for every follower, one list per user. Reading a timeline is then a single lookup of one list.

The two approaches put the cost in opposite places.

  • Cost of a post: pull does one insert. Push does one insert per follower.
  • Cost of a read: pull looks up every followed account and merges. Push reads one precomputed list.
  • Read latency: with pull it grows with how many accounts you follow. With push it is low and steady.
  • Freshness: pull is always current. Push is delayed until the fan-out finishes.
  • Storage: pull stores posts only. Push stores posts plus a copy of each post ID per follower.

Pull works well when writes are common and reads are rare. Push works well when reads far outnumber writes.

Key concepts

  • Fan-out
  • Fan-out on read (pull)
  • Fan-out on write (push)
  • Hybrid fan-out
  • Write amplification
  • Hydration
  • Load parameters

Interview questions

  • How would you design a home timeline for a Twitter-like service?
  • When is fan-out on read the better choice?
  • How do you choose the follower threshold for the hybrid, and what goes wrong at the boundary?
  • What happens if the fan-out pipeline falls behind?

Sign up free to read the full topic

More DDIA topics

Start free on Cariara · Coding problems · System design studio