SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a News Feed

Show each user a ranked stream of posts from people they follow, fast, even for celebrities.

⏱ 34 min readMedium case studyIntermediate24 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a news feed, like the home timeline on Facebook, Instagram or Twitter.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Finding the real problemThe prompt looks like a list query. The real problem is fan-out: one post must reach hundreds, or millions, of feeds. A strong candidate says so early and does the maths.
Write path versus read pathPush, pull and hybrid are three answers to one question: do the work when someone posts, or when someone reads? The interviewer wants the reasoning, not a memorised answer.
Handling the skewed caseMost accounts have a few hundred followers and a few have tens of millions. A design that only works for the average account fails in the first follow-up.
Caches and paginationA feed is a cached list per user, filled with IDs and hydrated into full posts. Pagination must stay stable while new posts arrive.
Trade-offs and honestyFresh versus cheap, ranked versus simple, exact versus eventual. There is no perfect feed, only reasoned choices and clear limits.

TL;DRThe whole design in 60 seconds

A news feed is a per-user list of post IDs that we keep ready in a cache, so opening the app is one fast read. The hard part is filling those lists: when someone posts, who does the work, and when?

  • Scale: 300M daily users, 2 posts each, about 7,000 posts a second. Each post goes to about 200 followers, so a naive push is about 1.4M feed inserts a second. Reads are about 35,000 feed opens a second.
  • Hybrid fan-out: push the post ID into each follower's cached feed for ordinary accounts, and do not push for celebrities. Followers fetch the celebrity posts at read time and merge them in.
  • Skip the inactive: only push to users who opened the app in the last 30 days or so. This roughly halves the write load.
  • Read: get the user's list of IDs from Redis, merge in the celebrity posts, rank the top candidates, then fetch the full posts in one batch from the post cache.
  • Pagination: a cursor made of a score and an ID, never an offset, so new posts do not cause repeats.
  • Honest limits: the feed is eventually consistent by a few seconds, deletes and unfollows are filtered when the feed is read, and ranking is a cheap two-stage model.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Chronological or ranked, follow graph shape, celebrities, media, how fresh, scale.
2. Estimate3Posts per second, feed opens per second, fan-out inserts per second, feed cache size.
3. API and data5Post, follow, get feed with a cursor. Posts, graph, feed cache.
4. High-level design8Post service, fan-out queue, feed cache, graph, ranking. One write path, one read path.
5. Deep dives15Fan-out strategy and the celebrity problem, feed storage and pagination, ranking, the graph and deletes.
6. Scale and failures7Fan-out backlog, lost cache, hot posts, counters, multi-region.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about what a feed contains, who is in it, how it is ordered, how fresh it must be, and what happens with very popular accounts.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
What is in the feed: posts only from people you follow, or also suggestions and ads?Suggestions need a recommendation system, which is a different problem.Posts from accounts you follow. Ads and suggestions can be added later.We build the follow-based feed and leave a clean place to insert other items.
Is it newest first, or ranked by relevance?Chronological is a sorted list. Ranked needs scoring and a second stage.Ranked, but simple: recent, close to you, and engaging.A cheap two-stage ranker after we collect the candidates.
How many users, how many posts a day, and how many accounts does a user follow?These numbers decide whether fan-out is a problem.300M daily users, 2 posts a day each, about 200 followers on average.Fan-out is about 1.4M inserts a second, so push is a real cost.
Are there accounts with millions of followers?This is the question that breaks the simple design.Yes. Some have 50M followers.We need a hybrid, with a different path for large accounts.
How fresh must the feed be? Is a few seconds late fine?If a few seconds is fine we can use queues and eventual consistency.A few seconds is fine. It does not need to be instant.Asynchronous fan-out through a queue.
What do posts contain: text only, or photos and video?Media decides storage and how feeds are served.Text, links and photos. Video comes later.Media goes to object storage and a CDN. The feed holds only IDs.
How long is the feed? Can a user scroll forever?Sets the size of the cached list and how pagination works.Show the latest few hundred, then load older posts on request.Cache about 800 IDs per user. Older posts are built on demand.
What happens when someone deletes a post, unfollows, or blocks?Feeds are copies, so removals must reach them.It should disappear quickly, but a short delay is fine.Filter at read time, and clean the caches lazily.
Do we need likes, comments and counts on the post?Counters are a separate hot-write problem.Show counts, but they may be slightly stale.Approximate counters, kept apart from the feed.
How available and how fast must the feed be?The feed is the home page. If it is slow or down the product is down.99.99% available and the first page in under 300 ms.Serve from cache, degrade gracefully, and never block on ranking.

Write the scope on the board

Functional (must do)
  • •Create a post (text, and media by link)
  • •Follow and unfollow an account
  • •Get my feed: recent, ranked posts from accounts I follow, a page at a time
  • •Posts, and the people they came from, can be hidden or deleted
  • •Show approximate like and comment counts
Non-functional (how well)
  • •Latency: the first page in under 300 ms at p99
  • •Availability: 99.99%. A stale feed is better than no feed
  • •Freshness: a new post appears in followers' feeds within a few seconds
  • •Scale: 300M daily users, about 7,000 posts and 35,000 feed opens a second
  • •Handle accounts with 50M followers without slowing anyone else
Out of scope (say it)
  • •Recommendations from accounts you do not follow
  • •Ads and sponsored posts (a place to insert them is enough)
  • •Stories, live video and direct messages
  • •Search and trending topics
🎤
Say it out loud
“Let me confirm the scope. We build the home feed: posts from accounts you follow, ranked with a simple model, a page at a time. There are 300 million daily users, about 200 followers on average, and some accounts with 50 million. A few seconds of delay is fine, the first page must load in under 300 milliseconds, and the feed must stay up, so a stale feed is better than none. Counts can be approximate. I will leave recommendations, ads, search and live video out. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: how many posts a second, how many feed opens a second, and how many feed inserts a second if every post is pushed to every follower? Which number is the scary one?

Assumptions (say them first)

AssumptionValue
Daily active users300 million
Posts per user per day2
Followers of an average account200 (so an average user follows about 200)
Feed opens per user per day10
Posts on one feed page20
Share of followers active in the last 30 days50%
Feed cached per user800 post IDs × 8 bytes = 6.4 KB
Registered accounts, of which active are cached1 billion, 500 million active
Peak compared to average3 times
Post record without mediaabout 1 KB
Posts with a photo, and photo size20%, about 300 KB

The arithmetic, line by line

WhatMathsResult
Posts per day300M × 2600 million
Post writes per second (average, peak)600M ÷ 86,400 ≈ 6,900, × 3about 7,000 and 21,000 per second
Feed opens per day, per second300M × 10 = 3B; 3B ÷ 86,400about 35,000 per second (105,000 at peak)
Feed inserts per day if we push to everyone600M posts × 200 followers120 billion per day
Feed inserts per second (all followers)120B ÷ 86,400about 1.4 million per second (4.2M at peak)
Feed inserts per second (active followers only)1.4M × 50%about 700,000 per second (2.1M at peak)
One post from a 50M-follower account (active only)50M × 50%25 million inserts from one post
Lookups per feed open if we build the feed at read time200 timelines + 20 posts; 35,000 × 220220 lookups, so about 7.7M lookups per second
Lookups per feed open with a cached feed1 feed list + 20 posts; 35,000 × 2121 lookups, so about 735,000 per second
Feed cache size500M active users × 6.4 KB3.2 TB, about 6.4 TB with overhead, about 64 nodes of 100 GB (128 with replicas)
Post storage per year (text), with 3 copies600M × 1 KB × 365 × 3about 220 TB a year, 660 TB with copies
Photo storage per year600M × 20% × 300 KB × 365about 13 PB a year (object storage and CDN)
Follow graph (one direction)1B accounts × 200 × 16 bytesabout 3.2 TB (6.4 TB with both directions)
What the numbers tell us about the design
  • •Write amplification is the story: 7,000 posts a second becomes 1.4 million inserts a second if every post is pushed to every follower. That is 200 times more work.
  • •Reading by pull costs 220 lookups per feed open, about 7.7M lookups a second. Pushing makes a feed open just 21 lookups. We pick push for normal accounts because reads are 5 times more frequent than posts.
  • •One celebrity post is 25 million inserts. Alone it would keep the whole fan-out fleet (about 1.5 million inserts a second) busy for about 17 seconds. A few such posts a minute never catch up. So big accounts must not be pushed.
  • •The feed cache is only IDs. 3.2 TB is large but fits in a cache cluster. Full posts are fetched in a batch from a separate post cache. Photos live in object storage and a CDN.
  • •Skipping inactive users halves the write load for free, and a user who returns after a month gets a feed built on demand.
🎤
Say it out loud
“Let me do the maths. 300 million users posting twice a day is 600 million posts, about 7,000 a second. Each goes to about 200 followers, so pushing everything is about 1.4 million feed inserts a second, 200 times the post rate. Feed opens are about 35,000 a second. If I build the feed at read time that is 220 lookups per open, about 7.7 million a second. If I keep a cached list per user it is about 21. And one post from a 50-million-follower account is 25 million inserts. So push for normal accounts, and something different for celebrities.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the three calls a client makes: post, follow, and get my feed. How does the client ask for the next page without seeing repeats? Then ask: what do you store, and in which store?

Endpoints

MethodPathRequestResponseNotes
POST/v1/posts{ text, mediaIds[], visibility }201 { postId, createdAt }Idempotency key in a header, so a retry does not create two posts. Media is uploaded first to object storage and referenced by ID.
GET/v1/feed?cursor=&limit=20none200 { posts: [...], nextCursor }The cursor is opaque. It encodes the score and the post ID of the last item, not an offset. Auth required.
POST/v1/follows/{userId}none204Idempotent: following twice is the same as once. Triggers a small backfill of that account's recent posts into the feed.
DELETE/v1/follows/{userId}none204Idempotent. The feed is filtered at read time, so the effect is immediate even if caches still hold the posts.
DELETE/v1/posts/{postId}none204Marks the post deleted. Feeds drop it when they hydrate posts. Caches are cleaned in the background.

Data model

StoreKey and valueNotes
Postspost_id → { author_id, text, media_ids, created_at, status }Sharded by post_id (or author_id). Source of truth. 1 KB per post. Cached by post_id.
Follow graphfollower_id → [followee_id, ...] and followee_id → [follower_id, ...]Two adjacency lists, so we can ask who I follow and who follows me. About 16 bytes per edge.
Feed cachefeed:{user_id} → sorted list of (score, post_id), about 800 entriesIn Redis, a sorted set per active user. IDs only. Trimmed after each insert.
Author timelinetimeline:{author_id} → recent (created_at, post_id)Each account's own recent posts. Used by pull for celebrities and for the profile page.
Post cachepost:{post_id} → post and author summaryHydration reads. Hot posts stay in memory.
Counterspost:{post_id}:likes → count (sharded)Approximate and eventually consistent, kept apart from the feed.
Feed entry in the cache (sketch)
ZADD feed:42  1717000000123  "9001"      -- score = time (or a ranking score), member = post_id
ZREVRANGEBYSCORE feed:42  (cursor_score  -inf  LIMIT 0 20   -- next page, newest first
ZREMRANGEBYRANK feed:42  0  -801          -- keep only the latest 800
📝Which store, and why
The feed is a hot, small, ordered list per user, read tens of thousands of times a second, so it lives in an in-memory store with sorted sets, such as Redis. It can be rebuilt from the real data, so losing it is a slowdown, not data loss. Posts and the follow graph are the sources of truth and must be durable, so they live in a sharded key-value or wide-column store (or sharded SQL). Photos go to object storage behind a CDN. Counters are separate, because a popular post receives many likes a second.
🎤
Say it out loud
“There are three calls. Post a post, which returns an ID. Follow and unfollow, both idempotent. And get feed, which takes a cursor and returns twenty posts and the next cursor. The cursor is the score and ID of the last item, not an offset, so new posts do not cause repeats. Storage: posts and the follow graph in a sharded durable store, one cached sorted list of post IDs per active user in Redis, and photos in object storage with a CDN. The feed holds only IDs, so it is small and cheap to rebuild.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw one post and one feed open. Where does the post go after it is saved? Where does the feed come from? What is different for a very popular account?
News feed: high-level design
📱Clientsapp, web
→↓HTTPS
🚪API gatewayauth, rate limit
→↓
Write path
✍️Post servicesave, return fast
↓PostCreated
📨Queue (Kafka)durable, partitioned
↓
🌱Fan-out workersskip big and inactive
→↓insert IDs
Read path
🧾Feed serviceread, merge, rank
↓
⚡Feed cacheRedis, 800 IDs per user
Data
🗄️Post storesharded, durable
🧩Post cachehydrate by batch
🕸️Graph servicewho follows whom
Ranking
🎯Rankercheap model on top 200
🧠Feature storeaffinity, engagement
Media
🪣Object storagephotos
🌍CDNclose to users
Posts are saved, then fanned out through a queue into cached feed lists. Large accounts are skipped by fan-out and merged in when the feed is read.
ComponentWhat it does
Post serviceValidates and saves the post, writes it to the author timeline, and publishes a PostCreated event. It returns before any fan-out happens.
QueueHolds PostCreated events durably. Partitioned by author, so one author's posts stay in order and a spike is absorbed instead of dropped.
Fan-out workersRead the follower list in pages, skip inactive followers, and insert the post ID into each follower's feed list. Skip the whole fan-out for large accounts.
Feed cacheOne sorted list of post IDs per active user. Rebuildable. Trimmed to about 800 entries.
Feed serviceOn read: fetch the list, merge posts from the large accounts the user follows, filter hidden and deleted posts, rank, hydrate, and return one page.
Graph serviceStores follows in both directions. Answers: who does this user follow, who follows this account, and which of those are large accounts.
Ranker and feature storeScores about 200 candidates with a cheap model, using signals such as recency, closeness and engagement.
Post cache and object storage with CDNPosts are read by ID in batches. Photos are served from a CDN, never through the feed service.
Write path (follow one request)
  1. The client calls POST /v1/posts with an idempotency key. The post service checks the request and saves the post to the post store.
  2. It also adds the post to the author's own timeline, then publishes a PostCreated event to the queue, and returns 201 to the client.
  3. A fan-out worker takes the event. If the author is a large account (above the threshold), it stops here: followers will fetch this post at read time.
  4. Otherwise it asks the graph service for the follower list in pages of, say, 1,000, and drops followers who have not been active in the last 30 days.
  5. For each remaining follower it inserts (score, post_id) into that follower's feed list in Redis and trims the list to about 800 entries. Inserts are batched and pipelined per Redis node.
  6. If a worker fails, the queue redelivers the event. The insert is idempotent (the same member and score), so a repeat changes nothing.
Read path (follow one request)
  1. The client calls GET /v1/feed with a cursor (empty for the first page). The gateway authenticates and passes it to the feed service.
  2. The feed service reads the user's list from Redis (the next 100 or so IDs after the cursor).
  3. It asks the graph service for the large accounts this user follows, and reads their most recent posts from their author timelines (pull). It merges those IDs into the list by time.
  4. It removes IDs the user must not see: posts deleted, authors blocked or unfollowed, and posts already seen recently.
  5. It sends the top candidates (about 200) to the ranker, which orders them and picks the page of 20.
  6. It fetches the 20 posts and their authors with one batch read from the post cache (a miss goes to the post store), and returns them with the next cursor.
  7. Photos are not in the response body. The client loads them from the CDN by URL.
🎤
Say it out loud
“Here is the picture. A post is saved, then a PostCreated event goes onto a queue and we return quickly. Fan-out workers read the queue. For normal accounts they insert the post ID into each active follower's cached feed list in Redis. For large accounts they do nothing. On read, the feed service takes the user's cached list, merges in the recent posts of the large accounts they follow, filters out hidden and deleted posts, ranks the top 200 candidates, and fetches the 20 winners as one batch from the post cache. The feed is only IDs, so it is small, and photos come from a CDN.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Fan-out: push, pull, or both?

The problem: Every post must show up in many feeds. We can do that work when the post is written, or when the feed is read. Normal accounts have 200 followers and celebrities have 50 million, and one rule must not melt the system for either.

OptionHow it worksGoodBad
Fan-out on write (push)When a post is saved, insert its ID into every follower's cached feed.Reading is one cache lookup. Very fast and predictable for the user.About 200 times more writes than posts. A celebrity post is 25 million inserts. Wastes work on inactive users.
Fan-out on read (pull)When a feed is opened, read the latest posts of every account the user follows and merge them.Posting is one write. No wasted work. A new follow or unfollow is instant.A feed open costs about 220 lookups (7.7M a second in total), and the slowest of them sets the latency. Expensive for the path users feel.
HybridPush for normal accounts. For accounts above a follower threshold, skip the push and pull their recent posts at read time.Writes stay bounded and reads stay cheap. Celebrity storms never reach the write side.Two code paths. A threshold to tune. A user who follows many large accounts has a slower read.
Push only to a hot subsetPush to followers active in the last 30 days, and build the feed on demand for everyone else.Halves the writes. Great as part of a hybrid.A returning user has a cold first load. Needs a rebuild path.
Pick
Hybrid: push for normal accounts to active followers, pull for large accounts

Reads are about 5 times more frequent than posts (35,000 feed opens a second against 7,000 posts), so it is worth paying at write time to keep reads cheap. That is why push is the default. But the cost of a push grows with the number of followers, and the skew is huge, so one rule cannot cover both ends.

Pick a threshold, for example 100,000 followers. Below it we push. Above it we skip the fan-out, and the feed service reads that account's recent posts at read time. A typical user follows only a handful of such accounts, so the extra read work is small (a few more lookups per open). We also skip followers who have not been active for 30 days, because pushing into feeds nobody opens is wasted work.

CasePushedInserts for one postReads for one feed open
Average account, 200 followers, 50% activeYes10021 (list + 20 posts)
Large account, 1M followers, threshold 100kNo (pulled)121 + about 6 big accounts = 27
Celebrity, 50M followers, pushed to activeWould be25,000,000 (about 17 s of the whole fleet)21
Celebrity, 50M followers, hybridNo (pulled)124
📝Worked example: the celebrity storm
Ordinary posts already use about 700,000 of our 1.5 million inserts a second. A celebrity posts 6 times a minute, which is 6 × 25M = 150M inserts a minute, or 2.5 million a second. That is more than the whole fleet can do, even with every ordinary post stopped. The queue only grows and every feed goes stale. With hybrid it is 6 inserts a minute.
💡Say the threshold out loud
There is no magic number. Choose it so that the push work from accounts just under it stays small, and watch the metric "inserts per post". It can be per account, and can change over time as accounts grow.
🎤
Say it out loud
“I would use a hybrid. Reads are about five times more frequent than posts, so I push for normal accounts to keep reading to one cache lookup. But a push costs one insert per follower, and one post from a 50-million-follower account is about 25 million inserts, more than the whole fan-out fleet can do. So above a threshold, say 100,000 followers, I skip the push and the feed service pulls their recent posts at read time and merges them. I also skip followers who have been inactive for 30 days. The cost is two paths and a threshold to tune.”
5.2

Storing and reading the feed, and paging through it

The problem: A feed read must be fast, must return full posts and not just IDs, and must page without showing duplicates even though new posts arrive while the user scrolls.

OptionHow it worksGoodBad
Cache full posts in every feedCopy the whole post into each follower's feed.One read gets everything.Huge memory (a 1 KB post × 200 copies). Edits and deletes need to fix every copy.
Cache IDs, hydrate in a batchThe feed holds post IDs only. On read, fetch the posts by ID with one multi-get from a post cache.Small and cheap. One copy of each post, so edits and deletes happen once. Cache hit rates are high for popular posts.A second step on every read. A cache miss goes to the database.
Offset paginationPage 2 is OFFSET 20 LIMIT 20.Simple.If three new posts arrive, the item at position 20 moves to 23 and page 2 shows duplicates. Also slow for deep offsets.
Cursor paginationThe client sends the (score, id) of the last item it saw. The next page is everything below it.Stable while new posts arrive. Fast: it is a range read on a sorted set.No jump to page 50. Needs a unique tiebreaker so equal scores do not skip items.
Pick
A cached list of IDs, hydrated by batch reads, with cursor pagination

IDs are tiny (8 bytes), so 800 of them per user is 6.4 KB, and the whole cache for 500 million active users is about 3.2 TB. Full posts live once, in a post cache keyed by ID, where hot posts are shared by millions of feeds and stay in memory. Edits and deletes then change one record, not 25 million copies.

The cursor is the pair (score, post_id) of the last item. The next page is the items strictly after that pair. New posts get a higher score and appear at the top, so a user who is scrolling down never sees a repeat. Ranked feeds can reorder, so we also keep a short list of IDs the user has already seen and drop them from later pages.

Reading one page (sketch)
ids   = redis.ZREVRANGEBYSCORE(feed:u, max=cursor.score, min=-inf, LIMIT 0 100)
ids  += authorTimelines(bigAccountsFollowedBy(u), since=cursor.score)   // pull part, a few lookups
ids   = ids - seen(u) - hiddenOrBlocked(u)                                  // filter
top   = ranker.score(ids.take(200))                                         // cheap model
page  = top.take(20)
posts = postCache.multiGet(page.ids)                                        // 1 batch call, not 20
return { posts: posts.filter(p => p.status == 'ok'), nextCursor: (page.last.score, page.last.id) }
⚠️Cache loss is a slowdown, not data loss
If a user's feed list is missing (evicted, or the Redis node died), rebuild it from the graph and the author timelines (pull) for the first page, then refill the list in the background. Size the cache, and use replicas, so this is a rare event rather than the normal case.
🎤
Say it out loud
“The feed stores only post IDs, 800 per active user, so it is 6.4 KB and about 3.2 terabytes in total. Full posts live once in a post cache, and I fetch the page's 20 posts with one batch read, so edits and deletes touch one record, not millions. For paging I use a cursor of score and ID, not an offset, so new posts arriving at the top never cause repeats. If a feed list is lost, I rebuild the first page by pull and refill the cache in the background.”
5.3

Ranking without making reads slow

The problem: A purely chronological feed is easy but not very good. Ranking needs features and a model, and it runs on every feed open, so it must be cheap, and it must never make the page fail.

OptionHow it worksGoodBad
ChronologicalSort by post time, newest first.Simple, predictable, nothing to compute.Noisy: a heavy poster buries everything else. Lower engagement.
Score at write timeCompute a score when the post is inserted into each feed and keep the list sorted by it.Reads stay cheap.The score ages (recency changes) and depends on the reader. Hard to change the model.
Two stages at read timeCollect candidates (the cached list and pulled posts, about 200), then score only those with a model, using precomputed features.A good balance. The model can change without rebuilding feeds. Cost is bounded by the number of candidates.Adds work and a dependency to every read. Needs a fallback.
Heavy model on all postsScore every post from every followed account with a large model.Best quality.Far too slow and costly for 35,000 feed opens a second.
Pick
Two stages: cheap candidate collection, then a small model on the top 200, with a chronological fallback

Candidate collection is the cached list plus the pulled posts, which we already have. The ranker scores only about 200 of them, with features that were computed ahead of time and kept in a fast store: how recent the post is, how close the viewer is to the author (messages, likes, profile views), the post type, and how well the post is doing (engagement so far).

Keep it cheap and safe: a hard time limit on the ranker (for example 50 ms), and if it times out, return the chronological order. Add diversity (do not show ten posts in a row from one author), drop posts the user has already seen, and keep a small share of unranked or random posts so we can measure whether the model is actually better, using an A/B test.

SignalExampleWhere it comes from
RecencyNewer is better, decays over hoursPost timestamp
Affinity (closeness)How often you like, comment on or message this authorPrecomputed in a feature store, updated by a stream
EngagementLikes and comments per view so farApproximate counters
TypeYou tend to open photos more than linksPer-user history
Negative signalsHidden, muted, reportedUser actions, filtered before scoring
🎤
Say it out loud
“I would rank in two stages. First collect candidates, which we already have: the cached list and the pulled posts. Then a small model scores only the top 200, using features computed ahead of time in a feature store, like recency, how close the viewer is to the author, and engagement. I would put a time limit of about 50 milliseconds on it, and if it times out we return chronological order, so ranking can never take the feed down. Then I filter posts already seen and add some diversity.”
5.4

The social graph, deletes and unfollows

The problem: Feeds are copies. When a user unfollows, blocks, or a post is deleted or hidden, the copies in millions of lists are now wrong, and users expect removal to be immediate. The graph itself is huge and has hot spots.

OptionHow it worksGoodBad
Update every copy at onceOn delete or unfollow, remove the post or author from every affected feed.Feeds are always clean.A delete of a popular post is millions of writes. An unfollow means scanning a list. Slow and expensive.
Filter at read timeLeave the copies in place. When a feed is read, check each ID's status and each author against the user's blocks and unfollows, and drop what is not allowed.Effect is immediate. No fan-out of deletes. Cheap, since we already read the posts.Stale IDs stay in lists until cleaned. Small cost on every read.
Lazy cleanup in the backgroundA background job removes old, deleted and blocked entries over time, or they age out when the list is trimmed.Keeps lists tidy at low cost.Needs a job. Not a guarantee by itself.
Pick
Filter at read time for correctness, and clean up lazily in the background

We already fetch the posts to hydrate the page, so checking status and the author against the viewer's block and unfollow list costs almost nothing, and it is correct the moment the change happens. The stale IDs left behind are harmless: they are never shown, and they fall off the end of the list when it is trimmed to 800.

For the graph, store follows in two directions: following(user) and followers(account). Shard both by the user or account ID. A very large follower list is not read as one piece. Fan-out reads it in pages, and the list of big accounts a user follows is a small separate set that the feed service reads on every open (and caches).

EventWhat we do right awayWhat we do later
Post deletedMark status = deleted. Hydration drops it.Remove it from caches and author timeline. Trim cleans old IDs.
UnfollowRemove the edge. Read-time filter drops that author at once.Background job removes that author's IDs from the feed list.
FollowAdd the edge. Backfill the account's last 20 posts into the feed.Future posts arrive by push or pull as usual.
Block or muteAdd to the viewer's filter set. Applied at read time.Same cleanup job as unfollow.
Account becomes largeFlip the account to pull-only above the threshold.Stop pushing. Old pushed entries age out of lists.
🎤
Say it out loud
“Feeds are copies, so when someone unfollows or a post is deleted I do not chase the copies. I filter at read time. We are already fetching the posts to hydrate the page, so I check the post's status and the author against the viewer's blocks, and the change is visible immediately. The leftover IDs are harmless and get cleaned by a background job or fall off when the list is trimmed. For the graph I store follows in both directions, sharded by ID, read the big follower lists in pages, and keep a small cached set of the big accounts each user follows.”
VisualizerFan-out: where push, pull and hybrid breakStart with push and slide the followers up to 50 million. Then try pull, then hybrid, and move the threshold. Watch the two meters: writes on the left, reads on the right.
How is the feed built?
Traffic level
Fan-out writes per second vs what the fleet can do3.2M of 1.5M (213%)
Feed lookups per second vs what the cache layer can serve735k of 5M (15%)
Inserts per big post = 50M followers × 50% active = 25M
Ordinary accounts = 7k posts/s × 200 followers × 50% = 700k/s
Big accounts = 6 a minute ÷ 60 × 25M = 2.5M/s
One feed open = 1 feed list + 20 posts = 21 lookups
All feed opens = 35k/s × 21 = 735k/s
Inserts per big post
25M
50M × 50%
Big post reaches followers in
falling behind
queueing ignored
Lookups per feed open
21
about 2 round trips
Feed lists in cache
3.2 TB
500M users × 6.4 KB
One post from an account with 50M followers makes 25M inserts. The fan-out needs 3.2M inserts a second and can do 1.5M, so the queue grows by 1.7M a second. Every feed behind it, ordinary ones too, goes stale. This is the celebrity problem. Switch to hybrid.

A simplified model with made-up round numbers and no random values: 7k posts a second from ordinary accounts, 35k feed opens a second, fan-out capacity 1.5M inserts a second, cache capacity 5M lookups a second, 1 billion accounts with 6.4 KB feed lists (800 ids × 8 bytes). The “accounts followed above the threshold” counts (12, 6, 3, 1) are only there to show the idea. Round trips assume 20 parallel lookups of about 1 ms. Real systems queue, batch and vary.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
If the number of users doubles, what breaks first? If the fan-out queue has a 10-minute backlog, what do users see? If the feed cache loses a node, what happens?

What breaks first, and the fix

BottleneckFix
Fan-out write volume (1.4M inserts a second)Hybrid for big accounts, skip inactive users, batch and pipeline inserts per Redis node, and scale the workers. Partition the queue by author.
Celebrity post stormNever push above the threshold. Pull their recent posts at read time and cache that small timeline, since many users read the same one.
Feed read latencyOne list read plus one batch hydration. Keep the pull part to a few accounts. Parallelise calls and set a timeout on each step.
Hot posts in the post cacheReplicate hot entries, add a short in-process cache in the feed service, and spread keys across nodes (see Hot Keys).
Like and comment countersSharded counters: split one counter into N sub-counters and add them up on read, or batch the updates through a stream.
Feed cache memory (3.2 TB)Cache only active users, cap the list at 800 entries, shard by user ID with consistent hashing, and add replicas.
Graph reads for big accountsRead follower lists in pages, keep a cached set of big accounts per user, and shard the graph by ID.

What if a part fails?

FailureHow the design copes
Fan-out queue backs upUsers see older posts for a while, not an error. Add workers, watch the lag, and process recent posts and active users first.
A feed cache node diesReplicas take over. Lists that are missing are rebuilt by pull for the first page, then refilled in the background.
The whole feed cache is lostServe every feed by pull for a while (slower), warm the most active users first, and use rate limits so the database is not flattened.
The ranker is slow or downA 50 ms limit, then fall back to chronological order. The feed still works.
A fan-out worker crashes halfwayThe queue redelivers the event. Inserts are idempotent (same member, same score), so repeats are safe.
A region goes downServe from another region. Feeds there may be slightly behind, because fan-out is replicated asynchronously. Posts are replicated by the store.
What to monitor
  • •Fan-out lag: time from a post being saved to it appearing in feeds (p50, p99), and the queue depth
  • •Feed read latency by step (list, pull, rank, hydrate), and the share served by fallback
  • •Cache hit rate for feed lists and for posts, and the rate of rebuilds
  • •Inserts per post by account size, to tune the threshold and spot a new celebrity
  • •Errors and timeouts of the ranker, graph service and Redis nodes
  • •Duplicate and stale-post rate seen by clients (a sign of cursor or filter bugs)
Security and abuse
  • •Check visibility on every read: private accounts, blocked users and deleted posts must never leak through a cached list.
  • •Rate-limit posting, following and feed reads per user, to stop spam and scraping (see Design a Rate Limiter).
  • •Detect fake accounts that follow and post in bulk to game the ranker.
  • •Validate and sanitise post content, and scan uploads for malware.
  • •Never trust the cursor: sign it or validate it, so it cannot be used to read someone else's data.

Step 7Wrap upabout 3 min

A post is saved, published to a queue, and fanned out by workers into a cached list of post IDs per active follower. Large accounts are not pushed: their recent posts are pulled and merged when the feed is read. Reading is one list lookup, a small merge, a cheap two-stage ranker with a chronological fallback, and one batch hydration of posts, paged by a score-and-ID cursor. Deletes, blocks and unfollows are filtered at read time and cleaned lazily. Photos come from object storage and a CDN.

Trade-offs you made

DecisionWhat we gainWhat it costs
Hybrid fan-outBounded writes, fast reads, and no celebrity storms.Two code paths and a threshold to tune. Heavier reads for users who follow many big accounts.
Feed holds IDs onlyTiny feeds (6.4 KB), one copy of each post, easy deletes and edits.An extra batch lookup on every read.
Skip inactive usersAbout half of the fan-out writes disappear.A returning user gets a slower first load while the feed is rebuilt.
Asynchronous fan-outPosting is fast and bursts are absorbed by the queue.A few seconds of delay, and eventual consistency between feeds.
Filter deletes at read timeRemoval is immediate without chasing millions of copies.A small check on every read, and stale IDs until cleanup.
Approximate countersNo hot rows, and very high write rates.Counts are a little stale and may differ between users.
If we had more time, we would…
  • •Insert ads and recommendations into the ranked list in a clean, separate step.
  • •Multi-region feeds: replicate fan-out events and decide which region owns each user's cache.
  • •A shadow mode and an A/B test setup for ranking models, so changes are measured.
  • •Prefetch the first page for users likely to open the app soon (a form of cache warming).
  • •A load test with a celebrity storm and a full feed-cache loss, to check the fallbacks.
🎤
Say it out loud
“To recap: posts are saved and sent to a queue. Workers fan them out into a cached list of post IDs per active follower, except for large accounts, which are pulled and merged at read time. A feed read is one list lookup, a small merge, a cheap two-stage ranker with a chronological fallback, and one batch fetch of the posts, paged by a score and ID cursor. Deletes and unfollows are filtered at read time. The trade-offs are two paths with a threshold, a few seconds of staleness, and approximate counters. With more time I would add ads, multi-region and ranking experiments.”

Q&ACross-questions (24)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Fan-out and the celebrity problem

The part interviewers push hardest. Know the numbers and say them.

Feed storage, pagination and ranking

Data, graph and consistency

Failures, scale and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
The feed must be strictly chronological, with no rankingDrop the ranker and feature store. Scores become timestamps, which makes cursors and merges simpler. Fan-out is unchanged.
Users follow up to 5,000 accounts (not 200)Pull gets much worse, and push gets cheaper per user. Raise the cap on list size, and lean harder on push with a lower threshold for big accounts.
Posts must appear in followers' feeds within 1 secondTighter fan-out SLO: more workers, smaller batches, priority queues for recent posts, and fewer skipped paths. Possibly push to followers who are online right now first.
Add stories that disappear after 24 hoursA separate, short-lived feed with a TTL on every entry. Read at the top of the app. Same fan-out idea, smaller lists.
Add live video postsPosts become events with a state (live, ended). Notifications and fan-out are urgent, and the video itself goes through a streaming path, not this system.
Groups and pages (many-to-many) as feed sourcesMore edges per user and large groups behave like large accounts: pull for large groups, push for small ones.
Private posts visible to a custom list of friendsFan-out targets the list, and the visibility check at read time uses the list. Larger risk of leaks, so test it carefully.
Strong consistency for the author's own postShow it locally on the client at once, or merge the author's own timeline into their feed on read. No change to global fan-out.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing boxes.Asks scale, ranking and freshness, and states the scope.Finds the skew (celebrities) and the freshness-versus-cost trade-off before drawing anything.
EstimationSkips it, or only counts posts.Posts, feed opens and storage.Computes fan-out inserts (200 times the post rate) and the celebrity post, and uses them to choose the design.
Fan-out designOnly push, or only pull.Explains push and pull and picks one.Hybrid with a threshold, skips inactive users, and quantifies where each strategy breaks.
Deep divesStays on the diagram.Covers caching and pagination.Cursor pagination, ID-only lists, two-stage ranking with a fallback, and read-time filtering of deletes.
Failures and scaleSays add more servers.Mentions replicas and queues.Backlog behaviour, cache loss and rebuild, thundering herd, idempotent inserts, and monitoring fan-out lag.
CommunicationSilent or jumps around.Follows the seven steps.States numbers, names costs of each choice, and says what is out of scope and what comes next.

AvoidCommon mistakes on this question

MistakeDo this instead
Computing the feed with a big join at read timeKeep a cached list of IDs per user and fill it by fan-out. A join over 200 accounts per open does not scale.
Pushing every post to every follower, with no exceptionsDo the celebrity maths out loud (25 million inserts) and add the pull path for big accounts.
Using offset paginationUse a cursor of score and ID so new posts do not cause duplicates, and deep pages stay fast.
Storing whole posts in each feedStore IDs, keep one copy of each post, and hydrate in a batch.
Ranking with a heavy model on every postCollect candidates cheaply, score only the top 200, and have a time limit and a chronological fallback.
Trying to delete or edit every copy in every feedFilter by post status and viewer at read time, and clean up lazily.
Forgetting inactive usersSkip fan-out to users inactive for 30 days, and rebuild on return.
Never saying what it costsFor each choice say what you gain and what you pay (staleness, two paths, extra read).

Revise60-second revision sheet

  • ✔Core problem: fan-out. 7,000 posts a second × 200 followers is 1.4 million inserts a second.
  • ✔Feed: a cached sorted list of post IDs per active user (about 800 × 8 bytes = 6.4 KB, 3.2 TB total).
  • ✔Hybrid: push for normal accounts, pull and merge for accounts above about 100k followers.
  • ✔Celebrity: 50M followers is about 25M inserts per post. Never push it.
  • ✔Skip inactive: no fan-out to users away for 30 days. Halves the writes.
  • ✔Read: list + pull + filter + rank top 200 + batch hydrate 20 posts. About 21 to 27 lookups.
  • ✔Pagination: cursor of (score, id), never an offset.
  • ✔Deletes and unfollows: filter at read time, clean lazily.
  • ✔Failure: queue absorbs spikes, inserts are idempotent, a lost cache is rebuilt by pull, the ranker has a fallback.
  • ✔Counters: sharded and approximate. A unique (user, post) row keeps likes exact.

Read these topics next

Caching Strategies→

The feed list and the post cache are a read-through, write-ahead cache.

Hot Keys→

Celebrity timelines, hot posts and counters are all hot-key problems.

Sharding→

Posts and the follow graph are sharded by ID.

Message Queues→

The fan-out queue absorbs spikes and retries failures.

Pagination, Filtering and Sorting→

Cursor pagination is the right way to page a moving list.

Cache Warming→

Rebuilding and prefetching feeds for returning users.

Consistent Hashing→

Spreading feed lists over cache nodes with little movement.

Design a Rate Limiter→

Protects posting, following and feed reads from abuse.

← Previous
Design a Chat App
Next →
Design a Notification System