Nadia, a singer with 30 million followers, posts a photo from backstage ten minutes before a show. Storing it takes one row: an ID, her account, the time, a caption and a reference to the image. The hard part comes after. Within a few seconds the photo should be near the top of the home feed of everyone who follows her and opens the app, and tonight that is millions of people.
Every feed has to decide when the work of a post happens. It can happen when someone posts: put the new post into every follower's feed right away, so that opening the feed only reads a list that is already there. Or it can happen when someone reads: store the post once, and assemble each feed from the accounts the reader follows at the moment they open it. Used on its own, either choice breaks on Nadia's photo, and the design in this post ends up using both.
We will take that photo through four versions of the feed and ask the same thing of each: what does it cost now, and who pays? Readers who already know feed design can go straight to the last drawing and the list of what breaks under it. The finished design is described in Learn's worked news feed; this post is about the decisions on the way there.
Opens outnumber posts fifty to one
The app is a photo-sharing app, and the subject here is its home feed: the recent posts from the accounts you follow. Uploading and serving the photos themselves is a separate problem, so a post in this design only carries a reference to its image. Every number below is an assumption of the exercise, rounded to keep the arithmetic easy; none is measured from a real service:
- 50 million accounts, of which 20 million are used on a given day. An account follows 200 others on average.
- 4 million posts a day: about 50 a second on average, and about three times that at the evening peak, 150 a second.
- Each of the day's users opens the feed 10 times: 200 million opens a day, about 2,300 a second on average and 7,000 a second at the peak.
- The biggest account has 30 million followers, and that is Nadia. Only a few thousand accounts have more than 50,000. A follower count includes every account that follows, not only today's users: say 10 million of Nadia's followers open the app on a given day.
Learn's worked design starts from a larger app and lands on different sizes, a lower threshold and longer lists. Neither set is the correct one: different numbers move the sizes and leave the reasoning where it is.
Two of those lines matter more than the others. Opens outnumber posts about 50 to 1, so the design should keep opening cheap even if posting gets more expensive. And followers are spread very unevenly: the average account has 200, and Nadia has 150,000 times that.
Three time limits, also assumptions. Opening the feed should feel instant, a few hundred milliseconds from tap to posts. Publishing can answer as soon as the post is stored. And a new post may take a few seconds to appear in followers' feeds, at their next refresh. Nobody notices a photo that arrives five seconds late; everybody notices a feed that takes five seconds to open.
Build the feed when it is opened
Start with a feed service and one relational database. Two tables matter here: posts (ID, author, time, caption, image reference) and follows (who follows whom). Posting is one insert. Opening the feed is one question to the database: the newest 20 posts written by any of the 200 accounts I follow.
Asked carelessly, that question reads every post those 200 accounts ever wrote and sorts them all. With an index on posts by author and time, the database can instead jump straight to each account's newest few posts and keep the newest 20 of the lot: 200 short index lookups per open. This is fan-out on read: a post reaches its readers when each reader looks.
Every open asks the database for the newest posts of each followed account.
Learn moreIndexing & query optimisation
For a new app this is enough, and it is the right place to start. The query is simple and always correct: a post is visible the moment it is stored, an unfollow takes effect on the next open, and a deleted post disappears everywhere at once, because nothing was copied anywhere. Nadia costs nothing special either. Her photo is one insert, the same as anyone else's.
Her cost shows up on the reading side. Each of the 10 million followers who open the app today runs the query, and her account is one of the 200 lookups in every one of those opens. Her posts on their own are no problem: a page of the index read that often stays in the database's memory. The trouble is the total. At the peak, 7,000 opens a second × 200 lookups is 1.4 million index lookups a second, against 150 inserts.
And most of that work repeats itself. With these numbers an account posts less than once a week on average (4 million posts a day across 50 million accounts), so the 200 accounts a reader follows write about 16 posts a day between them. Between two of the reader's ten opens, one or two of the 20 posts on screen are new. The database does 200 lookups to find two posts. Reads outnumber writes 50 to 1, and every read is the expensive operation: the work is on the wrong side.
Build the feed when the post is written
So turn it around: do the work once per post, when it is written, and let each open read the result. Every user gets a feed list, the IDs of the newest posts from the accounts they follow, newest first, kept in a feed cache in memory. When someone posts, the new ID goes into the list of each of their followers. Opening the feed becomes one list read plus a fetch of the posts behind the first 20 IDs. This is fan-out on write.
The author should not wait for 200 list writes, so the feed service does not do them. It stores the post, puts one job on a queue (“fan out post 123 by account 45”), and answers. Fan-out workers take jobs off the queue, read the author's followers from the database, and append the post ID to each follower's list. If a worker crashes in the middle of a job, the queue hands the job out again, so each list is kept as a set ordered by post ID (IDs here grow with time, so ID order is time order), and appending an ID that is already there changes nothing.
The lists hold IDs, not copies of posts, so editing a caption or deleting a post is still one write to the database; when the feed is fetched, an ID whose post is gone is skipped and the next one taken. Each list keeps only the newest 300 IDs, more than most people scroll through between two visits. Fan-out writes to every follower, whether or not they open the app today, so there is a list for each of the 50 million accounts: 50 million × 300 IDs × 8 bytes, about 120 GB before the store's own overhead. That is still memory a handful of machines can hold, in an in-memory store such as Redis.
The service stores the post and queues one job; workers write its ID into each follower's list.
Learn moreMessage queues & async workersTransactional Outbox
Opening the feed is now one read from memory and one fetch of 20 posts by their primary keys. At the peak that is 7,000 list reads a second and 7,000 batched fetches, where the previous version needed 1.4 million index lookups. The writes grew instead: say an ordinary post goes to 200 followers, the average, so it becomes 200 appends. At the evening peak that is 150 × 200 = 30,000 appends a second, and the workers are sized for 50,000. An ordinary post reaches its followers' lists a few seconds after it is stored, inside the time limit.
Those are the costs of this version: each post is written about 200 times, a follower sees a post seconds after it was stored instead of at once, and there is now a second record of who sees what, derived from the database, that has to follow it. An unfollow, for example, leaves the old account's IDs in the list until they are filtered out at read time or pushed off the end of the list by newer posts.
One gap is easy to miss. If the service crashes after storing a post and before queuing its job, the post exists and reaches nobody's feed. The service closes that gap by recording the job in a table of the same database, in the same transaction as the post, and then moving recorded jobs from that table to the queue; a crash in between leaves the job in the table, to be moved later. This is the transactional outbox, and the chat post on this blog uses it for the same reason.
What happens when the feed cache is lost? Say the cluster restarts empty. No post is lost: the database still has every post and every follow, and the cache only held something derived from them. The reading path is what suffers. The service finds no list for a reader and has to build one, and the only way it knows is the query from the first version. Run that on every open at once and the database gets the 1.4 million lookups a second this version exists to avoid, all at the same moment. So lists are rebuilt lazily and at a limited pace: a list is rebuilt the first time its owner opens the feed, and only as many rebuilds run at once as the database can take beside its normal work. A reader beyond the limit gets something cheaper for now, the newest posts of a slice of the accounts they follow, and the full feed on a later open. For a while, some feeds are slower or shorter. Posting still works: posts are stored and acknowledged as before.
One detail makes the rebuild correct. The workers keep appending while lists are missing, so a list holding only those fresh appends looks like a feed and is not one. The service has to know which lists have been rebuilt (a marker per list will do), and a rebuild merges into the list instead of overwriting it.
And Nadia's photo? It is one insert and one job, and the service answers her as quickly as anyone. Then the job reaches the workers, and they have 30 million lists to write.
Thirty million appends for one photo, so the few are pulled
Back to the moment this post opened with. The workers split a job that large into chunks of a few thousand followers, so the whole fleet can share it. The fleet appends 50,000 IDs a second, and the photo needs 30 million: 30,000,000 ÷ 50,000 = 600 seconds, ten minutes of the entire fleet for one post. And she posts at the evening peak, when the fleet is already doing 30,000 appends a second for everyone else. If the workers keep everyone else's posts moving, only 20,000 a second are spare, and her last followers get the photo 25 minutes after she posted it. If her chunks go first, every other post waits ten minutes. The size of the fleet only decides who does the waiting.
Now make it the night of an awards show, where Nadia posts 20 photos in an hour. That is 20 × 30 million = 600 million appends, or 12,000 seconds: more than three hours of the whole fleet's work from one hour of one account, and longer still with everyone else's posts arriving on top.
What happens when the fan-out queue falls hours behind? Posting still works. Nadia and everyone else see “posted” as soon as their post is stored, because the queue sits between publishing and fan-out. Opening the feed still works too, and quickly; it just shows lists that have stopped moving. A student who posts at nine in the evening is told her photo is up, and her job waits behind hours of Nadia's chunks: her 200 followers see it around midnight. The queue did what it was there for, protecting the publish path, and in doing so moved the whole cost onto freshness, for everyone.
More workers would not fix it at a sensible price. Finishing 600 million appends within the hour takes about 170,000 a second on top of everyone else's 30,000, four times the fleet, and the feed cache would have to absorb those writes as well, for a few evenings a year. Most of the appends are wasted anyway: only 10 million of Nadia's 30 million followers open the app on a given day, so two appends in three go to someone who will not look today.
The fix is to stop treating Nadia like everyone else. Pick a threshold, say 50,000 followers: accounts above it are not fanned out at all. Their posts are stored as before, and the feed service pulls them when a feed is opened. Opening the feed now means reading the reader's list, reading the recent posts of the big accounts this reader follows, merging the two by time and keeping the newest 20. Fan-out on write for almost everyone; fan-out on read for a few thousand accounts.
Two numbers change. The largest job the workers can ever get is now 50,000 appends, one second of the fleet, so a single post can no longer put more than a second of work into the queue. And each open does a little more: say the average reader follows five big accounts (another assumption), so an open costs five extra small reads. The service keeps, beside each reader's list in the feed cache, the short list of big accounts they follow, updated when they follow or unfollow, so it does not have to ask the database which ones they are on every open. Rebuilding a reader's list after the feed cache is lost rebuilds this short list too, from the follows.
Those recent posts need a place to be read from. The database could answer: five accounts per open at 7,000 opens a second is 35,000 index lookups a second, a fortieth of the first version's load. Look at what they ask, though. Nadia's newest posts alone would be read 3,500 times a second (more on that number below), and all 35,000 lookups land on the newest rows of the same few thousand accounts, returning the same answer every time until one of those accounts posts again. Repeating one answer thousands of times a second is the job a cache does for almost nothing, and it keeps the database's spare capacity for the rebuilds the feed cache may one day need. So the service keeps a small cache of each big account's newest posts, say its last 50 IDs. On a miss it reads the database and fills the entry (the cache-aside pattern). When a big account posts, the service stores the post and then adds the new ID to the front of that account's entry. That write can race with a refill: a refill that read the database just before the post was stored would write back a list without it. So, as with the rebuild of a feed list, a refill merges into the entry instead of overwriting it, and a marker says when the entry is complete, so that an ID added to a missing entry is not taken for the whole list. Each entry also expires after a few minutes, so that an entry a failed write left behind corrects itself.
Accounts above 50,000 followers are not fanned out; their recent posts are pulled when a feed opens.
Learn moreFan-out: push vs pullCache-AsideHot keys & cache stampedes
That cache is small, a few thousand short lists, and its traffic is lopsided. Nadia's entry is read by every open of her 10 million daily followers, half of all opens: about 3,500 reads a second at the peak. Reading one key 3,500 times a second is ordinary work for an in-memory store. Missing it is the problem. Posting no longer empties her entry, but expiry does, every few minutes, and so does the store evicting it or restarting. Every open that arrives between the miss and the refill being written back misses as well and sends the same query to the database. At 3,500 a second and a refill that takes 100 ms under load, that is about 350 identical queries for one entry, and the cache has a few thousand entries, each with its own moments to miss.
That is a cache stampede. The fix is to refill each entry once: the first open that misses takes a short lock on the entry in the cache and loads it, and the opens that miss after it wait for that one load instead of starting their own. Entries are also refreshed shortly before they expire rather than after, so that expiry alone rarely empties one. The opens that do wait, wait for one refill, about 100 ms here, inside the few hundred milliseconds an open is allowed.
What this version costs: the read path merges two sources, and the big-account cache is one more thing to keep correct. The threshold has to be chosen, and it works like a dial: lower means fewer appends and more pulling on every open. Accounts also cross it. One that passes 50,000 stops being fanned out while its older posts are still in its followers' lists, so the merge drops duplicate IDs; and to keep an account near the line from switching back and forth, it goes back to fan-out only once it falls well below, say to 40,000. Crossing the line also changes what its followers' feeds have to pull. A one-off background job, run by the same workers, adds the account to each follower's short list of big accounts (50,000 writes, about a second of the fleet) before its posts stop being pushed, and when the account drops back, its new posts are fanned out again, then a second job appends its recent posts to its followers' lists, split into jobs of at most 50,000 appends like any other, and only then removes it from its followers' short lists.
Nadia's photo now costs one insert and one write to her cache entry at write time. Her readers pay for it instead: one small read from memory in each of 3,500 opens a second, the cheapest place its work has been so far.
Ranking at read time
Every feed so far is newest first. Readers would rather see the posts they care about most at the top: a close friend's photo from this morning before a brand's post from a minute ago. That takes a ranking model, which gives each candidate post a score for this reader.
The tempting place to rank is the fan-out. The workers already touch every pair of post and follower, so they could score the pair and insert the ID at its scored position instead of at the top. It goes wrong in three ways. The score is fixed at the moment of posting, before anyone has liked or commented, and engagement is much of what a score is made of; keeping scores current would mean re-scoring lists that hold 50 million × 300 = 15 billion entries. The reader's interests change between opens, and a score stored days earlier cannot know that. And Nadia's photo no longer passes through the fan-out at all: big accounts' posts only meet a reader's list at read time, so they would need ranking at read time anyway. Ranking on write means two rankers and a stale score.
So ranking happens when the feed is opened, after the merge. The service collects the candidates, the reader's 300 IDs plus the recent posts of their big accounts (for a reader with the average five, at most 300 + 5 × 50 = 550), sends them to the ranking model with the reader's ID, gets scores back, and fetches the 20 best. At the peak that is 7,000 ranking calls a second, each scoring around 550 posts on those average numbers: about 4 million scores a second. That is a fleet of its own, and the reason the model is drawn as a separate box rather than as code inside the feed service.
The service sends a few hundred candidates to the model and waits only until a deadline.
Learn moreRecommendation systems: retrieval, ranking & cold startFallback
What happens when the ranking model is slow or down? It sits on the path a reader waits on, so it gets a deadline, say 100 ms of the few hundred an open is allowed. If the scores are not back in time, the service shows the candidates it already has, newest first: the feed of the previous version. If the model keeps failing, waiting 100 ms on every open only to give up is wasted time, so the service stops calling it for a short while and tries again later. Either way the reader gets a feed, at most 100 ms later and in a less useful order, and nothing else notices: publishing and fan-out never call the model. Count every time the fallback is used and alert on it, or a broken model can go unnoticed for days behind feeds that still look fine.
Nadia's photo is now one candidate among a few hundred in each of those opens, scored for each reader separately. For a fan it may be the first post on the screen; for someone who followed her years ago and never reacts to her posts, it may be tenth. One photo, a different position in each of 10 million feeds, decided at the moment each one is opened.
Where the work for one photo lives now
Follow two posts through the final drawing. The student with 200 followers posts: the service stores the post and its job in one transaction, answers, and moves the job to the queue; within seconds a worker reads her followers and appends the ID to 200 lists. Nadia posts: the service stores the photo and adds its ID to her entry in the big-account cache, and nothing else happens at write time. Each open does the rest: read the reader's list, read their big accounts' recent posts (refilling an empty entry once), merge, rank under a deadline, fetch 20 posts.
Eight boxes. Here is what happens when each part breaks, and who notices:
- The feed cache is lost → no post is lost. Lists are rebuilt on open at a pace the database can take, and for a while some readers get a slower or shorter feed. Posting still works.
- The fan-out queue is down or the workers fall behind → posts are stored and acknowledged (while the queue is down, their jobs wait in the outbox table), and feeds go stale for ordinary accounts' posts. No job is bigger than 50,000 appends now, so one post adds at most about a second of work to the queue. Big accounts' posts still appear on time: they never go through the queue.
- A worker crashes in the middle of a job → the job runs again, and appends keyed by post ID make the repeat harmless.
- The big-account cache is down → the service reads those short lists from the database, one load per account at a time in each service instance. If the database refuses that load, feeds come back without the big accounts' posts until the cache returns.
- The ranking model is slow or down → feeds come back newest first.
- The database is down → publishing stops, and so does opening the feed, because the posts behind the IDs live there. It is the one stateful box everything depends on, so run it replicated. (The feed service keeps no state of its own and simply runs as several instances.)
What the design kept moving is the cost of one post. In the first version Nadia's photo cost one row and every reader paid for it on every open. In the second, readers paid almost nothing and the workers paid 30 million appends. In the last, an ordinary post is paid for once, when it is written, and a huge account's post is paid for in small pieces, when it is read.
What this design leaves out
- The photos themselves. Uploads, thumbnails, object storage and a CDN; a post here only carries a reference to its image.
- Paging. Scrolling past the first 20 posts needs a cursor rather than a page number, because new posts keep arriving at the top.
- A cache of post bodies. Every open fetches 20 posts from the database by ID, and popular posts are fetched by many feeds at once; a cache in front of them is the usual next step.
- Followers who never open the app. Fan-out writes to their lists anyway; pushing only to recently active readers, and filling a list when its owner comes back, saves a large share of the appends.
- Likes and comments. The ranking model needs their counts as they arrive, and collecting and counting them is a system of its own that feeds the model.
- A much larger follow graph. 50 million accounts following 200 each make about 10 billion follow rows, which one well-indexed relational database can still hold; far larger graphs are partitioned by user.
Build it yourself
The News Feed Challenge asks for this design: both fan-out models, a plan for accounts with millions of followers, ranking, and new posts in followers' feeds within seconds. Its palette names products (PostgreSQL, Redis, Kafka) where this post draws generic boxes, and it has no model-serving component, so the ranking goes in an application service. Draw it, then send Nadia's photo through it. Photo Sharing Feed is the same feed with the photos put back: object storage, a CDN and thumbnails around the design above.