Design a news feed
Read first: Caching, Queues and logs, Partitioning and sharding
Ordinary posts are copied into each follower's timeline so the read is one lookup. A celebrity post is not copied, because one fanout would consume the write budget for minutes and stall everyone else. The read path merges a precomputed timeline with a handful of celebrity lists, and the threshold is a write budget rather than a guess about fame.
The ordinary account is an easy feed. You write the post into each follower’s timeline and the read is a single lookup. That design falls over on the account whose follower count is larger than the write budget you have left. That account is not a footnote you add if time remains. It is why the write path and the read path are different shapes.
Requirements
The reader is a person opening a reverse-chronological list of posts from accounts they follow. The writer is a person publishing a short post. You are not ranking the world. You are assembling a page of recent posts without making one popular account everyone’s problem.
Functional requirements:
- Publish a post and have followers able to read it in time order, newest first.
- A person follows and unfollows. The next page they open respects that.
- Delete and edit take effect on later reads. You do not need every already-open screen to update in the same second.
- The feed page returns in a budget you state. Assumption: p99 under 200 ms inside the region for a cache-friendly read. That is a product budget, not a measurement.
Non-goals:
- A learned ranker. Ranking needs a candidate set first. The hybrid below is that candidate set. Scoring it is a later interview.
- Chat, comments as a second product, and media transcoding. A post body is text of a few hundred bytes. Images, if you mention them, are object keys, not bytes in the timeline.
- A single global timeline of everything public. This is the accounts you follow.
- Pushing to a phone. That is a notification system. This page ends at the feed read.
Say who is not the celebrity. Most accounts have a few hundred followers. The design has to be excellent for them and merely correct for the account with millions. If you only optimize the celebrity, you have built a slow feed for everyone else.
Estimation
Assumptions, before any multiplication:
- 15 million people open the app on a given day.
- Each opens the feed 8 times that day.
- 800,000 of them publish, and those who publish write 1.5 posts on average, so 1.2 million posts a day.
- A typical ordinary author has 250 followers. This is the fanout you will use for the steady-state write rate. It is an assumption, and it is not the celebrity.
- Peak feed reads are 5 times the average, morning and evening. Peak posts are 3 times the average. Both multipliers are assumptions, and they do not have to match.
- A post body averages 400 bytes.
- A timeline keeps at most 500 post ids per person.
A day is 86,400 seconds. Show the shortcut and the exact division.
feed reads 120,000,000 / 86400 = 1,389 per second
shortcut 120,000,000 / 1e5 = 1,200 per second
peak reads, 5x assumption = about 6,900 per second
posts 1,200,000 / 86400 = 13.9 per second
shortcut 1,200,000 / 1e5 = 12 per second
peak posts, 3x assumption = about 42 per second
The shortcut is about 14 percent low because 86,400 is not 100,000. One million requests a day is about 12 per second. Your reads are a bit above that times a hundred. Your writes of posts are about a dozen per second. Posting is not the bottleneck. Copying each post into follower timelines is.
If every author were ordinary, at 250 followers:
12 posts/s * 250 followers = 3,000 timeline inserts per second average
42 * 250 = about 10,000 per second at the post peak
A partitioned timeline store handles 10,000 inserts per second. Now the other assumption, the one that is the design. One account has 8 million followers and publishes once. Fanout on write is 8 million inserts for that post.
Size the store, as an assumption, for 40,000 timeline inserts per second. Ordinary peak uses about 10,000 of that, leaving about 30,000 per second of slack. You want one post’s fanout to finish in under 10 seconds so the author is not waiting minutes while ordinary posts queue behind them. That 10 seconds is an assumption about product lag, not a law.
30,000 inserts/s * 10 s = 300,000 followers
Above about 300,000 followers, write-fanout of one post either blows the 10 second budget or steals the slack and stalls ordinary fanout. An 8 million follower post at 30,000 inserts per second would take 8e6 / 3e4, about 267 seconds, of the entire slack, and longer if it has to share the store. That single post is the celebrity. The threshold is 300,000 because that is the budget, not because a round number felt famous.
Storage, so you can see it is the small part:
1.2e6 posts/day * 400 bytes = 480 MB/day of bodies
365 * 480 MB = about 175 GB a year
times 3 replicas = about 525 GB
15e6 people * 500 ids * 8 B = 60 GB of timeline ids
Half a terabyte of posts with replicas is a small database. The celebrity problem is write amplification, not disk.
High-level design
flowchart LR
author[Author] --> posts[Post store]
posts --> gate[Follower threshold]
gate --> fanoutq[Fanout queue]
fanoutq --> timelines[Follower timelines]
gate --> authorcache[Author recent posts]
reader[Reader] --> timelines
reader --> authorcache
reader --> page[Merged page]
The post is stored once, partitioned by author id, so “recent posts by this author” is a local read. That placement matters for celebrities and is harmless for everyone else. Partitioning by post id would spread a celebrity’s posts across the cluster and turn the celebrity read into a scatter, so the post store stays keyed by author.
On publish, look at the follower count you already keep on the account. If it is at or under the threshold, enqueue a fanout job with the post id. Workers append that id to each follower’s timeline. If it is over the threshold, do not enqueue that job. The post already sits on the author’s recent list. Publish is done.
On read, load the reader’s precomputed timeline and the short list of celebrity accounts they follow. Fetch those celebrities’ recent ids from cache, merge by time, take a page, then load bodies by id. The body is not copied into the timeline. Delete is one write on the post plus a cache invalidation. A timeline that still holds the id drops it when the body is missing. If you had copied the text into every timeline, delete would be another fanout, including for people you tried not to fan out to.
The fanout job is a queue: competing workers, the job acked after the inserts it owns are done. Split a large ordinary fanout into chunks of follower ids so one job is not a hundred thousand writes with one ack at the end. A celebrity does not get a chunked job. A celebrity gets no job.
Deep dive
Fanout on write
For an ordinary post the write path does the work and the read path is one point read of “my timeline,” partitioned by reader id. At about 1,200 feed reads per second average, and about 6,900 at the assumed peak, one indexed read each is a comfortable database plus a cache of the hottest timelines. The user’s latency is one lookup, not the max of a fanout, because you are not fanning out on this path.
The timeline stores ids. Append is idempotent: inserting the same post id twice is a set add, not a duplicate row. Workers will retry. A duplicate post in the feed is a bug a person can see. A retry that finds the id already present is success.
What you pay is write amplification equal to the follower count, and a lag from “I clicked publish” to “the last follower’s timeline has it.” For 250 followers that lag is a round of queue delay, well under a second if the workers are sized for the 10,000 per second peak. You do not wait for fanout to tell the author the post is saved. The post row commits, then the job is enqueued. If the process dies between those, the recovery path is the same as any other dual write: write the post and an outbox row in one transaction, and let a publisher enqueue. At a dozen posts a second you can also just look for posts whose fanout has not been marked done. Either way, the post row is the truth. The timeline is a projection.
Fanout on read
The other extreme stores only the post and, on read, loads every account the person follows and merges their recent posts. Celebrity publishes become one row. The read becomes a scatter. A person who follows 100 accounts turns 6,900 feed reads per second into about 690,000 account lookups per second, before you even fetch bodies. Cache the recent posts per author and you remove the database from most of those, and you still wait on the slowest of 100 cache gets. The tail of a fanout is the page. A feed that is “100 fast calls” is not a fast feed.
Fanout on read is the right tool when the number of sources on one page is tiny. It is the wrong tool as the only tool for a person who follows a hundred ordinary accounts.
The celebrity is the design
Hybrid means ordinary accounts fan out on write, and accounts over the threshold fan out on read. The threshold from the estimate is about 300,000 followers, given a store sized for 40,000 inserts per second, ordinary peak at 10,000, and a 10 second budget. If the interviewer changes the slack or the budget, you recompute the threshold in front of them. You do not defend 300,000 as a universal constant.
Each reader stores a short list, “celebrities I follow,” separate from the full follow list. Assumption: a reader follows two celebrities. You maintain that short list when they follow or unfollow, and when an account crosses the threshold. Crossing the threshold is a job: set the flag, and stop write-fanout for posts created after the flag. Old posts can remain in timelines until they age out of the 500-id cap. New posts must not be written there.
A post records the decision that was made at publish time, a bit that says “I was fanned out” or “I am a celebrity post.” The read path trusts the bit. It does not also merge a celebrity’s fanned-out post from the timeline and from the author list. Without the bit, the moment of crossing produces duplicates. With the bit, an old post lives only in timelines and a new post lives only in the author list.
Read path, in order:
- Load my timeline ids, one partition, my user id.
- Load the celebrity ids I follow. A short list, tens of bytes, cached with the profile.
- For each, load recent post ids from a cache keyed by author id. Two cache gets in parallel, not a hundred.
- Merge by time, drop ids whose post bit says they do not belong on this path, take the page.
- Load bodies by id. Cache bodies by post id. They are immutable except for edit and delete, which invalidate.
Assumption you should say: 20 percent of feed opens follow one particular giant account. At 6,900 reads per second that is about 1,400 cache gets per second on one key. A cache serves that. The failure is expiry. If that key expires and 1,400 readers miss together, the author partition takes a stampede. Single-flight: one filler reads the author’s recent ids, everyone else waits. Jitter the TTL so you do not expire the giant and the ordinary hot timelines on the same second.
If a celebrity cache get times out, return the precomputed timeline without them and let the client refresh. A missing celebrity post is a better failure than a failed page. You are choosing a degraded read over a coupled one. Say it.
An ordinary account that goes viral and crosses 300,000 mid-day flips the flag between posts, not during one. The post that is already in the queue finishes under the old bit. You do not start a second path for it. If one post’s ordinary fanout is already too big, because you set the threshold too high, the queue will tell you: fanout lag, not read latency, is the symptom. Lower the threshold. You can also put a cap on inserts per post per second and, if a single job would exceed it, flip that post onto the celebrity path even if the account has not crossed the count. The budget, not the badge, is the rule.
Unfollow of an ordinary account leaves ids in the timeline until you filter them. Filtering on read against a recently-unfollowed set is enough. Rewriting the timeline on every unfollow is another fanout, pointed the wrong direction, and it is how a popular account’s departure becomes a write storm. Drop on read. The 500-id cap forgets them anyway.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Fanout on write for everyone | A read is one lookup | One celebrity post is millions of inserts and stalls the queue |
| Fanout on read for everyone | A publish is one row, celebrities are cheap to write | Every page waits on the slowest of many lookups, and read QPS multiplies by follow count |
| Hybrid at a computed threshold | Ordinary reads stay one lookup, celebrity writes stay one row | Two read sources to merge, and a flag you can get wrong at the boundary |
| Copy the post body into every timeline | The page needs no second fetch | Deletes and edits become fanouts, including for celebrities you tried to avoid |
| Store ids only | Delete is one write, timelines stay small | A missing body must be dropped on read, and the body store has to stay up |
| Fail the page if a celebrity cache misses | You never show a partial feed | One hot key’s timeout becomes an outage of the product |
The hybrid row is the design. The last row is the failure policy that keeps the hybrid from coupling your availability to one cache key.
Failure modes
- Fanout worker dies halfway through a chunk. Some followers have the id, some do not. The job retries. Idempotent insert means the ones who already have it stay at one copy. Symptom of forgetting idempotency: the same post twice in one feed, only after a deploy or a crash. A hot partition is a different symptom: one author’s post store, or one reader’s timeline if a bot is writing a single ordinary account faster than a partition can take. A human cannot type that fast. A mis-classified celebrity can.
- Celebrity treated as ordinary. Lag on the fanout queue grows after one publish, and ordinary posts wait behind millions of inserts. The read path looks healthy. The metric you want is fanout lag and inserts per post, as well as feed p99. Alerting only on read latency will not see this.
- Celebrity cache miss storm. The author partition’s read latency spikes, then feed p99 spikes if you waited on it. Single-flight and a degrade-to-timeline path keep the page up. A retry from every client at once is the retry storm version. The client refreshes once, not in a loop, and the filler is one read.
- Post committed, fanout job never enqueued. Those followers never see it, and a read-fanout will not save you because the bit said ordinary. The outbox or the “fanout not marked” scanner is the repair. The reverse bug, enqueue before commit, puts ids in timelines whose body never lands. Readers drop the missing body, so the post flashes and vanishes. Commit the body first.
- Threshold flapping. An account hovers at 300,000 because of follow-unfollow churn and you flip the flag every hour. Posts from the same afternoon take different paths and the merge logic, if it trusts the account flag instead of the post bit, duplicates or hides them. The bit is on the post. The flag is only consulted at publish.
- Cache of the timeline itself is stale after a new ordinary post. A short TTL, or a delete of that reader’s cached page on fanout, bounds it. Invalidating 250 cache keys on an ordinary post is fine. Invalidating 8 million would be a second celebrity fanout. Celebrity readers do not have this post in a precomputed timeline, so you invalidate the one author cache key, not every reader.
In the interview
First five minutes: reverse chronological, not ranked, and the reader follows both ordinary accounts and a few huge ones. Put the numbers up. About 1,200 feed reads per second with the shortcut, about a dozen posts per second, ordinary fanout a few thousand inserts per second. Then compute the threshold from slack and a lag budget before you say the word celebrity. Draw both paths. The bottleneck is an 8 million insert post, not the body storage.
Skip the ranker, skip social-graph tricks, skip a second copy of the post body “for speed.”
The question that follows is “what does the read do for someone who follows 100 ordinary accounts and two huge ones.” One timeline read, two cache gets, a merge. The tradeoff you admit: a celebrity post is not in the precomputed timeline, so a dead author-cache degrades the page, and an account near the threshold must record the path on the post or you will duplicate.
Check yourself
The timeline store can do 40,000 inserts a second, ordinary peak uses 10,000, and you want one fanout done in 10 seconds. Where do you set the threshold?
Spare capacity is 30,000 inserts per second. Times 10 seconds is 300,000 followers. Above that, one post either misses the lag budget or consumes the slack and delays everyone else’s fanout. The threshold moves if the budget or the slack moves. It is not a fixed definition of celebrity.
A reader follows 100 ordinary accounts and 2 celebrities. What do you read, and why is it not 102 queries?
Ordinary posts were already written into this reader’s timeline, so that is one lookup. The two celebrities were not, so you read two cached recent-id lists and merge. Fanout on write already paid for the 100. Fanout on read pays only for the accounts that were too expensive to copy.
A fanout worker crashes after writing the post id into half of a chunk of followers. What do you need on the retry?
An insert that is idempotent per reader and post id. The retry will see the id already present for the first half and will only add it for the rest. A blind append duplicates the post in those feeds. The post body was committed before the job, so the retry is repairing a projection, not guessing at content.
Why store post ids in the timeline instead of the post text?
A delete or an edit is one write on the post and a cache invalidation. Readers that still hold the id drop a missing body. Copying the text would turn every delete into a fanout across every follower, which is the cost you refused to pay for a celebrity in the first place, paid all over again on the way out.
What is 120 million feed reads a day at a 5 times peak, using both 86,400 and the shortcut?
120 million divided by 86,400 is about 1,389 per second. Divided by 1e5 it is 1,200. Five times the exact average is about 6,900 per second. That is the read rate the hybrid has to serve with one timeline lookup plus a couple of cache gets, not with a lookup per account you follow.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Jay Kreps, Neha Narkhede, Jun Rao, Kafka; Alex Xu, ByteByteGo volumes.