GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a News Feed (Twitter, Facebook)

Copy post IDs to the followers who will read them, pull the famous accounts at read time, and keep retries, paging and privacy correct. Built one step at a time, with experiments you can run.

A news feed shows each person recent posts from the accounts they follow. Store each post once. When an ordinary account posts, a background worker copies the post’s ID into the timeline of every follower who has been active this month. Very large accounts are not copied; their posts are fetched when a follower reads. The feed merges both, checks access, and returns a page with a cursor.

Difficulty: Medium. Reported in interviews at Amazon, Cloudflare, Brex, Asana, Snapchat. Also asked as Design Twitter, Design the Facebook News Feed, Design an Instagram feed, Design a timeline.

Practise one part of it on a canvas that tests your design: Post to a Feed With a Celebrity.

How do you design a news feed like Twitter or Facebook?

A news feed shows each person the recent posts of the accounts they follow, newest first, in pages they can keep scrolling. The hard part is that one post can have millions of readers. The page still has to load in a fraction of a second.

  1. Post: Meet at the bridge, 7:00. Saved once, then it has to reach every follower who reads.
  2. Follow: Follow Cycling club. A private account approves first, and a block cuts both ways.
  3. Open the app: Newest posts first. The page must come from one prepared list, not 300 lookups.
  4. Scroll: Page 2, no repeats. New posts keep arriving. Page two must not repeat page one.
  5. Block: Mira blocks Leena. Her photo must vanish from the next page, cached lists included.
A footballer with 50 million followers can post at the same moment as a cycling club with 400. That is what makes every step hard.

Here is the failure that makes the problem hard. Leena opens the app before a morning ride. Her cycling club posted the meeting point a minute ago, and it is not there. At the same moment, a footballer with 50 million followers posted a photo. The system is still copying that photo’s ID into ten million timelines. The club’s small job is waiting in the same queue behind it.

Both posts were saved in a few milliseconds. Copying made one of them late. One post is one record for its author, and it can become millions of entries for its readers. So the design is mostly about when that copying happens, who pays for it, and what is allowed to wait.

A second failure hides in the same list. Leena’s friend Mira blocks her after an argument. Mira’s photo from last night is still sitting in Leena’s list. The next page must not show it.

Every screen in the strip hides a failure like these, which is why interviewers ask this problem.

Here is the design in four sentences. Store each post once, and keep a short list of post IDs for every active reader. When an ordinary account posts, a background worker adds the new ID to each follower’s list. When a famous account posts, nothing is copied; its posts are fetched when a follower opens the app. The feed merges both, checks access and returns a page.

The rest of this page is about keeping that design correct when something goes wrong.

What is the interviewer testing?

Most candidates draw a post service, a fan-out queue and a timeline cache within ten minutes. That diagram is correct, and a mid-level answer often stops there.

The interviewer then pushes on five questions. A footballer with 50 million followers posts: what happens? A worker crashes halfway through the followers: who misses the post? A new post arrives while Leena scrolls: does page two repeat anything? One post goes viral: what stops one shard from melting? Mira blocks Leena: why is her photo still in Leena’s list?

A senior answer handles the first four. A staff answer also handles access checks when replicas lag, ranking that stays still while you scroll, and rebuilding lost timelines without an outage.

Spend most of the deep-dive time on fan-out and the famous account. A crashed worker, paging and a block are the usual follow-ups. A viral post and ranking are where a staff round goes. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

People you follow, or recommendations?
Picture Leena’s feed holding only her club, her sister and a footballer she follows. Now picture a For You feed full of strangers’ posts. The second needs a recommendation system and is a different interview. Assume the following feed.
Newest first, or ranked?
A ride cancellation posted an hour ago may matter more to Leena than a headline from a minute ago. Ranking changes the order of a page, not how posts reach it. Start newest first and add ranking at the end.
How large can one account get?
A club with 400 followers and a footballer with 50 million behave nothing alike. If the largest account has a few thousand followers, the simple design is enough. Ask, because the answer decides the hardest part of the design.
What must a delete or a block do?
Mira blocks Leena. Must Mira’s photo vanish from Leena’s next page, or within the hour? Assume the next page. That rules out trusting any cached copy of the feed.

Functional requirements

On the board: Functional requirements
1. Post text and photos; delete
2. Follow, approve, unfollow; block
3. Feed: followed accounts, newest first
4. Scroll without repeats; new-posts banner
5. Deletes and blocks hold next page
out: For You, likes, search, ads

Say it, don’t write it: The feed holds IDs that point at posts, so an edit or a delete changes one record.

The brief is a feed of posts from accounts you follow. Two people use it: an author who posts and a reader who scrolls.

  1. An author publishes a post with text and up to four photos, sees it on their own profile at once, and can delete it.
  2. A reader follows and unfollows accounts. A private account approves each follower. Anyone can block anyone.
  3. A reader sees posts from the accounts they follow, newest first, and scrolls without seeing a post twice. A banner says when newer posts are waiting.
  4. Deleted posts, and posts from someone who has blocked the reader, stop appearing from the next page on.

Out of scope

  • The For You recommendation feed
  • Likes, comments and reposts (the feed shows their counts only)
  • Search, notifications and direct messages
  • Ads
  • Training a ranking model

One product rule matters later. When Leena follows a new account, her feed gains up to 20 of its posts from the past week. She is not promised its whole history; the account’s profile page has that.

Non-functional requirements

On the board: Non-functional requirements
• Page < 300 ms (p95)
• New post in timelines < 5 s (p99)
• A saved post is never lost
• Delete or block holds from next page
• No post twice in one scroll
• 99.9% of feed requests succeed

Say it, don’t write it: Speed, freshness and privacy each get their own number.

Leena will not notice if the club’s post reaches her three seconds late. She will notice a page that takes two seconds to appear. Mira will notice if her photo keeps showing up after a block. So speed, freshness and privacy each get their own target. The numbers are illustrative interview targets, not measurements of any real service.

  • 95% of feed pages return within 300 ms, measured on the server in each region.
  • An ordinary account’s post reaches its active followers’ timelines within 5 seconds, 99% of the time. The clock runs from saving the post to its last timeline insert.
  • A saved post is never lost, and its author sees it on their own profile at once.
  • A delete or a block holds from the next page served, in every region.
  • A post appears at most once in one scroll.
  • 99.9% of feed requests succeed each month. If the timeline cache fails, pages are built on read instead.

The numbers on this page come from one made-up workload. 20 million people read their feed each day, and each opens it 10 times. Over a month, 50 million different people open the app. People publish 2 million posts a day. On average, a post has 200 followers who opened the app this month. A reader follows 300 accounts on average. The busiest hour runs at five times the average rate. Each deep dive below works out the numbers it needs from these.

Out of scope

  • A strict order across authors (a post can land a second after a newer one)
  • Recalling photos already downloaded to a phone
  • Pushing every new post to open apps as it happens

Core entities

On the board: Core entities
Post(id, author, text, photos, state)
Follow(follower, followee, state)
Block(blocker, blocked)
TimelineEntry(reader, post_id, author)
FanoutJob(post, chunk, done)

Say it, don’t write it: A post must never be lost. A timeline can always be rebuilt.

Follow one post through the system. The club publishes the meeting point. The post store saves it once, as post P9. Leena’s timeline gets a small entry that points at P9. Her page then reads P9’s text from the post store. If the club fixes a typo, one record changes, and every timeline still points at the right text.

Five records carry the design. A post holds its ID, its author, its creation time, its text, its photo IDs, its visibility and its state. It answers what P9 says, and whether it is still live. A follow joins a follower to an account, with a state of requested or approved. It answers whom Leena follows, and who follows the club. A block records who blocked whom. It answers whether Leena may see Mira’s posts right now.

A timeline entry holds a reader, a post ID and that post’s author ID. It answers which recent posts Leena’s page starts from. A fan-out chunk holds a post, the range of follower IDs it covers, and whether it is done. Together, a post’s chunks answer which followers still need P9.

A post must never be lost, so it lives in a durable store with copies. A timeline entry can always be rebuilt from posts and follows, so it lives in memory. Losing a timeline costs time, not data. That one distinction carries the whole design.

Where the data lives

Give every post an ID that sorts by time. Twitter’s Snowflake packs 41 bits of milliseconds, 10 bits of machine number and 12 bits of sequence into one 64-bit number. Machines create IDs without asking each other. A larger ID means a later post, to within about a second. Sorting by ID is then sorting by time. A single number can mark a place in the feed. The creation time can be read back out of the ID’s top bits, so nothing else needs to store it for ordering.

Posts go in PostgreSQL, split into shards by author_id. The club’s posts all live on one shard, so its profile page is one indexed read: the newest 20 rows for that author, ordered by post_id. A timeline entry carries the author ID, so the feed knows which shard holds each post it needs. The outbox table lives on the same shard as the posts it describes, so saving a post and its event is one local transaction. Every page reads the text of 20 posts, so a cache sits in front of the post store. The viral-post deep dive shows what that cache has to survive.

Follows go in a relational table split by user. Store each follow twice: once keyed by follower and once keyed by followee. The feed asks “whom does Leena follow?” and the fan-out asks “who follows the club?”. Those questions walk the data in opposite directions, so each needs its own index. When the two copies live on different shards, one is the source of truth and a background job repairs the other. A daily job also marks each follower-side row with whether that follower opened the app in the last 30 days, so fan-out can page through active followers only.

Timelines live in Redis. Each timeline is a sorted set. The member is the post ID followed by the author ID, both padded to a fixed width. The score is the creation time in milliseconds, read out of the post ID. Taking the time from the ID keeps Redis order and cursor order identical. Keep the whole ID out of the score. Redis stores scores as floating-point doubles, which hold whole numbers exactly only up to 2^53 (ZADD reference), and a Snowflake ID can be larger. Two posts in the same millisecond tie on score. Redis then orders them by member, byte by byte. That is why the post ID comes first and has a fixed width. To page, ask Redis for scores up to the cursor’s millisecond and drop members at or above the cursor’s ID. After each insert, trim the set to its newest 800 entries. Only readers active in the last 30 days have a timeline at all.

API

On the board: API
POST /posts {clientRequestId, text}
PUT, DELETE /me/following/:id
PUT /me/blocks/:id
GET /me/feed?limit=20&cursor=…
GET /me/feed/new?since=postId

Say it, don’t write it: The cursor is the last post’s ID, so a new post cannot shift page two.

Publishing is a small, rare write, so it returns as soon as the post is saved and never waits for followers. Reading a page is the hot path, so it takes a cursor and returns a bounded page.

RequestResponseRule it enforces
POST /posts with a client request ID201 with the post IDA retry with the same request ID returns the same post
DELETE /posts/{id}200; the post is marked deletedOnly the author may do it; the next page anywhere leaves it out
PUT /me/following/{accountId}200, following, or requested for a private accountRepeating it changes nothing
DELETE /me/following/{accountId}200Takes effect on the next page, before any cleanup
PUT /me/blocks/{accountId}200Hides each person’s posts from the other from the next page
GET /me/feed?limit=20&cursor=…Up to 20 posts and a next cursorThe reader comes from the login, never from a parameter
GET /me/feed/new?since={postId}How many newer posts are waitingCheap enough for an open app to ask every 30 seconds
Concrete exchangeMeaning
POST /posts with {"clientRequestId":"c-77","text":"Meet at the bridge, 7:00","photoIds":[]}201 {"postId":"P9","createdAt":"2026-09-24T06:14:02Z"}
GET /me/feed?limit=20200 {"items":[{"postId":"P9","author":{"id":"club","name":"Cycling club"},"text":"Meet at the bridge, 7:00","likeCount":12}],"nextCursor":"P9"}
GET /me/feed?limit=20&cursor=P9Only posts older than P9, and a new cursor
GET /me/feed/new?since=P9200 {"count":3}; the app shows “3 new posts”

The cursor is the ID of the last post on the page. The next request asks for posts older than that ID. Because IDs sort by time, one number is enough. A post that arrives in between cannot shift the boundary. The app receives it as an opaque token, so it cannot build one by hand, and the server can change what is inside later. A ranked feed, for example, puts a position there instead. A cursor says where to continue. It never grants access to a post.

Photos never pass through the feed. The app uploads them straight to object storage. The feed returns short-lived signed URLs that a CDN serves. The video streaming breakdown walks through that upload path in full.

Step 1: publish a post and read your own profile

The club’s organiser taps Post. The Post API checks who is posting, saves P9 with the client’s request ID, and returns. A retry with the same request ID finds P9 instead of saving a second post. The club’s profile reads the post store directly, so P9 is there on the next refresh.

The interactive version of this example is available when JavaScript loads.

Nothing has been copied anywhere. That keeps publishing fast however many followers an account has.

Step 2: follow an account

Leena taps Follow on the club’s page. The Feed API records the follow twice in the graph, once under Leena as follower and once under the club as followee. If the club were private, the follow would stay requested until the organiser approved it. A request alone lets Leena see nothing. Tapping Follow twice still leaves one follow.

The interactive version of this example is available when JavaScript loads.

Follows go through Leena’s API because she is the one following. A block works the same way: Mira blocking Leena is one row in the graph.

Step 3: build a page when Leena opens the app

Leena opens the app. The Feed API asks the graph for the 300 accounts she follows. It asks the post store for each account’s newest posts, merges them newest first and keeps 20. It drops any post that is deleted or whose author has blocked Leena. Then it fetches the text, the author names and the like counts for those 20 in batched reads, and returns the page with a cursor.

The interactive version of this example is available when JavaScript loads.

This design is correct, and for a small app it is enough. Its cost grows with every open: each page repeats 300 lookups, even when nothing new was posted. The deep dives start there, with the question every interviewer asks next.

Fan-out on write or fan-out on read: who pays for a post?

It is 7:40 on a Monday, the busiest hour. Leena opens the app on the train. The Feed API asks the graph for the 300 accounts she follows. Then it asks the post store for each account’s newest posts. Those are 300 lookups, spread across many shards, and her page waits for the slowest of them.

Say one lookup in a thousand takes longer than 300 ms, because its shard is busy or pausing. That sounds rare. A page makes 300 lookups, though. The chance that all 300 are fast is 0.999 multiplied by itself 300 times, about 0.74. So about one page in four waits on a slow shard and misses 300 ms. The target allows one in twenty.

Now count the whole system. 20 million readers open the feed 10 times a day. 20,000,000 × 10 is 200 million pages a day. 200,000,000 ÷ 86,400 seconds is about 2,315 pages a second. The busiest hour runs at five times that, about 11,575. At 300 lookups each, the peak is 11,575 × 300, about 3.5 million lookups a second.

Most of that work repeats itself. Leena’s club posts twice a day, and her ten opens ask it for new posts ten times. Posts are far rarer than pages. 2 million a day is 2,000,000 ÷ 86,400, about 23 a second, or 116 at the peak. 200 million pages against 2 million posts means reads outnumber posts 100 to 1. Building every page on read puts the work on the side that happens a hundred times more often.

So flip it, and do the work once, when a post is written. When the club posts, a worker writes the post’s ID into each follower’s timeline. Leena’s page then starts from one read of her own list, and one batched read of the 20 posts it names. That is fan-out on write. Building the page from the accounts is fan-out on read.

The first version copies each post to every follower. Replay the club’s post. The club has 400 followers, so a worker makes 400 writes. Only 200 of those followers opened the app this month. The other 200 entries sit in lists nobody reads, until newer posts push them out. Half the club’s fan-out goes to people who are away.

So copy only to followers who opened the app in the last 30 days. A daily job marks each follower row as active or not, and fan-out pages through the active rows only. The club’s post now costs 200 writes, one per reader likely to see it.

A reader who returns after two months has no timeline. Their first open builds one with the pull path, 300 lookups once, and marks them active again. From then on, new posts are pushed to them.

Price the fix for the whole system, using the workload’s average of 200 active followers per post. 2 million posts a day × 200 is 400 million timeline inserts a day. 400,000,000 ÷ 86,400 is about 4,630 inserts a second, or 23,150 at the peak. Say the whole worker pool writes 50,000 inserts a second. The peak uses less than half of it.

Pulling did 200 million pages × 300 lookups, 60 billion a day. Pushing does 400 million inserts. A page now starts from one read of the reader’s own list instead of 300 lookups. It still reads its 20 posts and checks access, as every design must.

Memory is the next cost. In this design’s Redis layout, an entry’s member is the post ID and the author ID, each written as 19 digits with a separator between. That is 39 bytes, and the score adds 8, so 47 bytes of payload. Each timeline keeps its newest 800 entries and trims the rest. 50 million monthly readers × 800 entries × 47 bytes is 1.88 TB, or 5.64 TB with three copies. Writing the two IDs as 8-byte binary numbers instead of text would roughly halve that. Three rules keep the bill down: IDs rather than posts, a cap of 800, and timelines only for readers active this month.

Twitter described the same shape in a 2012 conference talk. Its target was to deliver a post to followers within 5 seconds. A post from an account with 31 million followers could take up to 5 minutes. Each timeline entry held the post ID, the author’s ID and 4 bytes of flags. As two 8-byte IDs and the flags, that is about 20 bytes. Timelines were capped at 800 entries. They were kept only for people who had logged in within 30 days. (High Scalability’s 2013 write-up of the talk)

Those byte counts are payload only. A Redis sorted set keeps each entry in two structures, a skip list and a hash table. So the real memory per entry is larger still. Measure it before buying machines.

Copying also creates chores. When Leena follows a new account, her list has none of its earlier posts. A small job copies up to 20 of its posts from the past week into her timeline. When she unfollows an account, its entries are still in her list. The next page drops them at once, because every page checks that she still follows each author. The privacy deep dive shows that check. A job removes the entries later.

Leena also expects her own new post in her feed at once, before any worker reaches her timeline. Fan-out writes each post into its author’s own timeline too, but that takes a moment. So page one also merges in the reader’s own newest posts, read from the post store. The merge drops the duplicate ID once fan-out lands. The per-page check that she still follows each author skips her own posts.

The experiment prices pull, the “I’d pull it” tab, against push, the “I’d push it” tab, for three kinds of account. Each account’s followers open the app at their own rate: 8 times a day for the club and the footballer, and 4 for the news wire. Guess first, then run one day.

The interactive version of this example is available when JavaScript loads.

The club is easy. Pushing costs 400 writes a day. Pulling would cost 1,600 reads, because its 200 active followers each open the app 8 times a day.

The news wire is the opposite. It posts 60 times a day to 400,000 active followers, who each look 4 times. Pushing costs 24 million writes, and pulling costs 1.6 million reads. One of its posts also needs 8 seconds of the whole pool.

The footballer is the surprise. Pushing is the smaller daily total, 30 million writes against 80 million reads. It still fails, because each single post needs 200 seconds of the whole worker pool.

Two different tests decided these three. One is the burst: how long one post holds the pool, which grows with active followers. The other is the daily cost, which compares how often an account posts with how often its readers look. The footballer fails the first test, and the news wire fails both. The experiment gives a timeline write and a read of an account’s recent posts the same cost. In production they differ, so plug in measured costs. The shape of the answer holds: push what is cheap to push, and pull what is not.

Now shrink the app. Say 50,000 readers each follow 100 accounts and open the app 10 times a day. That is 500,000 pages a day, about 6 a second, or about 29 at the busiest hour. At 100 lookups a page, the peak is about 2,900 lookups a second. One indexed database can serve that with no queue, worker pool or timeline cache to run. So for a small app, building on read is the whole answer. Add fan-out when measurements show page time or database load climbing with the number of follows.

At this page’s scale, copying adds a queue and a pool of workers behind the post store.

The interactive version of this example is available when JavaScript loads.

Publishing still returns in milliseconds. All the copying happens behind the post store, where a failed step can be retried.

The gap: Gathering 300 accounts on every open makes each page wait for its slowest lookup.

Option 1: Build every page when it is read (fan-out on read)

Each page looks up the newest posts of every followed account and merges them.

Works when: The app is small, such as 50,000 readers following 100 accounts each.

Breaks when: At the peak it makes 3.5 million lookups a second, and a slow shard delays about one page in four.

Option 2: Copy every post to every follower

A worker writes each new post’s ID into every follower’s timeline.

Works when: Nearly every follower opens the app often.

Breaks when: Half the club’s writes go to followers who have not opened the app this month.

Option 3: Copy post IDs to active followers only (start here)

Write each post’s entry only into the timelines of readers active in the last 30 days, capped at 800.

Works when: Ordinary accounts, whose peak of 23,150 inserts a second fits the pool.

Watch for: A returning reader has no timeline, and one very large account can still hold the pool for minutes.

Fix within it: Build a returning reader’s timeline on their first open, and pull very large accounts, as the next deep dive shows.

In the interview: Open with option 3 and one line of arithmetic: 200 million pages a day against 2 million posts. Give option 1 as the right answer for a small app. When the interviewer names a very large account, move to the next deep dive rather than stretching this one.

Say this: Reads outnumber posts 100 to 1, so I do the work when a post is written. A worker copies each post’s ID and author ID into the timelines of followers active in the last 30 days, capped at 800 entries. A page then starts from one read of the reader’s own list, and a returning reader gets a timeline built on their next open. Very large accounts break this, so I pull those at read time.

How do you handle an account with 50 million followers?

At 6:14:01 the footballer posts a photo from last night’s match. Ten million of his 50 million followers opened the app this month, so fan-out owes ten million timeline inserts. Fan-out splits each post into chunks of 100 followers. Every chunk waits in one shared table of work, which the pool drains oldest first. His post becomes 100,000 chunks. At 6:14:02 Leena’s club posts the meeting point, and its two chunks join the table behind his. At 6:15:00 Leena opens the app. The meeting point is not there.

Do the arithmetic. The whole pool writes 50,000 inserts a second. 10,000,000 ÷ 50,000 is 200 seconds of the whole pool for one post. The club’s 200 inserts are 4 milliseconds of work. They wait behind his chunks and start at 6:17:21. When Leena opened the app, 59 × 50,000, about 2.95 million of his inserts, were done. None of the club’s were. The club’s post reached her timeline about 200 seconds after it was posted, forty times the 5-second target.

Nothing on the page-latency graph moved. Leena’s page loaded as fast as ever; it was simply old. Fast pages can still be stale pages, so freshness needs signals of its own. One is the age of the oldest unfinished fan-out job, split by account size. The other is the time from saving each post to its last timeline insert, which is the 5-second promise itself. Both jumped at 6:14.

The first idea gives large accounts their own table of work and their own workers. Replay 6:14. The club’s chunks go straight through in 4 milliseconds, and Leena sees the meeting point. The footballer’s post still takes 200 seconds on a pool of the same size. To reach all ten million followers within 5 seconds, a pool needs 10,000,000 ÷ 5, which is 2 million inserts a second. That is 40 times the whole shared pool. He posts 3 times a day, so that pool would work for about 15 seconds a day and sit idle for the rest.

So stop copying his posts at all. Keep one author timeline for the footballer in Redis: a sorted set of his recent post IDs, scored by time like every timeline. Publishing a post adds one member to it, and a miss refills it from the post store. His followers’ own timelines never receive his posts. When a follower opens the app, the Feed API reads their timeline and the author timelines of the pulled accounts they follow. It merges them by time, and the same cursor works on every list.

Replay 6:14. The footballer’s photo costs one write. The club’s chunks run at once, and its 200 inserts land at 6:14:02. At 6:15 Leena’s page reads her timeline, which holds the meeting point. It reads the footballer’s list, which holds the photo. The merge puts the meeting point first, because it is one second newer. Both posts are on her page, and neither waited.

The experiment steps through a page Leena loads later that morning. Her pushed timeline is on the left, and the footballer and a news wire are pulled. At each step the merge takes the newest post among the three heads, and one step is crossed out.

The interactive version of this example is available when JavaScript loads.

Each step compares only three heads, so a 20-post page takes a few dozen comparisons. The expensive part is fetching the lists, not merging them.

The crossed-out step matters later. The footballer was pushed until this morning, so his 9:06 post is in Leena’s timeline and in his own list. The merge skips the second copy because it carries the same ID.

The interactive version of this example is available when JavaScript loads.

A pulled account’s post reaches its author timeline through the outbox. The post and its outbox row commit together, in one transaction, as the worker-crash deep dive below describes. The outbox relay then appends the post’s ID to the author timeline, and retries until Redis accepts it. The append is safe to repeat, because a sorted set holds each ID once.

The tempting shortcut is for the Post API to append the ID itself, right after the commit. That is two writes with a gap between them. If the Post API crashes in the gap, or its Redis call fails, the post is saved and the list does not hold it. The author timeline is a cache of the post store and refills only on a miss, so it stays stale until it expires. Deleting the key after a failed append makes the next read refill the list, but that covers only a failed call. A Post API that crashes between the two writes deletes nothing.

Pulling moves the footballer’s cost from writes to reads. His 10 million active followers open the app 8 times a day, the experiment’s rate. That is 80 million reads of his list a day. 80,000,000 ÷ 86,400 is about 926 a second, or about 4,630 at the peak. All of them name one key, and that rate fits on one cache node. A surge many times larger is the viral-post problem, and the viral-post deep dive copies this list the same way.

A reader can also follow twenty pulled accounts, and each is one more list to fetch. Fetch them in parallel, with a deadline. If a few are slow, return the page without them and mark it as possibly incomplete. A page one post short beats a page that misses 300 ms.

That leaves the line between push and pull. The burst test is plain arithmetic. One post needs its active followers ÷ 50,000 seconds of the whole pool. 50,000 × 5 is 250,000, so an account with more active followers than that misses 5 seconds.

A follower threshold captures that test and misses the daily cost. Picture a local news desk with 100,000 active followers. It posts 60 times a day, and its readers look 4 times. One post needs 2 seconds of the pool, well under the line. Pushing still costs 100,000 × 60, which is 6 million writes a day. Pulling costs 100,000 × 4, which is 400,000 reads. Pushing costs 15 times more, yet a follower threshold would push it.

So decide per account, from both measurements. A daily job pulls an account when pushing costs more than pulling. It also pulls an account when one post needs more than 5 seconds of the whole pool. Only accounts above a size floor, say 10,000 active followers, are ever considered. Below it, one post costs the pool a fifth of a second, and a pulled list would add a fetch to every follower’s page for almost no saving. The floor keeps the pulled set small, so every Feed API server keeps the whole set in memory. A page compares Leena’s follow list with that set to learn which author lists to read.

The line creates the last problem: accounts that cross it. Say an account sits near the line and flips every day. Each switch risks posts that neither path holds. So switch only after the gap has held for several days.

The order of a switch matters too. Moving from push to pull, readers start pulling the account first, and workers stop pushing it afterwards. For a while both paths hold its posts. That overlap is the 9:06 post in the experiment, and the merge’s duplicate check absorbs it. Stop pushing first instead, and a post published between the two steps reaches neither path. Moving from pull to push, workers backfill the account’s recent posts into timelines before readers stop pulling.

The footballer now costs one list of recent posts, shared by all his followers, instead of ten million writes for every post.

The gap: One post that must reach 10 million timelines takes 200 seconds of the whole pool, and everything queued behind it waits.

Option 1: Push it like any other post

The footballer’s post joins the shared table of fan-out work.

Works when: No account has more than 250,000 active followers, the most one post can reach within 5 seconds.

Breaks when: The club’s post waits about 200 seconds behind one of his.

Option 2: Give large accounts their own queue and workers

Large fan-outs run on separate workers, so ordinary posts go straight through.

Works when: A few accounts are large, and minutes of delay for their own posts is acceptable.

Breaks when: Reaching 10 million followers in 5 seconds needs 2 million inserts a second, idle most of the day.

Option 3: Pull large accounts at read time and merge (start here)

Each large account adds its posts to one shared author timeline, and a page merges it with the reader’s own by time.

Works when: Some accounts have millions of followers.

Watch for: A reader who follows many pulled accounts has one more list to fetch for each.

Fix within it: Fetch pulled lists in parallel with a deadline, and mark a page possibly incomplete when some are slow.

Option 4: Decide push or pull per account, from measurements

Above a floor of 10,000 active followers, a daily job pulls an account when pushing costs more, or when one post needs more than 5 seconds.

Works when: Some accounts post far more often than their readers look, like the local news desk.

Watch for: An account near the line that flips back and forth.

Fix within it: Switch only after the gap has held for days, and let the two paths overlap during a switch.

In the interview: Open with option 3 and the 200-second arithmetic. Give option 2 in one sentence: it frees the club’s post and keeps the ten million writes. Add option 4 when the interviewer asks where the line between push and pull sits, and say what a switch costs.

Say this: One post from a 50-million-follower account would hold the whole fan-out pool for 200 seconds, and ordinary posts would wait behind it. So I stop copying very large accounts. Their posts go into one shared author timeline, and a follower’s page merges it with their own timeline by time. If asked where the line is, I decide per account from measured push and pull costs, with an overlap during a switch.

A fan-out worker crashes halfway through the followers. Who misses the post?

The club posts P9, and a fan-out event for it reaches Kafka. A planner reads the event and writes P9’s fan-out work into the database as chunk rows. Each row records whether its chunk is done. Workers claim chunk rows, and each claim is held by a short lease.

How short? A dead worker’s chunk waits out the whole lease before anyone retries it. Say the lease is 30 seconds. Then a crash leaves that chunk’s followers without the post for at least 30 seconds, six times the 5-second promise. So the lease must fit inside those 5 seconds, with room left for the work itself. A long lease protects a slow worker and breaks freshness for that chunk’s followers. A short lease has the opposite cost. Now and then it hands a live but slow worker’s chunk to another worker, and both of them write it.

Worker A claims chunk 1, and its machine loses power partway through. A’s lease runs out, and the job passes to worker B. What B does next depends on when A recorded its progress.

Say each chunk is 100 followers. Then a crash repeats at most 100 writes, which is why fan-out works in chunks. Crashes like this are routine. At the peak, workers write 23,150 timeline entries a second. A deploy restarts every worker, so every deploy lands in the middle of some chunk. The pictures below keep it small: six followers, in two chunks of three.

The first instinct is to avoid repeating work. So A records chunk 1 as done before writing anything. It writes follower 1, then its machine dies. B reads the chunk rows. Chunk 1 says done, so B moves on to chunk 2 and writes followers 4 to 6. Followers 2 and 3 never get the post. Nothing will ever retry it, because the record says it happened. So progress is recorded only after the writes it describes.

Flip the order, then. A writes followers 1 to 3, and only then records chunk 1 as done. Replay the crash, this time after all three writes and before the record. B sees chunk 1 unfinished and runs it again, so nobody is skipped.

Say each timeline is a plain list, where every write adds an element. Followers 1 to 3 now hold P9 twice, and their feeds show the meeting point twice. Recording progress after the writes turns every crash into repeated writes. So the writes have to be safe to repeat.

A timeline is already a Redis sorted set, and a sorted set holds each member once. The member is P9’s ID followed by the club’s ID. Writing P9 into a timeline that already has it leaves one entry. Replay the crash. B runs chunk 1 again, and its three writes change nothing. B records chunk 1 as done, then writes followers 4 to 6. All six followers hold P9 once. A worker crash now costs repeated work, never a lost or doubled post. The same rule covers the slow worker whose short lease ran out: it and its replacement both write the chunk, and each timeline still holds P9 once.

The experiment replays the crash three ways. Its tabs are “Mark done, then write”, “Write, then mark” and “Safe to repeat”. Watch followers 2 and 3.

The interactive version of this example is available when JavaScript loads.

Only the third tab ends with every follower holding the post once. It needs both rules together: progress after the writes, and writes that are safe to repeat.

Chunks need one more rule. Suppose chunk 2 is “followers 101 to 200 in the list”. Chunk 1 finishes, and then one of the first 100 followers leaves. Everyone after them moves up one place. The follower who was 101st is now 100th, so chunk 2 starts after them, and they never get the post. So each chunk row names a range of follower IDs, not positions. Chunk 2 is every active follower after, say, follower 88,412, up to and including follower 91,907. A follow or unfollow can change how many followers a range holds. It cannot move anyone into a different range, so nobody falls between two chunks.

One gap sits below the workers. Redis acknowledges a write, then copies it to its replicas a moment later. If a node fails over inside that moment, inserts it acknowledged can vanish. The chunk may already be marked done, so nothing writes them again. A worker can call WAIT before recording the chunk. That holds the record until a replica has the writes. The Redis documentation says this makes the loss less likely, not impossible. A timeline is derived data, so the design accepts a rare missing entry rather than paying for a stronger store.

Another gap opens before any worker runs. The Post API saves P9, then sends the fan-out event to Kafka. Suppose it crashes between the two. P9 exists, and the club sees it on its profile. No follower ever will. Send to Kafka first instead, and a crash leaves an event for a post that was never saved. Two systems cannot be written in one step.

So the Post API writes only to its database. It saves P9 and an outbox row in one transaction, on the club’s shard, so either both exist or neither does. A relay reads unsent outbox rows and publishes them to Kafka, retrying until Kafka accepts. Replay the crash. The API dies after the commit, and the outbox row is already saved. The relay publishes it a moment later.

The planner reads the topic from its last committed offset. It commits a new offset only after it has written the chunk rows. A planner that crashes before committing reads the same event again and plans the same chunks. Those chunks repeat only writes that are safe to repeat.

The relay can also publish one event twice. That happens when it crashes after sending, before marking the row sent. The second copy plans the same chunks again, and their writes change no timeline. A planner that remembers handled event IDs skips that repeated work. Delete outbox rows once they are published, or the table grows forever.

Debezium’s outbox event router is one ready-made relay. It reads outbox rows from the database log. The idempotency article follows the same retried-request problem at an API boundary.

The code shows both writes. The first tab saves the post and its event in one transaction, and the second inserts one post into one timeline. Its example writes the post ID as 9, padded to 19 digits, to keep it readable. A real Snowflake ID fills those digits, and the score is the time read out of it.

The interactive version of this example is available when JavaScript loads.

The first write leaves an event behind for every saved post, and a retried request writes no second event. The second write can run twice without harm, because adding a post ID that is already in a timeline keeps one copy.

One case is left: a post that fails on every attempt, because of a bug or bad data. Dropping it after the last retry would silently remove it from thousands of feeds. So park it in a dead-letter queue, raise an alert, and replay it once the cause is fixed.

The gap: A worker’s writes and its record of progress are two steps, and a crash can fall between them.

Option 1: Record the chunk as done, then write

A worker marks a chunk finished before writing it, to avoid repeated work.

Works when: Losing a delivery now and then is acceptable, which this feed does not accept.

Breaks when: A crash after the mark leaves followers 2 and 3 without the post, and nothing retries it.

Option 2: Write, then record, into a plain list

Progress is recorded after the writes, so a retry repeats the whole chunk.

Works when: Skipping a follower is the only failure that matters, and a post shown twice is acceptable.

Breaks when: Followers 1 to 3 end up holding the post twice.

Option 3: Writes that are safe to repeat, and an outbox (start here)

Record progress after the writes, write into sorted sets that hold each post once, and save each post with its outbox row.

Works when: Any fan-out: a worker crash means a retry, and a retry changes nothing that already happened.

Watch for: A post that fails on every attempt, chunk boundaries that shift, and inserts lost in a Redis failover.

Fix within it: Park a failing post in a dead-letter queue, give each chunk a range of follower IDs, and use WAIT where the gap matters.

In the interview: Open with option 3, and say its two rules in order: progress after the writes, and writes that are safe to repeat. Give option 1 in one sentence as the bug those rules avoid. Bring in the outbox when the interviewer asks what happens if the Post API crashes before the job is queued.

Say this: A crash can fall between a worker’s writes and its record of progress. I record a chunk as done only after its writes succeed, so a retry repeats work rather than skipping followers. The writes are safe to repeat, because a sorted set holds each post once per timeline. The post and its fan-out event are saved in one transaction, so a saved post always gets its job.

A new post arrives while Leena scrolls. Does page two repeat or skip?

Leena’s first page shows the posts from 9:06, 9:05 and 9:04. A real page holds 20 posts, and three keep the picture small. While she reads, the club posts at 9:07. Then she scrolls, and the app asks for page two. Which three posts come back?

The simplest request asks for the next rows: skip the three already shown, and take three more. In SQL that is OFFSET 3 LIMIT 3. In Redis it is a range by rank, positions 3 to 5 counting from zero.

Replay the scroll. The feed is now 9:07, 9:06, 9:05, 9:04, 9:03. The new post pushed every row down by one. Rows 4 to 6 start at 9:04, which Leena has already seen.

The opposite shift loses a post. Say a cleanup job removes an entry above the boundary while she reads. Every row moves up by one, and the post that slides into row 3 is never shown. An offset also slows down with depth. The PostgreSQL documentation warns that the rows an OFFSET skips still have to be read. It also warns that rows can come back in a different order without a unique ORDER BY. An offset counts rows in a list that keeps changing, so it cannot mark a place in it.

The next idea remembers where page one ended. Page two asks for posts created before the last one shown. Replay the scroll. The 9:07 post is newer than 9:04, so it falls outside page two’s range, and nothing repeats.

Now look closer at the clock. The API returns createdAt to the second, and at the peak about 116 posts are published every second. Say the club and the news wire both post at 09:04:12, and Leena follows both. Page one ends on the club’s post. “Before 09:04:12” skips the news wire’s post, which carries the same stamp. “At or before 09:04:12” shows the club’s post again. Millisecond stamps make a tie rarer, not impossible. A boundary needs a key that no two posts share.

The post ID is that key. It is unique, and a Snowflake ID sorts by time, as the data section showed. So the cursor is the ID of the last post on the page, and page two asks for smaller IDs. Replay the scroll. The 9:07 post has a larger ID than the 9:04 post, so it sits above the boundary, where page two never looks. Page two is 9:03, 9:02 and 9:01. Replay the tie. The two posts from 09:04:12 have different IDs, so whichever sorts lower lands on exactly one page.

In Redis, the score is the creation time in milliseconds, and the member starts with the post ID. Page two asks for scores up to the cursor’s millisecond, and drops members at or above the cursor’s ID.

The experiment replays the scroll. Its tabs are the offset and the cursor, and its chips change what happens while Leena reads.

The interactive version of this example is available when JavaScript loads.

The third chip is the one most candidates miss. A friend’s post stamped 9:05:30 reaches Leena’s timeline late, after page one loaded, because its fan-out was slow. It belongs between 9:06 and 9:05. That is above the cursor, so neither method shows it on this scroll. The new-posts banner misses it too, because its ID is smaller than the newest one Leena holds. Pulling to refresh reloads page one, which includes it only because it is still near the top. A post delayed by an hour would sit an hour down the feed. Leena would meet it only by scrolling back down to it. Most feeds accept that, and it is one more reason the 5-second fan-out target matters.

Posts above the boundary need their own path. Every 30 seconds, an open app sends the ID of the newest post it shows to GET /me/feed/new. The Feed API counts the newer entries in Leena’s timeline and her pulled lists, and returns a number. The app shows “3 new posts”. A socket to every open app could deliver that count sooner. It would cost one long-lived connection per open app, and a push on every post. The banner can wait 30 seconds, so a poll is the cheaper fit.

The cursor also works across the pulled lists. Every post ID comes from the same time-sorted scheme, so “smaller than P9” marks the same point in Leena’s timeline and in the footballer’s list.

A long scroll can run past the 800 entries a timeline keeps. Beyond that point the Feed API builds older pages the pull way, asking each followed account for posts below the cursor. That path is slower, and only readers who scroll that far pay for it.

A page can also come back short. Say 15 of the 20 candidates were deleted or hidden. Return the 5 that remain, with a cursor past the last one inspected. A run of hidden posts then cannot trap the app in a loop.

The gap: The feed changes while Leena reads it, so page two must start from something a new post cannot move.

Option 1: Skip the rows already shown (offset)

Page two asks for rows 4 to 6 of the feed as it is now.

Works when: The list cannot change while someone pages through it, as in a finished report.

Breaks when: A post arriving between pages pushes 9:04 onto page two again.

Option 2: Continue below the last timestamp shown

Page two asks for posts created before the last one on page one.

Works when: No two posts ever share a timestamp, which no busy feed can promise.

Breaks when: Two posts in the same second are either repeated or skipped.

Option 3: Continue below the last post ID shown (cursor) (start here)

Page two asks for post IDs smaller than the last one shown, and IDs are unique and sort by time.

Works when: Any newest-first feed, with a banner for what is new.

Watch for: A post delivered late lands above the cursor, where neither page two nor the banner counts it.

Fix within it: Keep fan-out inside its 5-second target, and let pull to refresh reload page one.

In the interview: Open with option 3. Say that the cursor is the last post’s ID, and that a new post cannot move it. If the interviewer asks why not a timestamp, give option 2’s tie. Raise the late post only if they push, and say that pull to refresh is the honest answer.

Say this: An offset counts rows in a list that keeps changing, so a new post shifts page two and repeats one Leena has seen. I page with a cursor: the ID of the last post shown, and page two asks for anything older. IDs sort by time and are unique, so a new post lands above the boundary, and a banner offers it. A post delivered late can land above the cursor too, and pull to refresh finds it.

One post goes viral. What stops a single shard from melting?

On the night of a cup final, at 20:14, the footballer posts a photo of his winning goal. Say 5 million readers load a page containing it within one minute. 5,000,000 ÷ 60 is about 83,000 pages a second. The ordinary peak is 11,575 pages a second, so this minute runs about 7.2 times above it. A final is a planned surge, and the feed adds servers for the night.

Extra servers absorb most of that load. Each page reads 20 posts, and those reads spread over millions of keys. The goal’s reads do not spread. Every one of those 83,000 pages a second reads the same post record and the same like count. The readers all follow the footballer, whose posts are pulled, so every page also reads his author timeline. All of it lands on those three keys.

The simplest path reads every post from the database shard that owns it. Posts are sharded by author, so the goal lives on the footballer’s shard. Say one shard or one cache node comfortably serves 20,000 reads a second of a single key. That figure is illustrative, so measure your own. The footballer’s shard now needs to serve 83,000 a second for one row, while the other shards carry only their ordinary share. Adding shards does not help, because one row lives on one shard.

The usual next step puts a cache in front of the post store. Pages read posts from the cache, and only misses reach the database. For most of the day that works well, because reads are spread over many posts. Replay the goal. The database is safe now. But the post’s cache key lives on one cache node, and that node takes all 83,000 reads a second. That is about four times what it can serve. The heat moved from one shard to one cache node.

The cache brings a second hazard. When the goal’s cached entry expires, every request that misses at that moment goes to the database together. At 83,000 a second, even a 10-millisecond gap is 830 requests for one row. So give each entry a soft expiry before its hard one. Once the soft expiry passes, one request refills the entry. The others keep reading the old copy until the refill lands.

The fix spreads the one key. Each Feed API server counts reads per post over the last few seconds, and a post read far more than the rest becomes hot. A hot post gets 10 copies under 10 keys, such as post:P77#0 to post:P77#9. The suffixes are chosen so that the 10 keys map to 10 different nodes. Plain suffixes would not guarantee that: 10 hashed keys on 20 nodes land on about 8 distinct nodes. Each reader picks one copy at random. Replay the goal. 83,000 ÷ 10 is about 8,300 reads a second per node, well under the 20,000 each can serve. The footballer’s author timeline gets the same treatment while the surge lasts. Each new post of his is added to all 10 copies, and each page reads one. Copies spread one key’s reads over as many nodes as there are copies.

Copies create the next problem. An hour later the photo is reported, and the footballer deletes it. A delete that clears post:P77#0 leaves nine copies still serving it. Readers who land on those see a deleted post.

So the delete path does the extra work, because deletes are rare and reads are not. It marks the post deleted in the post store, with a higher version number. Then, before the API answers, it overwrites all 10 cached copies with a deleted marker carrying that version. A marker beats a plain removal because of refills in flight. A refill that read the post just before the delete, or read a replica still behind, would write the live post back into an empty key. Each refill writes only if its version is newer than the cached one, so an old refill cannot replace the marker. The marker must outlive any refill still in flight, so it lives far longer than replica lag, say an hour.

A cache inside each Feed API server is the other common answer. Say 500 Feed API servers run on the night of the final. Each keeps the goal in memory for at most 2 seconds, so each fetches it at most once every 2 seconds. The cache tier then sees at most 250 reads a second for the post, however many readers there are. The price is the delete. A server’s copy can outlive the delete by up to its 2 seconds. Where the delete promise can allow that delay, it is the cheaper answer.

The like count has the same problem in the other direction: many writes to one row. Say 10,000 likes a second land on the goal. Each one updates the same counter row. Each waits for the row lock that the one before it holds. Split the count across 20 rows, and each row takes a twentieth, 500 likes a second. Adding up 20 rows on every page would be 83,000 × 20, about 1.66 million row reads a second. So a job adds them up once a second and caches the total beside the post, where the same 10 copies serve it. A like count a second behind is fine. For the same reason, a server can gather likes in memory and write them once a second. The hot-key article works through the same pattern for one key.

The gap: All 83,000 pages a second read the same few keys, and each key lives on one machine.

Option 1: Read every post from the post store

Each page fetches its 20 posts from the shard that owns them.

Works when: No single post is much hotter than the rest.

Breaks when: The footballer’s shard takes 83,000 reads a second for one row.

Option 2: Put a cache in front of the post store

Pages read posts from a cache, and only misses reach the database.

Works when: Reads are spread across many posts, as they are most of the day.

Breaks when: The one cache node holding the post takes all 83,000 reads, about four times what it can serve.

Option 3: Copy hot posts to many cache nodes (start here)

Keep 10 copies of a hot post under 10 keys on 10 nodes, and let each reader pick one.

Works when: One post is read far more than one node can serve.

Watch for: A delete, or a refill in flight, can leave a live copy behind.

Fix within it: The delete writes a versioned deleted marker to all 10 copies before it answers, and a refill never overwrites a newer version.

Option 4: Cache hot posts inside each Feed API server

Each server keeps the hottest posts in its own memory for at most 2 seconds.

Works when: A 2-second delay on deletes is acceptable.

Watch for: A deleted post can still be served for up to 2 seconds by a server that fetched it.

Fix within it: Keep the lifetime short, and state that delay in the delete promise.

In the interview: Open with option 3, because the question has already named one hot key, and option 2 only moves the heat to a cache node. Give the arithmetic: 83,000 reads a second on one key, about 8,300 per node with 10 copies. Then say what copies cost a delete before the interviewer asks.

Say this: A viral post is 83,000 reads a second on one key, and a cache alone moves all of that onto one cache node. I keep 10 copies of a hot post on 10 nodes, so each serves about 8,300. A delete writes a versioned marker to every copy before it answers, so no refill can bring the post back. The like count is split across 20 rows, so its writes spread too.

Mira blocks Leena. Why is Mira’s photo still in Leena’s timeline?

At 22:10 last night Mira posted a photo, and fan-out copied its ID into Leena’s timeline. At 7:05 this morning, after an argument, Mira blocks Leena. At 7:06 Leena opens the app. The entry is still in her list, because nothing removes it until a cleanup job gets to it. What does her next page show? Keep a second version of the scene in mind, where Mira deletes the photo instead.

The feed serves up to 11,575 pages a second at the peak, in several regions, with 95% of them inside 300 ms. Blocks and deletes are rare. Leena’s app loads pages thousands of times more often than Mira blocks anyone.

The fastest design stores ready-made pages. The timeline holds each post’s text and photo link, and the Feed API returns them as they are. Replay 7:06. The page was built last night, and nothing looks at the post or at Mira again. Leena sees the photo after the block. After a delete she sees it too, until the cached page expires. A page built from copies shows what was true when it was copied.

So the timeline holds only IDs, and each page re-reads its 20 posts through the cache in front of the post store. A delete marks the post and its cached copies deleted, as the viral-post deep dive showed. Replay the delete. The re-read sees the deleted state, so the page drops the photo. Replay the block. The post did not change. Its state still says live, and its visibility still says public, so the page shows it. A delete changes the post. A block changes the relationship between two people, and re-reading a post cannot see a relationship.

So every page also checks access. A timeline entry is a candidate, never permission. After re-reading its posts, the page makes one batched lookup in the graph for their authors. Does Leena still follow each author? Has either person blocked the other? For a private author, is she an approved follower? Replay the block. The graph holds the new row, so Mira’s photo is dropped. The check costs one batched read per page, 11,575 a second at the peak. Removing Mira’s entries from Leena’s list still happens later, in the background, so the list does not fill with posts that will always be dropped.

The experiment serves the photo three ways. The first tab serves the cached page, the second re-reads each post, and the third re-reads and checks access. Switch between them, then between a delete and a block.

The interactive version of this example is available when JavaScript loads.

Only the third tab handles both. It asks the post store about the post, and the graph about the relationship.

That check is only as fresh as the copy of the graph it reads. The feed serves pages in several regions, each from its own copy. Say Mira’s block is written in Europe, and Leena’s page is served in Asia, where the copy is two seconds behind. For those two seconds the Asian copy says there is no block, so the check passes. Read replication explains why a replica can be behind.

One answer sends every access check to the region that holds the newest copy. That is a trip between continents on every page, to guard against an event that almost never happens. The trip can take a large share of the 300 ms budget, and every page would pay it.

So make the rare write pay instead. Mira’s block is confirmed only once every region’s copy has it. Her screen shows the block a moment later. Every page served after that finds the block in its own local copy. Deletes work the same way.

That opens the next problem. Say the Asian region is cut off and cannot confirm. The block must not wait forever, and Asia must not keep serving from a copy that may miss it. So a region answers access checks from its own copy only while it holds a lease. The lease is a permission, granted by the other regions together, that lapses after, say, 10 seconds. They renew it only while the region keeps applying their writes.

Replay the cut. Mira’s block waits for each region to confirm, or for that region’s lease to lapse. The other regions stop renewing Asia’s lease, and it lapses within 10 seconds. Asia measures the lease on its own clock. It gives the lease up a little early, which covers clock drift and a short pause. A server paused for longer than that margin could still answer late, so keep the margin wider than the pauses you measure.

Without a lease, Asia stops answering from its own copy and asks a region that is current. If it cannot reach one, it leaves out every post it cannot check. For a region cut off from the rest, that is every post. Its readers see errors or empty pages until the link returns. A missing photo is better than a leaked one, and the price is that region’s availability.

One more leak sits outside the feed. Leena’s app may already hold a signed link to Mira’s photo, and the block cannot recall it. Anyone holding that link can use it until it expires. Even that limit holds only if the CDN checks the signature on every request. An edge that serves the photo from its cache without checking the signature first keeps serving it. A copy already downloaded to her phone cannot be taken back at all. Candidates often forget this leak.

So state the promise exactly. From the next page, the feed will not show Mira’s posts. The photo links it handed out stop working within 10 minutes, provided the CDN checks their signatures.

The gap: A timeline entry was allowed when it was copied, and a delete or a block can change that afterwards.

Option 1: Serve the cached page as it is

The timeline stores ready-made pages, text and photo included.

Works when: Nothing is ever deleted or hidden, which no social feed can promise.

Breaks when: Both the delete and the block are ignored until the cached page expires.

Option 2: Store IDs, and re-read each post when serving

Each page fetches its posts fresh and drops any that are deleted.

Works when: The only change that must show is to the post itself.

Breaks when: A block changes a relationship, not the post, so the photo still shows.

Option 3: Re-read the post and check access against a current copy

Each page also makes one batched graph lookup against a copy known to be current.

Works when: The feed runs in one region, where the current copy is close.

Breaks when: In several regions the current copy may be a continent away, on every page.

Option 4: Check the local copy, and let the block wait for every region (start here)

Pages check their own region’s copy, and a block is confirmed only once every region has it.

Works when: A feed served from several regions, where a cut-off region may serve errors rather than risk a leak.

Watch for: A region cut off from the rest cannot confirm, so its readers get errors until it reconnects.

Fix within it: The other regions grant each region a lease, and a block waits for each confirmation or lapsed lease.

In the interview: Open with option 4, because the requirement says every region. Say “a timeline entry is a candidate, not permission”. Give option 2 a sentence, because it catches a delete and misses a block, and that difference is the point. Bring in option 3 only to explain why the block waits rather than the page.

Say this: Re-reading a post catches a delete but not a block, because a block changes a relationship, not a post. So every page treats a timeline entry as a candidate and checks blocks and privacy before serving it. The check reads the local copy, and a block is confirmed only once every region has it. Photo links are signed and expire in about 10 minutes, and the CDN checks the signature on every request.

That completes the core design. The three sections below are shorter follow-ups that a staff round often adds.

If they push: how do you keep a ranked feed stable while Leena scrolls?

So far the feed is newest first. A ranked feed might put the club’s ride cancellation above a newer headline. Ranking changes which candidates reach the page and in what order. It does not change how posts reach the candidates.

Scoring every eligible post for every page is too slow. Meta describes a first pass in which a light model picks about 500 of the most relevant eligible posts, before heavier models score that smaller set. Copy the shape. Take a few hundred recent candidates from Leena’s timeline and her pulled accounts. Score them cheaply, then score the top few dozen carefully.

Ranking breaks the cursor. If every page request scores again, a post can move from position 18 to position 23 between page one and page two, and Leena sees it twice. So score once when her session starts. Store the ordered list of IDs for about 30 minutes. Let the cursor be a position in that list. New posts wait for a refresh. Access is still checked on every page, because a frozen order does not freeze permission. If the ranker is down, serve newest first and say so in the response. The app must not read a ranked cursor as if it were a newest-first one.

The interactive version of this example is available when JavaScript loads.

The ranker is the last box, and it is optional. Without it, the same candidates simply go out newest first.

If they push: a timeline cache node dies. What happens to those timelines?

Say the timelines are spread over 100 Redis shards, with three copies of each. That puts about 19 GB of payload on each node, and more in real Redis memory. When one node dies, a replica takes over. Readers keep their timelines, minus any last inserts the replica had not yet received, as the crash deep dive noted. The harder case is losing every copy of a shard, or a whole region’s cache after a bad deploy. Timelines are derived data, so no post is lost. The question is how to rebuild them without an outage.

One shard holds a hundredth of the 50 million timelines, which is 500,000. Rebuilding all of them at once, at 300 lookups each, is 150 million lookups against the post store in one burst. That turns a cache failure into a database outage.

So rebuild a timeline only when its reader comes back. Gather the newest posts of each account the reader follows, as step 3 did. At the peak, a hundredth of 11,575 pages a second is about 116 pages. Each lost reader’s first page costs 300 lookups, so the rebuilds start at about 35,000 lookups a second and fall as timelines refill. Allow one rebuild per reader at a time, and cap the total, so a burst of returns waits instead of piling on. The same path serves a reader who returns after six months away.

If they push: how does a post reach followers on another continent?

Say the club’s organiser is in London and one of its followers is in Singapore. The post is saved in the author’s home region, where its shard lives. The post and its outbox event are copied to every region. Each region keeps timelines for the readers it serves, and its own workers fan the post out to them. So the follower in Singapore gets the post a few seconds after a follower in London, because the copy has to cross first. Measure the 5-second target per region, from saving the post to the last insert in that region.

Blocks and deletes are handled differently. A post may reach Singapore a few seconds late, but a block may not. As the privacy deep dive showed, a block waits until every region has it, so every page can check access locally.

Walk one post and one page through the final design

The club saves P9 with its outbox row in one transaction. The relay publishes the event to Kafka. Workers page through the club’s active followers by ID, add P9 to each timeline, and record each chunk after its writes. The footballer’s posts skip the fan-out. Each one’s event makes a single append, to his author timeline, where it waits.

Leena opens the app. The Feed API reads her timeline, fetches the author timelines of the accounts she pulls, and merges them, dropping duplicate IDs. It re-reads the posts, checks blocks and privacy, and either hands a few hundred candidates to the ranker or returns them newest first. Leena gets 20 posts and a cursor. Thirty seconds later the banner says 2 new posts are waiting.

If Mira blocks her, the next page leaves Mira out before any cleanup runs. If Leena’s timeline is lost, the pull path rebuilds it from the post store and the graph.

RequirementWhere it is metThe trade-off
FR1 publish, profile, deletePost API, PostgreSQL shards by author, outboxFollowers see a post seconds after its author does
FR2 follow, approve, blockFollow graph, stored in both directionsTwo copies of each follow to keep in step
FR3 feed without repeats, new-posts bannerTimelines, pulled author lists, merge, ID cursorA late post can land above the cursor and wait for a refresh
FR4 deletes and blocksRe-read posts and check access on every pageAn access check on every page; photos already downloaded stay downloaded

How does the answer change for Twitter, Facebook, Instagram or LinkedIn?

Interview variantWhat carries overWhat changes
Design Twitter (the home timeline)Hybrid fan-out, capped timelines, ID cursorsReposts need a rule, so one post shared by five people Leena follows shows once
Facebook News FeedCandidates, access checks, staged rankingFriendships go both ways, groups and pages add sources, and ranking is the default
Instagram feedPost IDs, fan-out, access checksPhotos and video carry most of the bytes, so upload and CDN delivery matter more
LinkedIn feedMerging candidates and ranking themPosts reach friends of friends through likes and comments, so candidates come from activity as well as follows
Activity feed in a work appDurable events and access checked per readerAccess to the underlying document can change, so every item needs a fresh check
For You feedServing, ranking and paginationCandidates come from a recommendation system, which becomes the main problem

LeetCode’s Design Twitter problem asks for the same operations inside one program. The data structure it wants is the merge from the second deep dive, run over in-memory lists.

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelSeparates the post from timeline entries. Compares fan-out on write with fan-out on read using numbers. Pages with a cursor rather than an offset.
SeniorPushes to active followers only, pulls large accounts and merges by time. Makes fan-out safe to retry with an outbox. Checks access when serving, not only when copying.
StaffChooses push or pull per account from measured costs, with overlap during a switch. Handles hot posts, access checks under replica lag, and rebuilding timelines without an outage. Keeps a ranked session stable.
PrincipalSets the freshness, privacy and cost budgets and shows what each one costs. Explains how the design changes for two-way friendships, several regions and a recommendation feed.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.