Video in progress

Strong Middle 🏗️ System design

What is the difference between fan-out on write and fan-out on read when building a news feed? How do you handle a user with millions of followers?

With fan-out on write, a post is added to each follower's ready-made feed when it's written — reads are fast, writes are expensive. With fan-out on read, the posts of the people you follow are gathered when the feed is opened — writes are cheap, reads are heavy. In practice it's a hybrid: write for ordinary users, read for "stars".

📖 Answer

Push (fan-out on write). Ali wrote a post and has 300 followers. A worker adds the post ID to each one's feed in Redis (a feed:{userId} sorted set). Opening the feed is just a ZREVRANGE — milliseconds.

The problem: a blogger with 5 million followers. One post means 5 million writes, the workers are busy for minutes, and the last followers see the post late. And most of the followers never log in at all — the work is done for nothing.

Pull (fan-out on read). When the feed is opened: take "the latest posts of the 500 people I follow" and merge them by time. Writes are cheap, but every open reads from 500 sources — slow and heavy on the DB.

That's why in practice it's done as a hybrid:

  • users with, say, fewer than 10,000 followers — push;
  • those with more — their posts aren't written into feeds;
  • when the feed is opened: the ready-made feed is merged with the latest posts of the "stars" you follow (there are few of them, and their posts stay hot in the cache).

Extra practical points:

  • the feed stores only IDs, and the post text comes from a separate cache;
  • the feed length is capped (for example, the last 800), older ones come from the DB if needed;
  • don't push to users who haven't logged in for a long time, rebuild the feed when they come back;
  • if a post is deleted — no need to remove it from feeds immediately, filtering at display time is enough.

If the feed is ranked (not by time), at the last stage the set of candidates goes through a ranking service, but collecting the candidates is still the scheme above.