Messaging and async

Fan-out on write vs fan-out on read

How to build a timeline by precomputing it when someone posts or assembling it when someone reads, and why real feeds mix the two.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A social network shows each user a home timeline: recent posts from everyone they follow, newest first. The first version is one query.

SELECT p.* FROM posts p
JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = :me
ORDER BY p.created_at DESC
LIMIT 50;

At small scale this is fine. As the service grows it becomes the most expensive query in the system and also the most frequent, because opening the app is what users do most. Someone who follows 2,000 accounts needs the latest posts of 2,000 authors merged and sorted on every refresh. Once posts are sharded by author, that is a scatter-gather across many shards.

Twitter went through exactly this. As its engineers described in 2012, the service took about 4,600 new tweets per second on average and about 300,000 home timeline reads per second. Reads outnumbered writes by roughly 65 to 1, and the read was the expensive operation. So they moved the work. When a tweet was posted, they inserted its ID into a cached timeline for every follower, and a read became a single cache lookup. With an average of 75 followers per user, 4,600 tweets per second became about 345,000 cache writes per second, a good price for a cheap read.

Then the averages stopped helping. Some accounts had more than 30 million followers, and one tweet from one of them meant 30 million writes.

Doing the work at read time is fan-out on read, or pull. Doing it at write time is fan-out on write, or push. This lesson covers both, and what to do at the extreme.

Fan-out on read (pull)

Store each post once, indexed by author. To build a timeline, fetch the reader’s follow list, fetch recent posts for each followee, merge them by time and return the top page.

  • Writes are cheap and constant. One insert, however many followers the author has.
  • Reads are expensive and variable. The cost grows with the number of accounts the reader follows.
  • It is always fresh. There is no copy to fall behind, and a delete or an unfollow takes effect at once.
  • Nothing is spent on inactive users. A timeline is computed only when someone asks for it.

Choose it when reads are rare relative to writes, when most precomputed timelines would never be looked at, or as the starting design for a small system.

Fan-out on write (push)

Keep a precomputed timeline per user, typically a capped list of post IDs in a cache such as Redis. When someone posts, store the post once, then append its ID to the timeline of each follower. A read fetches the list and hydrates the IDs into posts.

The fan-out does not happen inside the post request. The post service writes the post, puts a job on a queue or log, and returns. Workers do the per-follower writes asynchronously. That is why fan-out belongs in a module about messaging: the queue absorbs bursts, the workers scale separately, and a backlog of fan-out jobs is a backpressure problem.

  • Reads are cheap and predictable. One lookup, whatever the reader follows.
  • Writes are amplified. One post costs as many writes as the author has followers.
  • Timelines are eventually consistent. A follower sees the post when the fan-out reaches them, usually within seconds.
  • Work and memory go on users who never look. A timeline is maintained for every follower, active or not.
  • Changes are awkward. Unfollows, deletes and privacy changes must be filtered at read time or cleaned out of many lists.

Choose it when reads far outnumber writes and follower counts are moderate, which describes most users of most feed products.

The celebrity problem

Push breaks at the top of the follower distribution, which is heavily skewed: most accounts have a few hundred followers and a few have tens of millions. It is the hot-key problem on the write path.

Take an account with 50 million followers. One post is 50 million timeline writes. At 100,000 writes per second, that is more than 8 minutes of the fan-out tier’s whole capacity for a single post. Three things go wrong:

  • Delay. Followers receive the post minutes apart, and everyone else’s fan-out queues behind it.
  • Disorder. A reply from an ordinary user can reach a timeline before the celebrity post it answers.
  • Waste. Most of those 50 million followers will not open the app before the post has scrolled out of their capped timeline.

Pull has no such problem on the write side. It has the mirror image on the read side: a reader who follows 5,000 accounts pays for all of them on every refresh.

Hybrid fan-out: push for most authors, pull for celebrities9 components: Ordinary author, Celebrity, Post service, Fan-out queue, Posts store, Fan-out workers, Timeline cache, Feed service, Reader. Connections: Ordinary author to Post service; Celebrity to Post service; Post service to Posts store (store post); Post service to Fan-out queue (fan-out job); Fan-out queue to Fan-out workers; Fan-out workers to Timeline cache (push post ID); Feed service to Timeline cache; Feed service to Posts store (pull celebrity posts); Reader to Feed service.Ordinary author300 followersCelebrity50 million followersPost serviceFan-out queuePosts storeindexed by authorFan-out workersTimeline cachepost IDs per userFeed serviceReaderstore postfan-out jobpush post IDpull celebrity posts

Step 1 of 8

An ordinary author with 300 followers publishes a post. The post service writes it once to the posts store and answers the author straight away. Nothing else happens on the request path.

Read the steps as text
  1. An ordinary author with 300 followers publishes a post. The post service writes it once to the posts store and answers the author straight away. Nothing else happens on the request path.
  2. The post service also puts a fan-out job on a queue. Workers look up the 300 followers and push the post ID onto each follower's cached timeline. This is fan-out on write: 300 small writes for one post.
  3. When one of those followers opens the app, the feed service reads a ready-made list of post IDs from the cache and then fetches the post bodies. The read is one cheap lookup, however many accounts the reader follows.
  4. Now a celebrity with 50 million followers posts. Fan-out on write would mean 50 million cache writes for one post. Even at 100,000 writes a second that takes more than eight minutes, and it delays every other author's fan-out queued behind it.
  5. So the post service checks the follower count and skips the queue for this author. The post is stored once in the posts store, indexed by author, and nothing is pushed to any timeline.
  6. The cost moves to the read. When a reader opens the app, the feed service takes their precomputed timeline and also fetches recent posts from the few celebrities they follow. This second part is fan-out on read.
  7. The feed service merges the two lists by time or by rank and returns one page. A reader follows only a handful of celebrities, so the extra work is a few lookups, and those popular posts are easy to cache.
  8. Push for the many authors with few followers, and pull for the few authors with many. Each post is written a bounded number of times and each read does a bounded number of lookups, so neither path has to carry the worst case of the other.
Hybrid fan-out: push for most authors, pull for celebrities

Hybrid approaches

Real feeds mix the two, so that each case is handled by the model that makes it cheap.

  • Split by author. Push for authors below a follower threshold. Above it, skip fan-out, and have the feed service pull those authors’ recent posts at read time and merge them in. A reader follows few celebrities, so the pull is a handful of lookups, and a celebrity’s recent posts are read so widely that they cache well.
  • Split by reader. Push only to followers who have been active recently, say in the last 30 days. When a dormant user returns, build their timeline by pull and cache it.
  • Store IDs, not content. Timelines hold post IDs. Bodies, counts and media are fetched at read time, so edits and deletes need no second fan-out.
  • Cap the list. Keep only the newest few hundred entries per user. Twitter’s description from that period gave 800. Anyone who scrolls past the cap falls back to pull.

Cost analysis with numbers

Assume 200 million daily active users. Each follows 200 accounts and so, on average, has 200 followers. Each posts once every two days and opens the feed 10 times a day.

Push Pull
Posts per second about 1,160 about 1,160
Work per post 200 timeline writes 1 write
Write work per second about 232,000 about 1,160
Feed reads per second about 23,000 about 23,000
Work per read 1 lookup about 200 lookups and a merge
Read work per second about 23,000 about 4.6 million

Push does about a quarter of a million small writes per second in the background. Pull does 4.6 million lookups per second on the request path, where latency matters. With 20 reads for every post, push wins clearly. The picture reverses only where an author’s follower count is huge or a reader is rarely active, and those are the cases the hybrid carves out.

Memory is the other cost. A timeline of 800 eight-byte IDs is 6.4 KB. For 200 million users that is about 1.3 TB before replication and overhead, which is a strong reason to cache timelines for active users only.

Beyond feeds

The same choice appears wherever one write is seen by many readers. Group chat can deliver a message to each member’s inbox in a small group, and have members pull from a shared channel log in a very large one. Notification systems expand “notify everyone who follows this team” at send time. A materialised view is fan-out on write, and a join at query time is fan-out on read. The deciding questions are always the read-to-write ratio and the size of the largest fan-out.

In the interview

For any feed or timeline design, name both models in your first minute and then choose with numbers: “Reads outnumber writes by about 20 to 1 and typical follower counts are in the hundreds, so I precompute timelines on write, asynchronously through a queue.” Raise the celebrity problem before the interviewer does, and give the hybrid: push below a threshold, pull and merge above it, and skip inactive followers. Close with what you gave up: timelines are eventually consistent, and deletes are filtered at read time. The news feed case study works through the full design.

Key takeaways

  • Fan-out on read stores a post once and assembles each timeline at request time: cheap writes, expensive reads.
  • Fan-out on write copies a post ID into every follower's precomputed timeline: cheap reads, writes amplified by follower count.
  • Fan-out on write runs asynchronously behind a queue, so timelines are eventually consistent.
  • A celebrity post is one write multiplied by tens of millions of followers. It delays everyone's fan-out and mostly updates timelines nobody will read.
  • Hybrid designs push for ordinary authors, pull for celebrities and merge at read time, and skip inactive followers.
  • Choose with numbers: the read-to-write ratio and the largest fan-out decide which side should carry the work.

Check yourself

1. A service takes 500 new posts per second, and authors have 400 followers on average. With pure fan-out on write, how many timeline writes per second does the fan-out tier perform?
2. Why is pure fan-out on write a poor fit for an account with 80 million followers?
3. In a hybrid design, why is pulling celebrity posts at read time cheap enough?
4. An internal tool has 50 analysts who occasionally open a feed built from 10,000 event sources that each post many times a minute. Which model fits?
5. A user deletes a post whose ID has already been fanned out to 2 million cached timelines. What is the cheapest correct way to handle it?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Fan-out on read in one sentence?

Store each post once and build a timeline at request time by fetching and merging recent posts from everyone the reader follows.

Fan-out on write in one sentence?

When a post is created, asynchronously append its ID to a precomputed timeline for each of the author's followers, so a read is a single lookup.

What is the celebrity problem?

An author with millions of followers turns one post into millions of timeline writes, which takes minutes, delays other fan-out and is mostly wasted. It is a hot key on the write path.

Describe the usual hybrid.

Push for authors under a follower threshold; for authors above it, skip fan-out and pull their recent posts at read time, merging them into the precomputed timeline.

Why do timelines store post IDs and not content?

IDs are small, so timelines are cheap to cache, and content is fetched at read time, so edits and deletes need no second fan-out.

What two numbers decide between push and pull?

The ratio of feed reads to posts, and the size of the largest fan-out (follower count for push, followee count for pull).

Review the deck