Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

System Design blueprint · Social media

Social news feed with fan-out

Precomputing each follower's feed makes opening the app one fast read, even with millions of users.

Steps
6
Subjective questions
32
Objective questions
32

The problem and the outcome

Problem: Building a feed by querying everyone you follow on every open is far too slow.

Outcome: Feeds open in milliseconds, and celebrity posts no longer melt the system.

Architecture

Author posts01Post servicePosts DBFan-outworkers02Feed cacheper follower03Reader opensthe app04Celebrity postspulled on read05Ranking model06savepush IDsreadmergeorder

How it works, step by step

  1. A new post is saved once in the posts store.
  2. Fan-out workers push the post ID into every follower's feed (fan-out on write).
  3. Each feed is a capped list of post IDs in a cache, so reading it is one fast lookup.
  4. Opening the app reads the precomputed feed instead of querying everyone you follow.
  5. Accounts with millions of followers skip fan-out; their posts are merged in at read time.
  6. A ranking model orders the merged list by predicted interest.

Tech stack

  • Post store (Cassandra / MySQL)
  • Fan-out workers on a queue
  • Redis lists or sorted sets per user
  • Ranking model
  • Graph store for follows

Key design decisions

  • Fan-out on write for most authors: push each post ID into followers' feed caches, so reading is one fast fetch.
  • Fan-out on read for celebrities, merging their recent posts at read time instead of writing to millions of feeds.
  • Store only post IDs in feeds and hydrate the posts in a batch, so edits and deletes show everywhere.

Common mistakes

  • Pushing a celebrity's post to 50 million feeds synchronously.
  • Storing full post bodies in every feed, so one edit means millions of writes.
  • Unbounded feed lists that grow forever in memory.

What to measure

  • Feed load p99
  • Fan-out lag (post to visible)
  • Feed cache memory per user
  • Engagement per session

Most-asked interview questions

Subjective questions 32

1Fan-out on write vs. fan-out on read: when do you use each?Asked almost every time

Fan-out on write precomputes feeds when someone posts, so reads are fast; it suits most users with modest follower counts. Fan-out on read assembles the feed when it is opened; it suits accounts with huge followings and users who rarely log in. Large networks use a hybrid of both.

2Walk through the architecture of a news feed system.Asked almost every time

A post service stores posts; a fan-out service, triggered by new-post events, pushes post IDs into followers' feed caches (Redis lists or sorted sets) for normal accounts. The feed service reads a user's cached feed, merges posts from followed celebrities at read time, hydrates IDs with post and user data from caches, ranks and paginates.

3How do you store the social graph?Asked almost every time

Store follow relationships in a table or graph store indexed both ways (followers of X, followees of Y), cache follower lists for active users, and shard by user ID. Graph databases help for multi-hop queries, but most feeds need only one hop.

4How would you rank a feed with machine learning?Asked almost every time

Generate candidates (recent posts from follows, popular posts, recommendations), compute features (author affinity, recency, engagement predictions, content type), score with a model predicting actions like clicks or likes, apply business rules (diversity, freshness, policy) and log impressions to train the next model.

5How do you paginate a feed that changes while the user scrolls?Very often asked

Use cursor-based pagination, such as 'items older than this post ID or timestamp', not page offsets. New posts arriving at the top then do not shift or duplicate items on later pages.

6How would you rank the feed instead of showing it in time order?Very often asked

Gather candidates from the precomputed feed and other sources, score each with a model using features such as affinity with the author, recency, and predicted likes or comments, then apply rules for diversity and freshness. Ranking runs at read time on a few hundred candidates.

7Why store only post IDs in feed caches?Very often asked

IDs are small, so millions of feeds fit in memory. Post content can change or be deleted and is stored once; feeds hydrate IDs at read time from a post cache, so edits and deletions apply everywhere.

8How do you handle a deleted post or a blocked user?Very often asked

Mark the post deleted in the post store and filter during hydration, so it disappears from all feeds without rewriting them; filter blocked or muted authors at read time and optionally clean caches asynchronously.

9How do you limit the size of feed caches?Very often asked

Keep only the latest few hundred items per feed (trim on insert), expire feeds of inactive users and rebuild them on demand when they return, saving memory for active users.

10How do you make the feed feel real-time?Very often asked

Push a 'new posts available' signal over WebSockets or SSE, or poll lightly, and let the user tap to load new items at the top rather than shifting content while they read.

11How do you handle users who follow many accounts?Very often asked

Merging at read time becomes expensive, so rely on fan-out on write for most of them, cap merging to recent posts, and precompute ranked candidates in the background for heavy users.

12How do you count likes and comments at scale?Very often asked

Increment counters asynchronously via events, use sharded counters or Redis for hot posts, write aggregated counts to the database periodically, and accept that displayed counts may be slightly behind.

13What consistency does a feed need?Very often asked

Eventual consistency is acceptable: a new post may appear in followers' feeds a few seconds later. Users should see their own posts immediately (read-your-writes), which you can do by inserting into their own feed synchronously.

14Fan-out on write vs. fan-out on read: how do you choose?Very often asked

Fan-out on write pushes a new post ID into every follower's feed cache, giving fast reads but expensive writes for accounts with many followers. Fan-out on read assembles the feed at request time, cheap to write but slower to read. Most systems use a hybrid: push for normal users, pull for celebrities.

15How would you design cursor pagination for an infinite feed?Very often asked

Return a page of posts with an opaque cursor containing the ranking score or timestamp and post ID of the last item. The next request fetches items after that position, which stays stable while new posts arrive and avoids the cost of OFFSET.

16How do you add ads or recommended posts to a feed?Often asked

Blend them in at ranking time with rules for spacing and frequency, label them clearly, and track their impressions separately; recommendations come from a separate candidate generator.

17How do you avoid showing the same post twice when paginating?Often asked

Use cursors based on a stable ranking score or post ID plus timestamp, and keep a short-lived snapshot of the ranked list per session so new posts do not shift pages.

18How do you backfill a feed when a user follows someone new?Often asked

Fetch the followee's recent posts and merge them into the user's feed cache asynchronously; when unfollowing, filter that author out at read time and clean up lazily.

19How do you serve media in feed posts?Often asked

Store media in object storage, generate multiple sizes and formats on upload, serve through a CDN, and lazy-load images and videos as the user scrolls.

20How do you moderate content in a feed?Often asked

Run automated classifiers on new posts (spam, abuse, nudity), queue borderline cases for human review, respect user reports, and hide or down-rank flagged content at read time while decisions are pending.

21How do you estimate storage for feed caches?Often asked

Multiply active users by items kept per feed by bytes per item (an ID and score, roughly 16–20 bytes): for 100 million users with 500 items, that is around 1 TB, spread across a Redis cluster.

22What is the cold-start problem for new users' feeds?Often asked

New users follow nobody, so the feed is empty. Suggest accounts to follow during onboarding and fill the feed with popular or interest-based recommendations until they build a graph.

23How do you test ranking changes?Often asked

Run offline evaluation on logged data, then A/B test online with metrics like engagement, time spent, hides and reports, watching for long-term effects rather than only clicks.

24How do you add stories or other time-limited content to a feed?Often asked

Store stories separately with an expiry time and a TTL, fetch them per followed user as a small ordered tray above the feed, cache recent stories per author, and remove them automatically when they expire rather than deleting from every feed.

25How do you avoid the rich-get-richer problem in ranking?Often asked

Blend exploration with exploitation: reserve a share of slots for fresh posts or less-seen authors, decay engagement signals over time, cap repeated exposure to the same author, and measure diversity alongside engagement.

26How would you support a chronological feed option alongside a ranked one?Often asked

Keep the same candidate set of followed posts and simply skip the ranking step, sorting by creation time. Store the user's choice, and cache the two orderings separately so switching does not invalidate the other.

27How do you keep the feed fast on slow mobile networks?Often asked

Send a small first page with compact post data and low-resolution image placeholders, prefetch the next page while the user scrolls, use HTTP compression and responsive images from the CDN, and cache the last feed locally for instant display on open.

28Which data store suits the feed cache?Sometimes asked

Redis sorted sets (score by time or rank) or lists give fast inserts and range reads; Cassandra or a wide-column store can persist feeds for larger, durable storage.

29How do you handle a viral post with millions of likes?Sometimes asked

Shard its counter, cache its hydrated data at every layer including the CDN for public views, and rate-limit write-heavy actions on it.

30What are the main metrics for a feed?Sometimes asked

Feed load latency, freshness (time from post to appearance), engagement rates, session length, hides and reports, and cache hit rates for hydration.

31How do privacy settings affect the feed?Sometimes asked

Each post carries its audience (public, followers, close friends); hydration checks the viewer's permission before returning a post, so changes in privacy take effect immediately.

32How do you explain to users why a post appears in their feed?Sometimes asked

Record the main ranking reasons at serving time, such as following the author, a friend liked it or a topic match, and show a short 'why am I seeing this' label with controls to see less of that author or topic.

Objective questions 32

1Which approach makes opening the feed fastest for typical users?Asked almost every time
  1. AFan-out on read
  2. BFan-out on writeCorrect answer
  3. CFull table scan
  4. DClient-side filtering

Why: The feed is already built when the user opens the app, so reading it is one lookup.

2What is usually stored in each user's feed cache?Asked almost every time
  1. ASQL queries
  2. BPost IDs with scoresCorrect answer
  3. CFull post content and images
  4. DEntire user profiles

Why: Small IDs fit in memory; content is hydrated.

3How should a user see their own new post?Asked almost every time
  1. AImmediately, by inserting into their own feedCorrect answer
  2. BAfter the next rebuild
  3. COnly on refresh tomorrow
  4. DNever

Why: Read-your-writes for the author.

4How are deleted posts removed from millions of feeds?Asked almost every time
  1. ARewriting every feed synchronously
  2. BWaiting for TTLs
  3. CThey are not removed
  4. DFiltered during hydrationCorrect answer

Why: Mark the post deleted once.

5What is the usual fix for celebrity accounts?Very often asked
  1. ABlock them from posting
  2. BPull their posts at read timeCorrect answer
  3. CStore their posts in the client
  4. DShard them by country

Why: A hybrid model merges celebrity posts at read time instead of writing them to millions of feeds.

6What does an ML ranking model typically predict?Very often asked
  1. AServer load
  2. BThe author's age
  3. CLikelihood of actions like clicks or likesCorrect answer
  4. DThe post's word count

Why: Scores rank candidates.

7How do you keep feed caches from using too much memory?Very often asked
  1. AStore images in Redis
  2. BDisable caching
  3. CTrim to recent items and expire inactive usersCorrect answer
  4. DStore everything forever

Why: Rebuild feeds on demand when users return.

8How should new posts appear while a user is reading?Very often asked
  1. AReload the page
  2. BNever
  3. CA 'new posts' prompt to load themCorrect answer
  4. DShift content automatically

Why: Avoids moving content under the reader.

9How are like counts kept fast for hot posts?Very often asked
  1. ASharded counters updated asynchronouslyCorrect answer
  2. BOne row locked per like
  3. CRecounting on every view
  4. DClient-side only

Why: Slightly delayed counts are fine.

10Feeds generally require…Very often asked
  1. AEventual consistencyCorrect answer
  2. BStrict serialisability
  3. CTwo-phase commit
  4. DNo consistency

Why: A few seconds of delay is acceptable.

11What helps new users with empty feeds?Very often asked
  1. AFollow suggestions and recommendationsCorrect answer
  2. BShowing nothing
  3. CShowing errors
  4. DRandom old posts only

Why: The cold-start problem.

12Fan-out on write makes which operation cheap?Very often asked
  1. AReading the feedCorrect answer
  2. BPosting as a celebrity
  3. CDeleting a user
  4. DChanging privacy settings

Why: Feeds are precomputed, so reads are a cache lookup.

13Why do feed APIs use cursors instead of OFFSET?Very often asked
  1. AOFFSET is not supported by SQL
  2. BCursors disable caching
  3. CPositions stay stable as new posts arriveCorrect answer
  4. DCursors use more memory

Why: New posts would shift OFFSET pages and cause duplicates.

14Which pagination style suits an infinite feed?Often asked
  1. ACursor-basedCorrect answer
  2. BRandom sampling
  3. CPage numbers in the URL only
  4. DOFFSET / LIMIT

Why: Cursors stay stable as new items are inserted, so the user does not see repeats or gaps.

15What prevents duplicates across feed pages?Often asked
  1. ACursors with a stable session snapshotCorrect answer
  2. BOffset pagination
  3. CRandom ordering
  4. DReloading pages

Why: New posts do not shift pages.

16Which Redis structure suits a ranked feed?Often asked
  1. AString
  2. BHyperLogLog
  3. CBitmap
  4. DSorted setCorrect answer

Why: Score by time or rank.

17When a user follows someone new, their feed…Often asked
  1. AIs deleted
  2. BStays unchanged forever
  3. CIs rebuilt synchronously for all users
  4. DIs backfilled with recent posts asynchronouslyCorrect answer

Why: Merge in the background.

18How are ads blended into a feed?Often asked
  1. ABy replacing every other post
  2. BRandomly
  3. COnly at the top
  4. DAt ranking time with spacing rulesCorrect answer

Why: Label sponsored posts clearly.

19How should ranking changes be validated?Often asked
  1. ACheck CPU only
  2. BOffline evaluation then A/B testsCorrect answer
  3. CDeploy to everyone at once
  4. DAsk one user

Why: Watch long-term metrics.

20Where should media in posts be served from?Often asked
  1. AThe database
  2. BThe app server
  3. CA CDN in multiple sizesCorrect answer
  4. DThe feed cache

Why: Lazy-load while scrolling.

21How are post privacy settings enforced?Often asked
  1. AThey are not
  2. BPermission checks during hydrationCorrect answer
  3. COnly at posting time
  4. DBy the CDN

Why: Changes apply immediately.

22Borderline flagged posts should be…Often asked
  1. ADeleted instantly always
  2. BIgnored
  3. CQueued for human review and down-rankedCorrect answer
  4. DShown at the top

Why: Classifiers are not perfect.

23Stories that expire after 24 hours are best removed by…Often asked
  1. AA weekly batch job
  2. BUsers manually
  3. CA TTL on separately stored storiesCorrect answer
  4. DDeleting them from every feed cache

Why: Separate storage with expiry avoids touching millions of feeds.

24Reserving slots for fresh posts helps…Often asked
  1. AReduce storage
  2. BSpeed up writes
  3. CEncrypt posts
  4. DAvoid rich-get-richer rankingCorrect answer

Why: New authors get a chance to be seen.

25A chronological feed option needs…Often asked
  1. AThe same candidates sorted by timeCorrect answer
  2. BA completely separate social graph
  3. CNo caching
  4. DA new database

Why: It is the ranked pipeline without the ranking step.

26Which helps feeds load fast on slow networks?Often asked
  1. AFull-size images only
  2. BSmall first pages and image placeholdersCorrect answer
  3. CSending all posts at once
  4. DDisabling compression

Why: Less data first means faster first paint.

27Roughly how much memory do 100M feeds of 500 IDs need?Sometimes asked
  1. AAround 1 TBCorrect answer
  2. BAround 1 GB
  3. CAround 10 MB
  4. DAround 1 PB

Why: About 20 bytes per item.

28Which metric measures post-to-feed delay?Sometimes asked
  1. ABounce rate
  2. BUptime
  3. CFreshnessCorrect answer
  4. DClick-through rate

Why: Time from post to appearance.

29How is a viral post's public view load handled?Sometimes asked
  1. ADisabling it
  2. BServing from the primary DB
  3. CRate-limiting reads to zero
  4. DCaching it at every layer including the CDNCorrect answer

Why: Caching spreads the read load.

30Social graph lookups need indexes in…Sometimes asked
  1. ABoth directions: followers and followeesCorrect answer
  2. BOne direction only
  3. CNo direction
  4. DAlphabetical order only

Why: Fan-out needs followers.

31Muted authors are best handled by…Sometimes asked
  1. ABlocking the author's account
  2. BFiltering at read timeCorrect answer
  3. CRewriting every past feed
  4. DDeleting their posts

Why: Read-time filtering is cheap and immediate.

32A 'why am I seeing this' label is built from…Sometimes asked
  1. AThe user's password
  2. BServer logs only
  3. CRanking reasons recorded at serving timeCorrect answer
  4. DRandom text

Why: Real reasons build trust and give useful controls.

Track your progress through every blueprint in your dashboard.

Start learning