You open the app, and twenty posts appear in about a second. This is one of the most misunderstood questions in system design, and most answers start in the wrong place. They open with a fanout strategy, which is a choice about when to copy a post out to its readers, before anyone has said what problem it solves.
The problem starts with a query. To show your feed, I need the recent posts from every account you follow, merged together and put in order. That is a join between two tables and a sort, with nothing clever in it. You could write the SQL in a minute.
The trouble is that nobody can afford to run it. A user follows 200 accounts on average, and there are 300,000 feed loads a second. That is 60 million lookups a second before you have ranked, filtered or rendered anything. So you do not run the query on every load. You keep the answer ready in advance.
Your feed is a cache of a query nobody can afford to run. Once you see it that way, every decision in this design is a decision about that cache: when you fill it, who you fill it for, and what you put in it. The last decision is what to do about accounts whose one post would have to go into 100 million of these caches at once.
The well-known parts of this problem all follow from that. Fanout on write fills the cache early, when a post is written. Fanout on read fills it late, when somebody opens the feed. The celebrity problem is the point where filling early stops working, because one post becomes more writes than can finish in a few seconds. It is not a special case you bolt on. It is a number you can calculate.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
Users post. Users follow other users. When you open the app, you see recent posts from the people you follow.
Before you design anything, separate the four things people call a "feed". Each one works differently.
- The home feed. Posts from the accounts you chose to follow. It is a join you precompute, meaning you compute it in advance and store the result. This is the problem.
- A ranked feed. The same posts, ordered by how interesting a model predicts each one is to you, rather than by time. It reuses everything below, but it changes what "the answer" means, so it gets its own deep dive.
- Explore or recommendations. Posts from people you do not follow. There is no follow graph to join against, so it is a retrieval and ranking problem with almost nothing in common with the home feed.
- Notifications. Someone liked your post. Each notification goes to one user and is triggered by an event. The volume is tiny next to the feed, and it is a different system.
We are designing the first, with the second as a deep dive that changes several earlier answers.
Functional requirements
Core:
- Post. A user publishes a post, which becomes visible to their followers.
- Read the feed. A user opens the app and gets recent posts from accounts they follow, most recent first.
- Page through it. Scrolling gets older posts, without duplicates and without skipping any.
- Follow and unfollow, with the feed reflecting it.
Out of scope, deliberately:
- Explore, recommendations and anything from people you do not follow.
- Media storage and delivery. It is object storage with a content delivery network (CDN) in front, and the post carries a pointer.
- Search over posts, which is an inverted index and a separate system.
- Notifications, direct messages, comment threads.
Non-functional requirements
- A feed loads in under 200 ms at p99, server side, for the first page. p99 means 99 of every 100 loads are faster than that.
- Reads dominate writes by about 50 to 1. Twitter reported roughly 300,000 timeline reads a second against 6,000 writes. Optimise the read path and let writes be expensive.
- Scale: 500 million daily active users, 2 billion accounts, and an average of 200 accounts followed. Follower counts have a long tail: a few accounts have more than 100 million followers.
- A post may take seconds to appear in a follower's feed. It may not take minutes, and it must always appear in the end. Seconds are fine, and this permission is what makes the whole design possible.
- A feed may be slightly stale or slightly incomplete. Nobody notices a missing post from three hours ago. Everybody notices the same post twice while scrolling.
Requirement 4 is the one the design rests on, so state it in exactly those words. It gives you permission to do the work asynchronously, meaning after the request has returned. Without it, publishing a post would have to update 100 million feeds before returning, and no design does that in under a second. With it, the write path becomes "accept the post, then do the rest later". Every hard part of this problem moves into work you can put on a queue.
The set up
Core entities
- User. An account. For this design, the only thing that matters about it is its follower count, and that count drives the entire design.
- Post. A post has an author, a timestamp, content and media pointers. It is written once, read a huge number of times, and rarely changed.
- Follow. A one-way edge, a link from the follower to the account they follow. This is the only relationship in the system, and both directions of it get queried: "who do I follow" on read, and "who follows me" on write.
- Timeline. The ordered list of post ids for one user's feed, precomputed and stored. You would not design this table on your own. It exists only because the query it replaces is too expensive to run, and it is what this whole article is about.
How a feed gets assembled at all
Settle this before the interface, because everything else depends on it. The answer people usually name is worth nothing in an interview without the reasoning that produces it.
Start with the simplest first attempt: run the query when the feed is asked for.
SELECT * FROM posts
WHERE author_id IN (SELECT followed_id FROM follows WHERE follower_id = ?)
ORDER BY created_at DESC
LIMIT 20;
It is correct. It needs no new infrastructure, no background workers, and no cache to keep in step with anything. A post is visible the instant it is written, so requirement 4 costs you nothing. If you are building this for 10,000 users, ship it and stop there.
Then work out what it costs.
Per feed load
accounts followed, average = 200
the database must find recent posts from each,
merge 200 sorted lists, and keep the top 20
At the read rate
300,000 feed loads/s × 200 authors = 60M author
lookups/s
at an optimistic 0.1 ms of work each
60e6 × 0.0001 s = 6,000 cores,
busy, doing only this
And that is before ranking, filtering blocked accounts,
removing deleted posts, or fetching any content.
The 20 posts you return cost you a 200-way merge.
You throw away almost everything you touched.That is 6,000 cores to answer a question whose result is twenty rows. Most of the work is thrown away. You merged 200 lists and kept 20 posts. Then the same user pulled to refresh, and you did it all again.
The cost also falls in the wrong place. Requirement 2 says reads outnumber writes 50 to 1, so this design puts the expensive work on the side that happens 50 times more often. Twitter described its own system this way: Twitter is primarily a consumption mechanism, not a production mechanism. So put the cost on production, the side that happens less often.
So turn it around. Do the merge once, when the post is written, and keep the answer. When someone posts, look up their followers and append the post id to each follower's timeline. Reading a feed becomes a single range read: one request for the newest entries of one list. A data store can do very few things more cheaply.
Here is the trade. Reads are now cheap, and the cost of a write grows with the author's follower count. For an account with 300 followers, a post is 300 small appends, and nobody notices. For an account with 100 million followers, one post is 100 million appends, and that is a real problem. Most of the high-level design is about that one case.
System interface
POST /v1/posts
{ "content": "...", "media": ["m_8f2c"] }
→ 202 Accepted { "post_id": "p_91c4" }
GET /v1/feed?cursor=eyJ0IjoxNzU0NjQwMDAwMDAwLCJpZCI6InBfOTFjNCJ9&limit=20
→ 200 OK { "posts": [...], "next_cursor": "..." }
Three details to note.
Posting returns 202, not 201. 202 Accepted says the post exists but has not reached anybody's feed yet. That puts requirement 4 into the API contract instead of hiding it. It also lets the client show the post in the author's own view straight away, while the fanout runs.
The feed is paged by cursor, never by offset. ?page=3 breaks here in a way that is easy to miss. New posts are written to the feed while you scroll. By the time you ask for the next twenty, five new posts may have arrived at the top and pushed everything down. Offset 20 now returns posts you already saw. A cursor marks a position in the list itself, usually the timestamp and id of the last post you were given. New arrivals at the top cannot move it.
The cursor is opaque. The server encodes it and hands it back as a blob the client cannot read. If clients can build their own cursors, the format becomes a public API, and you can never change how the feed is stored.
High-level design
1. Store the follow graph so both directions are cheap
The design needs two questions answered fast: who do I follow, on the read path, and who follows me, on the write path. They are the same edge read in opposite directions. A table keyed one way can only answer one of them cheaply.
So store the edge twice: a following table keyed by the follower, and a followers table keyed by the account being followed. Writing a follow writes both rows. Storing the same fact twice like this is called denormalising, and here it is on purpose. The two tables can briefly disagree, and for a follow graph that does not matter.
Two details that only show up in production:
The follower list of a large account is a dataset, not a row. 100 million followers at 8 bytes each is 800 MB for one account, and you do not want all of it in one partition. Store it in chunks, so the fanout workers can read it in pages and process the pages in parallel.
Reading a large follower list is a paged scan, not a lookup, and the fanout worker has to be written that way from the start. Suppose a worker loads the whole list before doing anything. It works for the 99.9 percent of accounts with under 1,000 followers, and it falls over on the first account with 10 million. If the worker reads one page at a time and hands each page on as its own unit of work, the same code serves both.
The read direction needs a cache and the write direction does not. "Who do I follow" is asked on every feed load, the answer is small, and it changes rarely, so it belongs in a cache next to the reader. "Who follows me" is asked once per post, the answer is huge for the large accounts that cause the trouble, and a background worker reads it with no latency requirement. The two directions look the same in the schema, and they are used in completely different ways.
Unfollow does not go back and clean timelines. If you unfollow someone, their old posts may stay in your timeline for a while. Deleting them means scanning your whole timeline, for a result nobody will notice. Instead, filter them out at read time, or let them age out of the list. This is the first of several places where a feed does not have to be exactly right, only free of surprises.
2. Get a post into a follower's timeline
This is the write path, where most of the hard work in this problem happens.
A post is written to the post store, and a fanout job is queued. A worker reads the author's follower list and appends the post id to each follower's timeline. Three details here should be said out loud, not assumed.
It goes through a queue, not inline. The 202 from the API means the post is safely stored, and the fanout runs afterwards. So the time a user waits to post does not depend on their follower count. That is what makes posting feel the same for everyone.
Timelines are capped. Twitter capped home timelines at 800 entries. Nobody scrolls past a few hundred posts, and anyone who does can be served by the slow path, the query from earlier. Without a cap, each timeline grows forever. With one, each timeline has a fixed size you can multiply by the number of users, and the storage arithmetic in section 4 depends on that.
The append is idempotent, meaning that doing it twice has the same effect as doing it once. Fanout workers retry, and a retried job must not put the same post in a timeline twice. Key each entry on (timeline_owner, post_id), so the second write changes nothing.
Twitter's published figures, for scale:
posts 400M/day, ~5K/s average, >12K/s in events
fanout deliveries 30 billion/day ≈ 350,000/s average
also quoted as 300,000/s
ratio 30e9 / 400e6 = 75 deliveries per post
So the average post reaches 75 timelines, and the system
does two orders of magnitude more writes than posts.
The waste is worth naming too. If a third of followers
open the app on a given day:
30e9 × (1 - 0.33) ≈ 20B writes/day
into timelines nobody
opens that day20 billion wasted writes a day sounds like a lot, but it is mostly fine, because each one appends a few bytes to a list. It matters in the next section, where the fix for celebrities also removes the part of it that goes to followers who have stopped opening the app.
3. What happens when someone has 100 million followers
This is where fanout on write stops working, and you can calculate exactly where that happens.
Fan out to everyone, and add workers when it is slow
One post becomes 100 million appends. You add more fanout workers until it finishes fast enough.
It does not work, and the reason is not total throughput. Twitter published its own delivery latency: 3.5 seconds at p50 (the median) to reach one million followers, and up to 5 minutes at p99. That is with a fleet already built for this job. 100 times more followers means 100 times the work for that single post, and all of it arrives at the same moment, as one burst on one author's follower list.
So the first followers see the post in a second, and the last see it minutes later. Users notice, because people reply to a post that their friends cannot see yet. The burst also competes with every other post being fanned out at that moment. One celebrity's post slows down the feeds of users who have never heard of them.
Do not fan out for large accounts; merge them in at read time
Pick a follower count as the threshold. Above it, skip the fanout entirely, and keep the author's recent posts in one small list of their own. When a reader asks for their feed, read their timeline and fetch the recent posts of the few large accounts they follow, then merge the two.
Twitter describes doing exactly this: for accounts like Taylor Swift, "don't bother with fanout anymore, instead merge in her timeline at read time".
Say out loud why this works. A celebrity's recent posts are one list, read by 100 million people. That list is the busiest cache entry you have, and every one of those readers shares it. Fanout would have written 100 million copies of the same information. The merge reads one copy 100 million times, and a cache handles that well, because every read is a hit on the same entry.
Here is the cost. A read is no longer a single range read. It is one range read plus a small merge, and the design now has two paths where it had one.
Derive the threshold instead of picking one
Do not treat the threshold as a config value that somebody guesses. You can work it out from a requirement you already wrote down.
Requirement 4 said a post may take seconds to appear. Take five seconds as the freshness budget. Twitter's own figure gives the fanout rate for a single post: one million followers in 3.5 seconds is about 285,000 deliveries a second.
fanout rate, one post 1e6 / 3.5 s ≈ 285,000/s
freshness budget 5 s
max followers before you miss it
5 × 285,000 ≈ 1.4M followers
freshness budget 10 s ≈ 2.9M followers
So the threshold is not a taste. It is
followers_max = freshness_budget × fanout_rate
and if you want a tighter feed you get a lower threshold,
which is the trade stated as an equation.The same reasoning covers a second problem. If a follower has not opened the app in six months, a write into their timeline will never be read. Those writes are part of the 20 billion a day counted earlier, the part that goes to people who are not coming back soon. So do not fan out to inactive followers either. Keep a last-seen timestamp for each user. Fan out only to followers who have been active recently, and build the timeline for anyone else when they next open the app.
Now one mechanism handles both the celebrity and the inactive user, and both follow the same rule: only precompute what somebody is going to read.
4. Decide what a timeline actually stores
This choice changes the storage bill by a factor of about 50, and many answers skip it.
Store the whole post in every timeline
Each timeline entry holds the text, the author name, the timestamp and the media pointers. A read is one lookup, with nothing else to fetch and no second round trip.
It is the fastest read available, and that is why people choose it. Then you do the arithmetic. One post fanned out to 100,000 followers is 100,000 copies of the same text. At a kilobyte each, that is 100 MB of duplicated storage for one post that somebody wrote in four seconds.
It also turns every change to a post into a fanout of its own. If the author edits the text, 100,000 copies are now out of date. If they change their display name, every post they have ever written is wrong in every timeline it reached. A one-row update has become a background job with no upper limit.
Store references, and fetch the content on read
The timeline holds ids. Twitter's entry was the tweet id, the author id, and four bytes of flags for things like whether it is a retweet. Together that is twenty bytes.
Reading now takes two steps: get twenty ids, then fetch twenty posts. The second step is called hydration. It is a multi-get against a post cache, meaning one request that fetches many keys at once. It costs a few milliseconds and gives you two things. Storage drops by a factor of fifty. And a post has exactly one copy, so editing it, deleting it or renaming its author is a single write that every reader sees.
Notice that hydration is shared, and design for its tail
Hydration is less of a cost than it looks. Twenty readers of the same popular post all fetch the same cache key. The post cache keeps one copy for all of them, and that is the saving the naive design was paying storage to get. The more popular a post is, the better this works. In the naive design, a more popular post meant more copies.
The number to watch is the tail, not the average. A multi-get takes as long as the slowest of its twenty keys. A 1 percent miss rate per key gives roughly an 18 percent chance that at least one of the 20 misses. So nearly a fifth of feed loads pay a trip to the post store. Size the post cache against that number, not against a hit rate that looks fine on a dashboard.
The same reasoning tells you what to put in the cache: whole rendered posts, not raw rows. Every reader needs the same rendering. Doing it once per post instead of once per reader is the same saving again, one level up.
So the timeline stores references, not content, at twenty bytes an entry.
Does a timeline for every daily active user fit in memory?
Size one entry in Redis, then one timeline, then all of them.
Per entry, in listpack, the packed form Redis uses for
small sorted sets. Each number is a 64-bit integer: 8 B,
plus a type byte and a length byte.
post id, the member = 10 B
post time in ms, the score = 10 B
= 20 B
Per user, capped at 800 entries
800 × 20 B = 16 KB
Across 500M daily active users
500e6 × 16 KB = 8 TB
× 3 replicas = 24 TB
Redis uses that form only up to 128 entries by default.
Past it, a sorted set becomes a skiplist (a linked list
with extra pointers for fast search) plus a hash table.
Each entry is then a skiplist node (24 B, plus 16 B per
level, 1.33 levels on average), its member string, and a
24 B hash table entry with an 8 B bucket. After the
allocator rounds each one up:
per entry ≈ 105 B
800 × 105 B ≈ 84 KB
500e6 × 84 KB × 3 replicas ≈ 126 TB
Twitter's entries were also 20 B of payload (tweet id,
author id, flags), kept in a Redis list, and it reported
"a couple of terabytes of RAM" for 150M active users:
one copy at 16 KB a user, 150e6 × 16 KB = 2.4 TB
one copy at 84 KB a user, 150e6 × 84 KB = 12.6 TB
The first is in the range of their figure. The second is
already six times their figure, before counting replicas.
Store the posts inline instead, at ~1 KB each:
500e6 × 800 × 1 KB = 400 TB
50× more, and
now edits fan out tooAt 16 KB per user, every timeline fits in memory. With whole posts inside, they would not.
The 16 KB needs one Redis setting. Redis keeps a sorted set in listpack, one flat block of memory, only while the set has at most zset-max-listpack-entries entries. The default is 128, so an 800-entry timeline would become a skiplist at 84 KB. Raise the setting to 1,024 on the timeline cluster, above the 800 cap. The price is CPU on every append. A listpack has no index, so each ZADD walks the list twice: once to check that the post is not already there, and once to find its place. For 800 entries that takes roughly 10 microseconds. Even at twice the 350,000 appends a second from section 2, that is 7 seconds of CPU every second, or 7 cores across the whole cluster. The default encoding would cost 102 TB more memory instead.
The cost of storing references is the second step on the read path, hydration, which turns twenty ids into twenty posts. Each post in the cache is shared by every reader who sees it, and the hit rate is high, because a small number of popular posts get most of the reads. Hydration has its own line in the latency budget in deep dive 2.
Which data stores, and what actually forces each one
Three storage decisions have now been made, each for its own reasons, and they landed on three different kinds of store. Put them side by side, because "which database?" is the next question, and no single database fits all of them.
One relational database for posts, follows and timelines
This is the right place to start, and it lasts longer than people expect. Posts arrive at 6,000 writes a second, which one primary can handle. The follow graph needs an ordered index scan in both directions, which is what B-tree indexes do well. Even timelines could be rows.
It fails as soon as you price the read path. 300,000 feed loads a second, each needing 20 rows from a timeline table, is 6 million row reads a second. The same table also has to take the fanout writes, and those writes are the problem. Fanout is 700,000 timeline appends a second at peak. That is two orders of magnitude above the post rate, and it lands on the same machine that serves the reads.
The amount of data is not what breaks this. One data store is being asked to be a durable record and a busy queue at the same time.
Relational for posts and follows, memory for timelines
Split the data by what it is for. Posts and the follow graph are the record: they must survive, they are read by key, and they need ordered indexes. Timelines are a cache of a query. They can be rebuilt from posts and follows, and they need a read that takes 1 to 3 ms.
The fact that timelines can be rebuilt is the whole reason for the split. A lost timeline can be computed again, so it does not need to survive a crash. The store does not need to provide durability, so it can be memory.
Add a third store for the write rate that does not belong anywhere else
Likes, view counts and any signal recorded per view arrive at 10 to 100 times the post rate, and they need no joins. If you put them in the relational store, the busiest write in the system competes with the write that must not be lost.
When you say what each store gives you, the choice stops sounding like a vendor preference:
| store | what goes in it | the requirement that forces it |
|---|---|---|
| relational, sharded by user | posts, follows | ordered scans in both edge directions, and data that must survive |
| in-memory lists | timelines | a 1 to 3 ms read at 300,000/s, and rebuildable, so durability is not needed |
| append-optimised wide-column | likes, view counts | a write rate two orders of magnitude above posts, with no joins |
| object storage plus CDN | media, if the product has any | out of scope here, and worked through in Instagram |
The key fact is that timelines do not need durability. Everything else about that tier follows from it. Its three replicas are there to share the read load and to keep serving when a node fails, not to keep the data safe. It needs no write-ahead log and no backup, and a restart costs a rebuild rather than an incident. A candidate who says "Redis" has named a product. A candidate who says "this is a cache of a query, so it does not need to survive, so it can live in memory" has explained why any of several products would work.
The tables
-- Sharded by user_id.
posts (
post_id bigint primary key, -- time-sortable
user_id bigint not null,
body text,
created_at timestamptz
)
index (user_id, post_id desc) -- the author's own page
-- The same edge, stored twice, written together.
following (
follower_id bigint,
followee_id bigint,
created_at timestamptz,
primary key (follower_id, followee_id)
)
followers (
followee_id bigint,
follower_id bigint,
created_at timestamptz,
last_active_at timestamptz,
primary key (followee_id, follower_id)
)
index (followee_id, last_active_at desc) -- fan out to the living first
-- Not a table. A Redis sorted set per user, capped, in memory.
-- key timeline:{user_id}
-- member post_id
-- score the post's time in ms, read from the id's time bits
-- (exact in a double, which a post_id is not)
-- cap 800 entries = 16 KB per user, in listpack
-- config zset-max-listpack-entries 1024 (default 128)
Three things to note.
The follow edge is two tables, not one table with two indexes. A second index on one table would work at small scale. At 400 billion edges, the two directions have different hot spots, different growth and different shard keys, so each gets its own table and is sharded on its own key. A follow writes both, and accepts that they can briefly disagree.
followers carries last_active_at. This column is there for fanout, not for the follow itself. Section 3 skips inactive followers, and the fanout worker has to tell who is active from the index it is already scanning. Otherwise it costs a lookup per follower, and there can be 100 million of them.
The timeline score is the post's time in milliseconds, not the post id. The id looks like the obvious score, because ids already sort by time. But Redis stores a score as a double, a 64-bit floating point number, and a double holds whole numbers exactly only up to 253, about 9 × 1015. A Snowflake-style id puts the millisecond count above 22 bits of machine id and sequence number, so it passes 253 about 25 days after its epoch. From then on, nearby ids round to the same score. A cursor that asks for scores below the last one then skips every post that shared its score. A millisecond count fits in 41 bits, so it stays exact. The score is read from the id's own time bits, so the two cannot disagree. The id goes in the member. Redis orders members that share a score by comparing their bytes, so the set is in (time, post_id) order, the same pair the cursor in section 5 holds.
The queries that carry the product
-- 1. Fanout. Resumable, batched, and it filters the dead
-- inside the index rather than after fetching them.
SELECT follower_id
FROM followers
WHERE followee_id = $1
AND last_active_at > now() - interval '30 days'
AND follower_id > $2
ORDER BY follower_id
LIMIT 5000;
-- 2. Read the timeline. Not SQL. One range read of a
-- sorted set, newest first, from the cursor's time.
-- The bound is inclusive, because the last post shown
-- can share its millisecond with posts not yet shown.
-- ZREVRANGEBYSCORE timeline:{user} $cursor_ms -inf
-- WITHSCORES LIMIT 0 25
-- Then drop entries at $cursor_ms whose post id is at
-- or above $cursor_post_id: the last page showed them.
-- 3. Hydration. The ids from step 2, in one multi-get
-- against the post cache, falling through to:
SELECT post_id, user_id, body, created_at
FROM posts
WHERE post_id = ANY($1);
-- 4. The large accounts this user follows, merged at read
-- time because they were never fanned out.
SELECT p.post_id, p.user_id, p.body
FROM following f
JOIN posts p ON p.user_id = f.followee_id
WHERE f.follower_id = $1
AND f.followee_id = ANY($2) -- the known large set
AND p.post_id > $3
ORDER BY p.post_id DESC
LIMIT 25;
Query 1 runs about 6,000 times a second and reads up to 5,000 rows each time. It is by far the largest row scan in the system. Query 2 runs 300,000 times a second and touches one key. The cheapest query is the one the user waits on, and the expensive one is not. The whole design exists to make that true.
Be careful with query 4. It is the only join in the design, and the only limit on its cost is how many large accounts one user follows. Cap that set explicitly. Otherwise a user who follows 2,000 celebrities hits a slow path that nobody else can reproduce.
5. Page through a feed that is changing underneath you
The feed grows at the top while a user scrolls down it, so paging through it is harder here than in a list that does not change.
Offset pagination is broken, and you should be precise about why. You ask for items 0 to 19. Five new posts arrive. Then you ask for 20 to 39 and get the items that were at 15 to 34 before, so you see five posts twice. If posts are deleted between the two requests, you skip some instead. The user sees duplicate cards while scrolling, which is the one symptom requirement 5 said is not acceptable.
Cursor pagination fixes it by naming a position instead of a count. The cursor holds the sort key of the last item returned. For a chronological feed that is (timestamp, post_id), and the id breaks ties between posts written in the same millisecond. The next page asks for everything that comes after that point in the list. New arrivals at the top change nothing, because the cursor points at an item in the list, not at a distance from its start.
Deep dives
The first three come up in nearly every version of this interview. Number four is where ranked feeds change the answers above. Prepare it hardest, because most modern feeds are ranked and most candidates only prepare the chronological one.
1. How many servers, and what actually needs scaling?
Timeline store (in memory, listpack encoding) 500M daily active × 16 KB ≈ 8 TB × 3 replicas ≈ 24 TB at 256 GB per node ≈ 94 nodes default encoding, 126 TB / 256 GB ≈ 490 nodes Read tier 300,000 feed reads/s a node serving cached range reads, ~20k/s ≈ 15 nodes plus hydration multi-gets against the post cache Fanout workers 350,000 deliveries/s average, 700k+ peak a worker doing ~5,000 appends/s ≈ 70 workers plus headroom for event spikes at 12k posts/s Post store (on disk, the archive) 400M posts/day × 1 KB × 365 ≈ 146 TB/year ───────────────────────────────────────────────────────── The timeline tier is small and hot. The post store is large and cold. Sizing them together is the mistake.
The two data stores have opposite shapes and need opposite technologies. The timeline tier is 8 TB of tiny lists that are read often and rewritten constantly. That is a job for an in-memory store with a list type that appends and trims cheaply, such as a Redis sorted set in the listpack encoding. The post store is hundreds of terabytes of records that are written once and read by primary key. That is a job for a store on disk, such as the sharded relational database chosen above. Answering "one database, sharded" for both is the most common structural mistake in this design.
Two consequences follow.
The system survives losing the timeline tier, and you should say so. It is a cache. If it goes, you rebuild it slowly from the post store and the follow graph, and in the meantime the read path serves degraded feeds. The system does not survive losing the post store, so that is where the money for durability should go.
Fanout workers scale with events, not with the average. On a normal day they have plenty of room. Their peak arrives when something big happens in the world, at more than twice the average post rate. If you size for the average, feeds go stale at the moment the most people are looking.
2. Where does the 200 ms go?
edge and TLS, warm connection 5 to 20 ms fetch the timeline, one range read 1 to 3 ms merge in large accounts followed 1 to 3 ms hydrate 20 post ids, multi-get 2 to 8 ms filter blocked, muted, deleted 1 to 2 ms hydrate authors and counts 2 to 6 ms serialise and respond 2 to 5 ms ──────────────────────────────────────────────────── server side, cache warm ~14 to 47 ms one cache miss to the post store +10 to 30 ms The budget is comfortable, and it is comfortable because every step is a key lookup. The moment any step becomes a scan or a join, it stops being comfortable.
The total matters less than the shape. Every step on the read path is a lookup by key. That is not luck. It is what the whole write-path design paid for, and you have to protect it. A feature that needs "posts from the last hour by people in your city" is a scan, so it goes on a different path or into the precompute.
Hydration is the one step that can go wrong, for the tail reason in section 4: a multi-get is as slow as its slowest key. It is also the only step whose cost depends on something you do not control, which posts are popular this hour. So watch it during an event.
3. What happens when the fanout falls behind
Fanout runs from a queue, so the failure to plan for is not that it stops. It is that it keeps working while falling further behind.
One queue, workers pull from it, add workers when it backs up
This works until one celebrity post enters the queue as a single job with 100 million appends in it. One worker has to take the whole job, and it stays busy for minutes while everything queued behind it waits.
The symptom surprises people: feeds go stale for users who do not follow the celebrity at all. One large account has used up the fanout capacity for everybody.
Split the work, and give small accounts their own lane
Split the follower list into chunks, so one post becomes many jobs of a few thousand appends each. The whole fleet can then work on it in parallel, and any worker can pick up any chunk.
Then give each size of job its own queue, called a lane. A post from a small account goes into a lane where every job is tiny and finishes within a second. A post from a large account goes into a lane sized for bulk work. Now a burst in one lane cannot hold up the other.
Name the risk that is left yourself. The bulk lane can still fall behind, and the followers of those accounts see stale feeds. That is a real loss of quality, and it is the right one to accept. It has a limit, and it affects people who mostly follow accounts that post constantly anyway.
Make the read path able to cover for the write path
A stale timeline does not have to produce a stale feed.
The read path already merges in large accounts at read time, and the same merge can do more. Record the timestamp of the newest entry in each timeline. If it is older than a threshold, top up the feed at read time with a bounded query for recent posts from the reader's most active follows. The feed is correct, it costs a little more to serve, and the user sees nothing wrong.
Now fanout lag raises the cost of a read gradually, instead of breaking the feed all at once. A few seconds of lag costs nothing. A few minutes of lag costs read-path CPU, for the affected users only. And a deep queue no longer causes an incident where users can see the feed is broken.
Here is the cost. You now have a second code path that runs rarely. Code that runs rarely breaks without anyone noticing, so it will be broken on the day you need it unless you run it on purpose. Run it for a small percentage of requests all the time, so it is always being tested.
4. Ranking, and what it does to everything above
Most real feeds are not chronological, and switching to a ranked feed changes several answers given above. This deep dive shows whether a candidate has thought about feeds or has memorised a fanout diagram.
The core difficulty is that a ranked order depends on the reader, and on a model that changes. A chronological timeline is the same list for everyone who follows the same people, so precomputing it is clearly right. A ranked timeline is different for every reader, and it stops being valid when the model updates, so precomputing it fully is clearly wrong.
The design that works splits the problem in two.
Retrieval stays precomputed. Retrieval means collecting the posts the reader might want. The timeline becomes a candidate set rather than the answer: a list of post ids, produced exactly as described above. Nothing in the fanout design changes.
Ranking happens at read time, over that candidate set. A model scores those candidates, and the top twenty are returned. Scoring hundreds or a few thousand items per request is affordable, and scoring millions is not. That is the whole reason retrieval and ranking are separate stages.
| chronological | ranked | |
|---|---|---|
| what the timeline holds | the answer | a candidate set |
| ordering | done at write | done at read |
| same for all readers | yes | no |
| cost per read | one range read | one range read plus scoring |
| pagination | cursor on (time, id) | cursor on a stable rank key, not the score |
The last row is where candidates go wrong. You cannot paginate on the score. The score changes between page one and page two, so items reorder and the reader sees duplicates. The fix is to rank the candidates once, freeze that order in a short-lived session, and have the cursor point into the frozen list.
Two more things change, and here the design changes shape rather than only gaining a step.
The candidate set gets bigger, and each entry matters less. A chronological timeline holds the answer, so 800 entries is plenty. A ranked timeline holds material for the model to choose from, so you want more of it, from more sources. That includes posts that arrived while the reader was away, which they may not have seen. The fanout does not change, but the cap does, and so does what you choose to keep.
Freshness means something different. In a chronological feed, a post that arrives late appears in the wrong place, and the reader notices. In a ranked feed, a late post is scored with everything else the next time the reader loads the feed, and it lands wherever its score puts it. Ranking tolerates fanout lag better than a chronological feed does. Have this argument ready, because it connects deep dives 3 and 4.
5. What happens the moment you follow someone
This question is small and often asked, and it shows whether you have thought the precompute through.
You follow an account. Your timeline was built without them, so it contains none of their posts. Do you backfill?
The lazy answer is to do nothing, and you can defend it. Their next post fans out to you like anyone else's, so within seconds the follow works for every new post. You do not get their history, and for a chronological feed that is arguably correct: you followed them now, so you see what they say from now on.
The eager answer is to backfill on follow: merge their recent posts into your timeline immediately. It feels better to the user. It costs one bounded query and one merge for one user, and that is cheap, because follows are rare compared with reads.
The best answer does neither at write time. Backfill lazily on the next feed load, using the read-time merge that already exists for large accounts. It is a code path you already have, and a follow stays two row inserts, one in each follow table, with no fanout at all.
Then add a limit. A follow of a large account must not trigger a backfill of their entire history. A user who follows fifty accounts in one sitting would set off fifty bounded queries in a burst. Cap how much you merge in, and let the rest arrive as the accounts post.
Unfollow is the reverse, and the answer is the same as in section 1: filter at read time, let the entries age out, and never scan a timeline to remove things.
6. Deletes, blocks, edits and privacy
Every one of these is the same problem: the timeline holds a reference to something whose state has changed since it was written.
Fixing them all at write time is the wrong approach. Deleting a post that reached 100 million timelines would need 100 million removals, and blocking someone would need a scan of your timeline for their posts.
Filter at read time instead. Hydration already fetches each post, so a deleted post comes back missing and is dropped. A blocked author is checked against a small per-reader block list held in the read path. A post that has gone private fails the same check. All of this is nearly free, because you were already fetching the post to render it.
Two consequences to state:
Your page size is not your fetch size. If you request 20 ids and 3 are filtered out, you return 17, and the user sees a short page. So over-fetch, usually by 20 to 30 percent, and trim to the page size after filtering.
Deleted posts become invisible, not absent. The entry stays in timelines until it ages out, and it is never shown. That is correct, and you should say so out loud. "We delete it from every timeline" sounds responsible, and it means 100 million writes that nobody needed.
7. Cold start, and the users you are not fanning out to
The staff answer in section 3 stopped fanning out to inactive users. That raises a new question: what happens when one of them comes back?
Their timeline is empty or months old. Building it on demand means running the read-time query from the set up, which we showed is expensive. The difference is that it now runs for one returning user, not 300,000 times a second. A query that is unaffordable at the read rate is affordable at the rate inactive users come back.
So on their first request, run the fallback path, fill the timeline, mark them active, and let normal fanout take over. Their first feed load is slower, and that is acceptable for someone who has not opened the app in months.
The same mechanism handles brand-new users, and for them the harder problem is not technical. A new account follows nobody, so the correct feed is empty. That is a product problem, solved with suggested accounts and recommended posts. Call it a product problem in the interview, rather than designing your way around it.
8. How do you know it is working?
In an incident, you must be able to answer four questions. How long is the fanout lag? What fraction of feed loads hit the fallback path? Are the hydration caches holding up? Is anyone getting duplicate posts?
- Fanout lag, by queue lane, at p50 and p99. This is the main health signal for the whole design, because it is what users notice as "the app is broken".
- Feed load latency, split by warm and cold path. The cold path is the fallback query. If you average the two, you will not see the fallback path slowly turning into the common path.
- Hydration cache hit rate, and the distribution of misses per request rather than the mean, for the tail reason in section 4.
- Duplicate rate in paginated sessions, sampled. It is the one correctness bug users report, and nothing else catches it.
- Do not label metrics by user id or author id. Each id becomes its own metric series. Because of the follower distribution, a handful of authors would produce most of those series, and they are the ones you will most want to look at during an incident. Keep them in sampled logs and a top-N list instead.
Final design
One post, and one feed load:
- A user posts. The API writes it to the post store and returns
202with the post id. Nothing has fanned out yet. - A fanout job is queued. A dispatcher reads the author's follower count and decides: below the threshold it fans out, above it it does not, and the post lands only in the author's own recent-posts list.
- For fanout, the follower list is read in pages and split into chunks of a few thousand. Chunks go to the small-account lane or the bulk lane depending on the author's size.
- Workers add the post id to each active follower's timeline, scored by the post's time in milliseconds. The post id is the member, so a retry is a no-op. Then they trim the list to 800 entries.
- A reader opens the app. The read path fetches their timeline with one range read, and in parallel fetches recent posts from the handful of large accounts they follow.
- If the timeline's newest entry is older than the staleness threshold, it tops up with a bounded fallback query for that reader's most active follows.
- It merges the sources, over-fetches by about 25 percent, hydrates the ids against the post cache, filters blocked, muted and deleted, and trims to the page size.
- It returns the page with an opaque cursor holding
(timestamp, post_id)of the last item, so the next page is unaffected by anything that arrives at the top meanwhile.
Four numbers justify this shape. There are 300,000 feed reads a second against 6,000 writes, so the work moves to the write side. Each timeline is 16 KB in Redis's listpack encoding, so 500 million of them fit in 8 TB of memory. The fanout threshold is roughly 1.4 million followers, because that is a five second freshness budget multiplied by the observed fanout rate. And the post store grows by 146 TB a year, but almost nobody reads it directly, because a cache in front of it serves nearly every read.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
At this level, breadth matters more than depth, and it is fine to be led through the deep dives.
You should get to a precomputed timeline rather than a query per read. You should also be able to say why: reads far outnumber writes, so the expensive work belongs on the write side. You should know that the follow graph needs to be readable in both directions, and that a feed is paged rather than returned whole.
You are not expected to raise the celebrity threshold, ranking or fanout lag unprompted, but you should reason about them once they are raised. Noticing that a timeline should hold references rather than whole posts is a good signal at this level.
Senior
You drive the structure, and three things should appear without prompting.
The read-time query, priced and rejected. "We use fanout on write" is only a conclusion. Show the arithmetic that forces it, because you need the same number later for the threshold.
The celebrity case, with a mechanism. Skip fanout above a threshold and merge at read time. State why this works: a celebrity's posts are one list read by millions, which is the best case for a cache, where fanout would have written millions of copies.
References, not content, in the timeline. That makes hydration a separate step on the read path, with its own latency and its own cache.
When prompted, you should get to three more: cursor pagination and why offset breaks, a cap on timeline length, and filtering deletes and blocks at read time instead of removing them from every timeline.
Staff+
At this level, the job shifts from producing the design to spotting which numbers control it.
Derive the threshold rather than choosing it. The maximum follower count equals the freshness budget times the fanout rate. Once it is an equation, a product decision about feed freshness turns directly into an infrastructure number. You can then tune the system, instead of arguing about the threshold again each time.
Notice that the same rule covers two problems. Only precompute what somebody will read. That one rule is both the celebrity fix and the inactive-user fix, and it removes the writes that go to followers who are gone for months.
Separate retrieval from ranking, and follow it through to pagination. Freeze the ranked order per session, or the cursor is meaningless.
Make the read path able to cover for the write path. Then fanout lag costs extra read work instead of causing an outage. Run that path all the time, so it works when it is needed.
Say which tier you would let fail. The timeline store is a cache and can be rebuilt, and the post store cannot. Saying so tells the interviewer you know which parts the system cannot lose.
Be able to say what you would not build: fanout to inactive users, deleting posts from every timeline, offset pagination, a consistency guarantee between different users' feeds, or one database for both the timeline tier and the post archive. A team could ship each of these and regret it.
Sources
Every real-world figure here comes from a published source rather than an anecdote. Twitter's material is still the most detailed public account of this problem, so most of the numbers come from it. The Redis memory figures come from Redis's own docs and source code.
- High Scalability, The Architecture Twitter Uses to Deal with 150M Active Users, 300K QPS, a 22 MB/S Firehose, and Send Tweets in Under 5 Seconds. The source of most figures used above. 300,000 timeline reads a second against 6,000 writes. 400 million posts a day, and 30 billion fanout deliveries a day, also quoted as 300,000 a second. Home timelines capped at 800 entries, replicated three times, and held in Redis's native list type in a cluster of "a couple of terabytes of RAM". Delivery to a million followers at 3.5 seconds p50 and up to 5 minutes p99. And the decision to stop fanning out for very large accounts and merge them at read time instead.
- Raffi Krikorian, Timelines at Scale, Twitter. The talk the figures above are drawn from. It includes the timeline entry layout of tweet id, author id and four bytes of flags, the 20 bytes of payload behind the comparison with Twitter's memory figure in section 4.
- Twitter, Snowflake. The id layout: 41 bits of milliseconds above 10 bits of machine id and 12 of sequence number. That puts a post id past 253, which rules it out as a sorted set score.
- Redis documentation, ZADD and Memory optimization. Scores are doubles, exact for whole numbers only up to 253, and members that share a score are ordered by their bytes. Small sorted sets get a packed encoding up to
zset-max-listpack-entries, 128 by default, as a trade of CPU for memory. - Redis, source code at version 7.4.0.
redis.confsets the 128 default.listpack.cstores a 64-bit integer in 10 bytes, andt_zset.cstores each entry as two of them and walks the list on every insert.server.handdict.cgive the skiplist node and hash table entry that the default encoding uses instead.