← Building blocks

Precompute on write, read cheaply

Latency & performancesenior

Assembling a page at read time (a feed, a dashboard) is too slow.

Say it like this

Reads are far more frequent than posts, so I do the work at write time by fanning each post into the timeline cache of every follower, and a feed read becomes one range query.

Basic solution

Do the work when the data changes and store the result per user, so a read is a single fetch (fan-out on write).

Redis lists / sorted setsbackground workersKafka consumers

Fan-out on write with a celebrity bypass

A post event goes to fan-out workers that write the post id into each follower timeline. Posts from very large accounts skip the workers and are pulled at read time, then merged.

How it works

  1. A user creates a post. The post service writes it to the posts store and publishes a post-created event containing the post id, the author id and the timestamp.
  2. A fan-out worker consumes that event, fetches the author's follower ids from the graph service a page at a time, and for each follower runs ZADD home:{follower} with the post id as the member and the timestamp as the score. Each follower's home timeline is a sorted set of post ids ordered by time.
  3. After adding, the worker trims each sorted set to a fixed length, for example 800 ids, so the memory per user never grows beyond that.
  4. A feed read runs ZREVRANGE home:{user} 0 19 to get the 20 newest post ids, then fetches those post bodies and the author profiles in one batched call to the caches, then drops any post that is deleted or whose author the user has since unfollowed.
  5. Authors with more followers than a threshold are skipped by the workers entirely. At read time the feed service fetches the recent posts of each such author the user follows and merges them into the list by timestamp.

Why the timeline holds ids, not bodies

  • An edit or a delete changes one post entry in the post cache rather than every timeline that references it, and each timeline entry is about 8 bytes instead of a kilobyte of text.

Worked example

News feed

  • 100M DAU, 10M posts/day, average 200 followers, 5 feed reads per user per day.
  • Writes: 10M × 200 = 2B ZADDs/day ≈ 23K/s average, ~70K/s at peak. Redis handles ~100K ops/s per node, so a small cluster of a few shards.
  • Reads: 500M/day ≈ 6K/s average. Each read is one ZREVRANGE plus one MGET, both sub-millisecond, instead of a merge across 200 followees' posts.
  • Memory: 100M users × 800 ids × ~10 B of payload ≈ 800 GB, and a Redis sorted set adds roughly 50 to 100 B of overhead per entry, so plan for several TB across the cluster before trimming inactive users (drop timelines for users inactive 30 days and rebuild on return).
  • The celebrity cut-off: an author with 20M followers would cost 20M ZADDs per post; at 70K/s that is 5 minutes of the whole cluster. So above ~10K followers, pull instead: at read time fetch each followed celebrity's last 20 posts (one cache read each, typically fewer than 10 celebrities per user) and merge.

Variants and when each wins

Fan-out on write (push)

  • Every post is copied into every follower's timeline at write time. Reads are a single range query and as fast as they can be; writes are heavy for popular authors and wasted on readers who never come back.

Fan-out on read (pull)

  • At read time the feed service fetches recent posts from everyone the user follows and merges them. There is no write amplification, but each read costs one fetch per followee and gets slow past a few hundred.

Hybrid

  • Push for ordinary authors, pull for celebrities above a follower threshold, and merge the two at read time. It wins at Twitter scale because it keeps both the write cost and the read cost bounded.

Push to active users only

  • Fan out only to users seen in the last N days, and rebuild a dormant user's timeline by pull when they return. It wins by cutting write and memory cost by the inactive fraction of users, which is often most of them.

Recommendation: hybrid with an active-user filter; state the follower threshold and that it is tunable.

Failure modes

Celebrity post stalls the workers

  • You notice fan-out lag climbs to minutes right after a famous account posts, and ordinary users' posts arrive late. It happens because one event turned into millions of ZADDs on the same worker. Fix it with the celebrity threshold so those posts are pulled at read time instead, and by paging the follower list across many workers so no single worker owns a huge fan-out.

Deleted post still in timelines

  • You notice a removed post keeps showing in feeds. It happens because its id was already copied into thousands of timelines and the delete did not visit all of them. Fix it by filtering at read time: the post fetch returns "deleted" and the feed service drops the id, rather than chasing every timeline.

Unfollow leaves old posts

  • You notice a user keeps seeing an author they unfollowed. It happens because that author's post ids are still in the user's sorted set. Fix it by removing that author's ids from the set on unfollow (ZREM), or by filtering against the user's current following set at read time.

Fan-out worker loses events

  • You notice a post never appears in some timelines. It happens because the worker crashed partway through a fan-out and the event was consumed at-most-once, so the remaining followers never got it. Fix it by consuming from a durable log and committing the offset only after the whole batch is done, and by making ZADD idempotent (the same id with the same score can be re-applied safely).

Memory growth

  • You notice Redis starts evicting timelines. It happens because sorted sets were never trimmed, or because inactive users' timelines are kept forever. Fix it by trimming to the cap on every write (ZREMRANGEBYRANK) and expiring the timelines of users who have not logged in for a while.

Interviewer follow-ups

Answer out loud before you open each one.

How do you pick the follower threshold for celebrities?

From the write budget: the number of ZADDs per post you can afford at peak without delaying ordinary fan-out, divided by posts per second from large accounts. It starts around 10K followers and is tuned from fan-out lag metrics; it should be a config value, not a constant.

What happens when a user who has been inactive for a year opens the app?

Their timeline cache has been expired, so the feed service falls back to pull: fetch recent posts from their followees, merge, rank, and write the result back as a fresh timeline. The first load is slower; subsequent loads are push-fed again.

How is the merged timeline kept sorted when celebrity posts are pulled in?

Both sources produce (post id, timestamp) pairs. The pushed timeline is already sorted; the celebrity lists are small and sorted per author. A k-way merge by timestamp over a page worth of candidates costs microseconds, and ranking then reorders the top candidates anyway.

Why not store the whole rendered feed per user?

Because any edit, delete, or profile change would have to touch every rendered copy, and each copy would be kilobytes instead of bytes. Storing ids and hydrating from shared caches keeps the write path small and makes filtering at read time possible.

Connections

In study paths
Feeds and fan-out
Built on
Skip list
Pairs with
Fan one event out to many consumers · Keep events as a replayable log · Precompute joins · Fix a hot shard · Rank instead of sorting by time
Pulls against
Know your write amplification · Delete without losing history
Used in
News Feed (Twitter / X timeline)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingPost service, Fan-out workers, Feed serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon MSK (Kafka)Post eventsManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon ElastiCacheTimeline cache, Celebrity recent postsMemorystoreAzure Managed RedisRedis, Valkey, Memcached