Feeds and fan-out
Precomputing what users will read, and keeping it right when the source changes.
When you finish, you should be able to say
Explain hybrid fan-out and what happens to a cached timeline when a post is deleted.
The route
6 blocks (2 fundamental, 3 senior, 1 staff), then the practice problem.
- Precompute on write, read cheaplySenior
- Fix a hot shardSenior
- Precompute joinsFundamental
- Page results with a cursorFundamental
- Rank instead of sorting by timeStaff
- Protect against a cache stampedeSenior
- News Feed (Twitter / X timeline)
Next, step 1 adds Fan-out workers, Timeline cache (outlined). A box fills in when you tick “I can explain this” on the block that introduces it; plain boxes come from the problem itself.
The central idea: do the work on write so a read is one fetch.
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.
Adds to the design: Fan-out workers, Timeline cache
Check yourself: How do you pick the follower threshold for celebrities?
The celebrity problem is a hot partition; see it as one before solving it.
One partition takes most of the traffic (a celebrity, a popular tenant, a time-ordered key).
Say it like this: The celebrity partition is taking most of the writes, so I salt the key into sub-partitions and read them back together, trading a wider read for an even write load.
Adds to the design: Celebrity post keys
Check yourself: How do you detect a hot partition before it becomes an incident?
Per-partition throughput and latency metrics with an alert on the ratio of the hottest partition to the median. Many stores expose this directly, such as CloudWatch contributor insights for DynamoDB. Alert at 5× the median, which is well before saturation.
Feeds store copies on purpose; this is the discipline that keeps copies consistent.
A hot read path needs a multi-table join every time.
Say it like this: The home timeline is read a thousand times more than it is written, so I denormalise: each post is copied with its author name and avatar into the per-user feed row at write time, and the read is a single range scan with no joins.
Adds to the design: Posts store, Timeline cache, Graph service
Check yourself: How do you decide which fields to copy?
Copy what the page always shows and what changes rarely: post text, author handle, avatar URL. Leave out what changes constantly or is cheap to fetch in a batch: like counts, follow state. Every copied field is a future fix-up job, so copy the minimum that removes the join.
Infinite scroll over a changing list needs cursors, not offsets.
Users scroll long lists; OFFSET queries get slower the deeper they go.
Say it like this: Users scroll a long timeline, so I page by cursor rather than offset: the client sends the last (created_at, id) it saw, the query seeks past it on the index, and page 1,000 costs the same as page 1.
Adds to the design: Feed service
Check yourself: Why must the cursor include the id as well as the timestamp?
Timestamps collide, especially at millisecond resolution under load. Without a tiebreaker the comparison created_at < cursor either skips rows that share the cursor timestamp or returns them again. Adding the unique id makes the ordering total and the seek exact.
Where a ranker sits relative to the cache, and what it costs in latency.
Chronological feeds bury the posts users care about.
Say it like this: A chronological feed buries what the user cares about, so I fetch a few hundred candidate ids cheaply, score them with features in a ranking service under a strict latency budget, and keep chronological as the fallback when the ranker is slow or down.
Adds to the design: Ranking service
Check yourself: Why fetch ids first and bodies last?
Ids are tiny and the ranker only needs features, not text, so scoring 400 candidates costs a few kilobytes of ids plus feature lookups. Hydrating 400 bodies would be 400 KB and most of it is thrown away; hydrate only the 20 that survive.
A feed refresh storm at 9am is a stampede; finish with the protections.
A popular key expires and every request misses at once, flattening the database (dog-piling).
Say it like this: I stop a hot key from dog-piling the database by letting one request refresh it while everyone else is served the stale value, and I jitter TTLs so keys never expire together.
Adds to the design: Celebrity post keys
Check yourself: What is the difference between a cache stampede and a thundering herd?
A stampede is the specific case of one popular key expiring and all its readers missing at once. A thundering herd is the general pattern of many clients acting at the same instant, such as reconnects after an outage or retries aligned to the same backoff. The fixes overlap: jitter, coalescing, and serving stale.
Putting it together
How the blocks above combine into one design for News Feed. The numbers on the boxes are the steps that introduce each part.
The home timeline, assembled from the path Each number is a step of this path; a box with two numbers is shaped by both blocks. The ring colour is the block's category, as on the route map. Boxes without a number come from the problem itself. Point at a step below, or at a bubble, to see where it appears.
A post is written once and fanned out by workers into every follower timeline, except for celebrities, whose recent posts are pulled at read time from a replicated per-author key. The feed service merges both, ranks the candidates and pages with a cursor.
How each block shows up in the design
- 1. Precompute on write, read cheaply: fan-out workers copy each new post id into every follower's home timeline, a Redis sorted set capped at 800 ids, so each of the 100K timeline reads per second at peak is one range query instead of a query that assembles the feed.
- 2. Fix a hot shard: accounts above the follower threshold are never pushed, because one 50M-follower post would be a quarter of the system's steady write load; readers pull those posts at read time from a per-celebrity key copied under several suffixes, so no single cache node or partition takes the load.
- 3. Precompute joins: each timeline holds the result of joining the follow graph with recent posts ahead of time, and the graph itself is stored twice, as followers and as following, so "who follows X" and "who does Y follow" are each a single-partition read.
- 4. Page results with a cursor: the feed returns 20 ids per page with a cursor made of the last item's score and post id, which stays stable while new posts land at the top, where an offset would shift and show duplicates.
- 5. Rank instead of sorting by time: the ranking service scores up to about 500 merged candidates in under 50 ms after the cache, never inside fan-out, so a new model ships without rebuilding a single timeline.
- 6. Protect against a cache stampede: the per-celebrity keys are the hottest in the cache, so when one expires a single request refreshes it from posts_by_author while the rest are served the old ids, instead of millions of feed reads landing on one partition at once.
- ★
News Feed (Twitter / X timeline)
Now run the timed practice. The blocks above should appear in your answer without prompting; if one does not, that is the one to reread.
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.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Post service, Fan-out workers, Feed service, Writer, Reader, Fix-up job, History API | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon MSK (Kafka) | Post events | Managed Service for Apache Kafka | Event Hubs (Kafka API) | Confluent Cloud, Redpanda |
| Amazon Keyspaces | Posts store, Graph service | Bigtable | Managed Instance for Apache Cassandra | Apache Cassandra, ScyllaDB |
| Amazon ElastiCache | Timeline cache, Celebrity post keys, Celebrity recent posts, Merged result cache, Feature store, Post cache, Redis | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon SageMaker | Ranking service | Vertex AI | Azure Machine Learning | KServe, Ray Serve, NVIDIA Triton |
| Amazon Aurora | posts (source), profiles (source), Database | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |
| Amazon DynamoDB | feed_item (read model) | Firestore, Bigtable | Cosmos DB | ScyllaDB, Apache Cassandra |
| Amazon Kinesis Data Streams | Impression log | Pub/Sub | Event Hubs | Apache Kafka, Redpanda, Apache Pulsar |