SkillSprout
Chapter 6 · Lesson 4
Advanced
25 min read

Design a News Feed (Facebook-style)

Overview

A news feed is the home screen of a social network: a personal list of posts from your friends, the pages you follow and the groups you joined. Unlike a plain timeline, it is ranked. Out of thousands of posts you could see, the system picks the few hundred that matter most to you and puts the best ones first. That makes the problem a mix of data plumbing (collecting posts fast) and decision making (scoring them cheaply). This lesson walks the eight-step interview framework with the reasoning to say out loud: candidate generation, a simple scoring formula (with an ML ranker as the upgrade), the feed publisher, ranking service and feed cache, stable cursor pagination, privacy checks, ads, and what happens when parts of the system fail.

Detailed Notes

How to use this lesson

Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about any real company. The interviewer will not check that 500 million daily users is realistic; they will check that your estimates drive your design. This lesson focuses on the ranked, personalized feed. A separate lesson covers the Twitter-style timeline, where ordering is mostly chronological.

Four terms are used throughout:

  • A candidate is a post that might be shown to a user. Generating candidates means collecting posts that are eligible.
  • A feature is a measurable fact used for scoring, such as "how often this viewer likes this author's posts" or "how many likes the post has".
  • Ranking means giving each candidate a score from its features and sorting by that score.
  • Fan-out means copying one post into the feeds of everyone who should see it (the push-versus-pull idea from the fan-out trade-off lesson).

Step 1: Clarify Requirements

Spend the first five minutes turning "design Facebook's news feed" into a precise scope. A good opening: "Should the feed be ranked or chronological, and does it include pages and groups, or only friends?"

Functional requirements

  • A user opens the app and sees a feed of posts from friends, followed pages and joined groups.
  • The feed is ranked: the most relevant posts appear first, not simply the newest.
  • The feed is paginated: the user scrolls and the app loads more posts without duplicates or gaps.
  • A user can publish a post (text plus media links) with an audience: public, friends only, or a specific group.
  • The user can switch to a chronological view (newest first).

Extended requirements

Mention these and ask whether to include them. Do not design them in depth unless asked.

  • Ads inserted between organic posts (we cover the integration at a high level).
  • Feedback signals: like, comment, share, hide, "see less of this".
  • Notifications and a "new posts available" banner.

Non-functional requirements

  • Low latency: p99 feed load under 500 ms. (p99 means 99 of 100 requests finish faster.) Users open the feed constantly and abandon slow screens.
  • High availability: 99.99% for reading the feed. A degraded feed is far better than an error page.
  • Freshness: a friend's new post should be eligible for ranking within about 10 seconds for 99% of posts.
  • Personalization quality: ranking should measurably raise engagement, but a slightly stale score is acceptable.
  • Privacy correctness: a post must never reach someone not allowed to see it. This one is not negotiable and never traded for speed.
  • Scalability: hundreds of millions of daily users and tens of thousands of feed loads per second.

Consistency decision. Feed contents can be eventually consistent: a post appearing 10 seconds late is fine. Privacy cannot be: after you block someone, their posts must vanish immediately. Say this early; it shapes where the privacy check lives (Step 6).

Out of scope

Post creation UI, media upload and transcoding, full ads auction mechanics, search, messaging, and the training pipeline of the ML model. We will describe how a model plugs in, not how it is trained.

Interview tip. Candidates often draw "post service, feed table, cache" and never mention ranking. For a Facebook-style feed, the interviewer wants to hear how posts are chosen and ordered. Ask early whether the feed is ranked, and name the stages: candidates, features, score, filter.

Step 2: Estimate Scale

Estimation tells you which parts are hard. Round every number so you can do the arithmetic aloud.

Assumptions to state

  • 1 billion monthly users, 500 million daily active users (DAU).
  • Each active user opens the feed 10 times per day.
  • 20% of daily users publish one post per day: 100 million posts a day.
  • A user has about 200 friends, and about half of them are recently active (opened the app in the last 7 days).
  • Pages and groups are followed or joined by many users; a few have millions of followers.
  • A feed page has 20 posts; one post card (text, metadata, media URLs, not the media bytes) is about 1 KB.
  • A day has about 100,000 seconds.

Request load

text
Feed loads per day      = 500M users x 10 opens        = 5 billion
Feed loads per second   = 5B / 100,000 seconds         = 50,000 per second
Peak (x3 factor)        = 50,000 x 3                   = 150,000 per second

Posts per day           = 500M x 20%                   = 100 million
Posts per second        = 100M / 100,000               = 1,000 per second (3,000 at peak)

Read-to-write ratio     = 50,000 / 1,000               = 50 : 1

So what: reads outnumber writes 50 to 1, and each read is expensive because it must rank. The read path gets the optimization effort, but the write path is not tiny either, as the next calculation shows.

News Feed: Estimate the Scale
Estimation

Request load

500Mdaily active users
given
5Bfeed loads / day
× 10 opens
50K/sfeed loads
÷ 100,000 s
150K/sat peak
× 3 peak factor
100K/sfan-out inserts
100M posts × 100

Feed cache

4 TB

500M users × 500 IDs × 16 bytes (8 KB each)

IDs only, in memory, for daily users

Ranking CPU

~750 cores

150K req/s × 500 candidates × 10 µs

Two-stage funnel, rank once per session

Fan-out writes

100K/s

300K/s at peak; one big page post = millions

Hybrid: pull for huge accounts
Key point. Rank in a two-stage funnel, cache IDs only, and give big accounts a pull path.

Reads drive ranking CPU, writes drive fan-out. Both come from 500 million daily users.

Fan-out writes

If we precompute feeds, every post is copied into each recently active friend's feed list:

text
Copies per post         = 200 friends x 50% active     = 100
Feed inserts per day    = 100M posts x 100             = 10 billion
Feed inserts per second = 10B / 100,000                = 100,000 per second
Peak (x3)               = 300,000 per second

So what: 1,000 posts per second turn into 100,000 cache writes per second. That is manageable for a sharded in-memory cache, but only for normal users. A page with 5 million followers would cause 5 million writes for a single post, so big accounts need a different treatment (Step 6.3).

Ranking compute

text
Candidates per request       = about 500 posts
Cheap scoring cost           = 10 microseconds per candidate
CPU per request              = 500 x 10 us = 5 ms
Cores at peak                = 150,000 req/s x 5 ms = 750 cores
With 2x headroom             = 1,500 cores = about 50 machines of 32 cores

An ML model at 100 us per candidate on all 500 would cost 10x more: 7,500 cores.
Run it only on the best 100 after the cheap stage: 100 x 100 us = 10 ms
per request x 150,000 = 1,500 cores.

So what: ranking is a real CPU bill. Use a two-stage funnel: a cheap score over about 500 candidates, then a costlier model over only the top 100.

Feed cache size

text
Entry per post               = post_id (8 bytes) + timestamp/source (8 bytes) = 16 bytes
Feed list per user           = 500 entries x 16 bytes = 8 KB
All daily users              = 500M x 8 KB            = 4 TB
With one replica             = 8 TB = about 125 nodes with 64 GB of memory each

So what: the feed cache stores only IDs, which keeps it small enough for memory. We cache only daily active users and cap each list at 500; a returning inactive user triggers an on-demand rebuild.

Storage, bandwidth and events

text
Posts                  = 100M/day x 1 KB      = 100 GB/day = about 37 TB/year (185 TB in 5 years)
Feed response          = 20 posts x 1 KB      = 20 KB per page
Outgoing bandwidth     = 50,000/s x 20 KB     = 1 GB/s = 8 Gbps average, about 24 Gbps at peak
Impression events      = 5B loads x 20 posts  = 100B/day = 1,000,000 events per second
Impression volume      = 100B x 100 bytes     = 10 TB/day (30 TB for 3 days of stream retention)
Engagement events      = 5B/day (10 per user) = 50,000 per second

So what: post metadata is modest. Media bytes are served by a CDN (a network of edge servers close to users), not by feed servers. The activity event stream is the biggest data flow in the system (a million events per second), so events must be batched by the client and flow through a partitioned message queue, never through a database on the request path.

Interview tip. Always end with "so what": "100,000 fan-out writes a second means sharded cache writes, celebrities need pull, 750 cores of ranking means a two-stage funnel."

Step 3: Define the APIs

Read the feed

http
GET /v1/feed?limit=20&cursor=eyJzIjoiZnMtOWE3IiwicCI6MjB9&sort=ranked
Authorization: Bearer <token>
json
{
  "items": [
    {
      "type": "post",
      "post_id": "7301944820113",
      "author": { "id": "u_42", "name": "Maya", "kind": "user" },
      "body": "Weekend hike!",
      "media": ["https://cdn.example.com/p/881.jpg"],
      "like_count": 14,
      "created_at": "2026-11-28T09:12:00Z",
      "reason": "friend"
    },
    {
      "type": "ad",
      "ad_id": "ad_551",
      "sponsored": true,
      "body": "Trail shoes, 20% off",
      "impression_token": "tok_ab12"
    }
  ],
  "next_cursor": "eyJzIjoiZnMtOWE3IiwicCI6NDB9",
  "ranking": "ranked"
}
  • sort is ranked (default) or chronological.
  • The cursor is an opaque token. The client never parses it, only sends it back.
  • ranking tells the client whether it got the ranked feed or a degraded fallback.

Status codes: 200 OK; 401 Unauthorized; 410 Gone if the cursor's feed session expired (the client reloads from the top); 429 Too Many Requests if the client polls too fast; 503 Service Unavailable only as a last resort (we prefer degraded 200 responses).

Publish a post

http
POST /v1/posts
Idempotency-Key: 5c1e-77ab
Content-Type: application/json

{ "body": "Weekend hike!", "media": ["m_881"], "audience": "friends" }

Returns 201 Created with the post_id, 400 for invalid audience, and replays the first response if the same Idempotency-Key arrives again (so a retry does not publish twice).

Supporting APIs

http
GET  /v1/feed/new-count?since=<post_id>   # "12 new posts" banner, polled every 60 s
POST /v1/events                           # batched impressions and engagement
DELETE /v1/posts/{post_id}                # author deletes; removed from every feed

How the API shapes the architecture

GET /v1/feed is the hot, latency-critical endpoint and does not accept "page numbers": it accepts a cursor, which lets the server freeze an ordering for the scroll session. POST /v1/events takes batches because a million single events per second would be wasteful.

Step 4: Define the Data Model

Start from access patterns:

  1. Read a viewer's candidate post IDs (150,000 per second at peak).
  2. Get posts by ID to build the response (about 20 per feed page).
  3. List the sources of a viewer (friends, pages, groups) and list followers of an author (for fan-out).
  4. Append events at a million per second.
  5. Read features such as affinity between a viewer and an author.

Fields and why each exists

  • posts.post_id: a time-sortable unique ID (the Snowflake idea from the unique-IDs lesson) so newer posts sort higher and IDs need no coordination.
  • posts.audience: who may see it. The privacy check reads this on every request.
  • posts.status: active, hidden or deleted. Deleting sets the status; cached IDs are filtered at read time.
  • edges: one row per relationship (friend, follow page, member of group). It is stored twice: by viewer (pull path) and by source (fan-out path).
  • feed_cache: a capped list of (post_id, ts, source_kind) per viewer. Holds IDs only; the post content is fetched later.
  • feed_sessions: a frozen, ranked list of IDs for one scroll session; this is what makes pagination stable.
  • affinity: a precomputed 0 to 1 closeness between a viewer and an author, built from past likes, comments and profile visits.
  • activity_events: append-only record of impressions and engagement, the source of all learning signals.
The Data Model
Data model
postsKey-value / wide-column
  • PKpost_idbigint

    time-sortable unique ID

  • IDXauthor_idbigint

    user, page or group; for 'recent posts by author'

  • author_kinduser | page | group
  • audiencepublic | friends | group:id

    read by every privacy check

  • bodytext
  • media_refslist<string>

    blob storage keys, not bytes

  • created_attimestamp
  • statusactive | hidden | deleted

Partitioned by post_id so popular authors do not create a hot partition.

edgesKey-value store
  • PKviewer_idbigint

    pull path: what does this viewer follow?

  • SKsource_idbigint

    friend, page or group

  • edge_kindfriend | follow | member
  • IDXsource_id (reverse copy)bigint

    fan-out path: who follows this author?

  • blockedboolean

    checked at read time

One-hop reads only, so a graph database is unnecessary. Stored twice for both directions.

feed_cacheIn-memory cache
  • PKviewer_idbigint
  • SKpost_idbigint

    newest first, capped at 500

  • tstimestamp

    chronological fallback order

  • source_kindfriend | page | group

Derived data: can always be rebuilt from posts and edges.

feed_sessionsIn-memory cache (TTL 15 min)
  • PKsession_idstring

    inside the signed cursor

  • IDXviewer_idbigint
  • ranked_idslist<bigint>

    top 200, frozen order

  • expires_attimestamp

Freezing the order is what makes page 2 consistent with page 1.

affinityFeature store
  • PKviewer_idbigint
  • SKauthor_idbigint
  • affinityfloat 0..1

    hourly batch from engagement

  • updated_attimestamp

Input to scoring. Per-post counters are kept in the same store.

activity_eventsEvent stream
  • PKuser_idbigint

    partition key keeps one user's events in order

  • SKtstimestamp
  • event_typeimpression | like | comment | hide
  • post_idbigint

Append-only, about 1M events per second.

  • feed_cache.post_idposts.post_id· refers to
  • edges.source_idposts.author_id· source of posts
  • activity_events.post_idposts.post_id· many to one
Key point. The feed cache and sessions hold only post IDs. Everything else is looked up on demand.

Content, relationships, derived feed lists, learned features and events live in different stores.

Which databases?

  • Posts: lookups by post_id plus "recent posts by author". A key-value or wide-column store partitioned by post_id with a secondary index on author_id fits. Partitioning by author_id would make a popular author a hot partition.
  • Edges: the social graph is huge but queried only by one hop (friends of X). Two copies in a partitioned key-value store are enough; a graph database is not needed for one-hop reads.
  • Feed cache and sessions: an in-memory store with TTL, because they are derived data and can be rebuilt.
  • Events: a message queue / event stream feeding a data lake, never a transactional database.

Trade-off thinking. Storing a feed as IDs only makes the cache 10x to 50x smaller than storing full posts, and edits or deletes need no cache rewrite. The price is one extra batch lookup (hydration) per page. At 20 posts per page that lookup is cheap, so we take that deal.

Step 5: High-Level Design

Separate the write path (publishing and fan-out) from the read path (ranking and serving). They have different loads and failure rules.

The Write Path and the Read Path
Architecture
Write pathRead pathClientapp / browserAPI gatewayauth, limits, LBPost service~1K posts/sPost storesource of truthFeed service~50K loads/sEvent streampost createdRanking servicescore + sortFeed publisherfan-out workersFeed cacheIDs per viewer1POST /postsGET /feedsavehydrateconsumeappend IDscandidates
Key point. The event stream decouples publishing from fan-out, and ranking is its own scalable service.

Publishing fans IDs into the feed cache; reading collects candidates and ranks them.

Components and why each exists

  • API gateway / load balancer: authentication, rate limiting, and spreading traffic across identical servers.
  • Post service (write path): validates and stores a post, then publishes a "post created" event.
  • Activity event stream: a durable message queue carrying post-created events and engagement events. It decouples publishing from fan-out so a slow consumer never blocks a user.
  • Feed publisher (write path): consumes post events, looks up the author's followers, applies privacy rules, and appends the post ID to each recently active viewer's list in the feed cache.
  • Feed cache: precomputed candidate IDs per viewer.
  • Feed service (read path): coordinates one feed request: gets candidates, asks for ranking, hydrates, filters, inserts ads.
  • Ranking service (read path): reads candidate IDs, fetches features, scores and sorts. It is stateless and scaled by CPU.
  • Post store: the source of truth for post content.
Loading Page 1, Then Page 2
Request flow
AppFeed serviceFeed cacheRanking service1GET /v1/feed2read candidate IDsplus pulled big pages and groups3~500 IDs4score candidatesfeatures fetched in one batch5top 200, ordered6save session (15 min)720 posts + cursorhydrate, privacy check, ads8GET ?cursor=...9next 20 from sessionno re-ranking
Key point. Page 2 never re-ranks, so it cannot duplicate or skip posts.

Ranking happens once per session. Later pages read the frozen list.

Request flow

Write path.

  1. Client sends POST /v1/posts; the gateway authenticates.
  2. The post service saves the post and emits post_created to the stream.
  3. The feed publisher consumes it, fetches followers, skips blocked or ineligible viewers, and appends the ID to each active viewer's feed list.

Read path.

  1. Client sends GET /v1/feed.
  2. The feed service reads the viewer's precomputed IDs plus fresh posts from big pages and groups.
  3. The ranking service scores about 500 candidates and returns the top 200 in order.
  4. The feed service saves them as a feed session, hydrates the first 20, applies the privacy check, adds ads and returns page 1 with a cursor.

Step 6: Deep Dive

For a ranked feed, spend most of the time on candidates, scoring, the fan-out choice and pagination.

6.1 Candidate generation

Candidate generation answers: which posts are worth scoring at all? We cannot score every post from the last week, so we narrow it to about 500.

Sources, merged and de-duplicated:

  • Precomputed friend posts from the feed cache (cheap, already fanned out).
  • Pulled posts from big pages and groups: the latest 20 posts of each large source the viewer follows, from a "recent posts by source" cache.
  • Backfill for returning users whose cache is empty or stale: read the latest posts from their top friends and rebuild.
  • Time limit: drop anything older than about 7 days.

Cap each source so one chatty group cannot fill all 500 slots. Then remove posts the viewer already saw recently (a per-user "seen" set, which can be a Bloom filter: small, fast, and may rarely hide an unseen post, which is acceptable).

6.2 Features and the ranking stage

Start with a simple, explainable scoring formula. It is the right first answer in an interview because you can compute it by hand:

text
score = affinity x content_weight x engagement_boost x freshness

affinity          0 to 1, how close viewer and author are
content_weight    photo 1.2, video 1.3, link 1.0, text 0.9
engagement_boost  1 + log10(1 + likes + 2 x comments)
freshness         0.5 ^ (age_hours / 6)     (half-life of 6 hours)

Worked example with three candidates:

text
A: close friend photo, 2 h old, 10 likes + 2 comments
   affinity 0.8, weight 1.2, boost = 1 + log10(15) = 2.2, freshness = 0.5^(2/6) = 0.79
   score = 0.8 x 1.2 x 2.2 x 0.79 = 1.7

B: page link, 12 h old, 1,000 likes + 200 comments
   affinity 0.3, weight 1.0, boost = 1 + log10(1,401) = 4.1, freshness = 0.5^(12/6) = 0.25
   score = 0.3 x 1.0 x 4.1 x 0.25 = 0.31

C: group text post, 30 min old, no engagement yet
   affinity 0.5, weight 0.9, boost = 1.0, freshness = 0.5^(0.5/6) = 0.94
   score = 0.5 x 0.9 x 1.0 x 0.94 = 0.42

The order is A, C, B. The new group post beats the viral but old page post because freshness and affinity outweigh raw popularity. The logarithm prevents a post with 1,000 likes from scoring 100 times higher than a post with 10.

Where features come from. A feature store (a fast key-value store of precomputed facts) holds viewer-author affinity and per-post counters. Batch jobs recompute affinity hourly from the activity events; counters are updated within seconds by stream consumers. The ranking service fetches them in one batched call for all 500 candidates (never 500 separate calls).

The ML upgrade. Production feeds replace the formula with a trained model that predicts, per candidate, the chance of a like, comment, share or hide, then combines those probabilities into one score. Because that model is about 10x costlier, the two-stage funnel from Step 2 applies: the cheap formula trims 500 candidates to about 100, then the model re-ranks those. The feature store and the logged impressions are exactly the inputs the model needs, so the architecture does not change when you upgrade.

The Ranking Funnel
Architecture
Feed cachefriend post IDsBig sourcespages and groupsCandidate merge~500, dedupedFetch featuresone batched callFeature storeaffinity, countersScore: formulakeep top ~100ML rankeroptional upgradePrivacy filter~200 kept, orderedPage builder20 posts + ads500 IDsfeaturesre-ranks
Key point. Cheap work on many candidates, expensive work on few. The ML ranker plugs into the same slot.

Each stage gets more expensive per post and sees fewer posts.

Trade-off thinking. A formula is predictable, debuggable and cheap, but handcrafted weights plateau. A model finds patterns humans miss but needs training data, monitoring for drift and more CPU. Say: "formula first as a baseline and fallback, model as the production ranker."

6.3 Precompute versus on-demand merge

This is the push-versus-pull fan-out decision from the trade-offs chapter, applied to a ranked feed.

Precompute vs On-Demand vs Hybrid
Comparison

Precompute (push)

fan-out on write

  1. 1

    Author posts

    event reaches the publisher

  2. 2

    Copy ID to each follower

    100 inserts for a normal user

  3. 3

    Reader loads own list

    one cache read

  • Fast, cheap reads
  • Predictable latency
  • A 5M-follower post means 5M writes
  • Wasted work for inactive users

Great for normal accounts

On-demand (pull)

merge on read

  1. 1

    Reader opens feed

    list sources

  2. 2

    Fetch recent posts of each

    200+ lookups

  3. 3

    Merge and rank

    every single load

  • No write amplification
  • Always the freshest data
  • Slow reads, p99 at risk
  • Load multiplied by 150K req/s

Fine for few huge sources

Hybrid

push small, pull big

  1. 1

    Push if followers < 10K

    into feed cache

  2. 2

    Skip big pages and groups

    kept in a recent-posts cache

  3. 3

    Read merges both

    ~500 candidates, then rank

  • Bounded writes
  • Reads stay fast
  • Two code paths to operate
  • Threshold needs tuning

Recommended

Key point. Use precompute for the many small authors and on-demand for the few huge ones.

The choice is when to do the work of collecting each viewer's candidates.

Hybrid rule. Authors with fewer than about 10,000 followers are fanned out on write. Big pages and large groups are not: their posts are pulled and merged at read time. The threshold keeps fan-out writes bounded: a 5-million-follower post would otherwise cost 5 million cache writes and delay everything queued behind it.

Because the ranker re-scores candidates on every session anyway, pulling a few big sources adds only a few cache reads, not a new ranking path.

6.4 Pagination with cursors and stable ordering

Offset pagination (?page=3) breaks in a ranked feed: scores change and new posts arrive, so items shift between requests, causing duplicates and gaps.

Our approach, a feed session snapshot:

  1. Page 1 triggers ranking. The top 200 post IDs are saved in feed_sessions in the order they were ranked, with a 15-minute TTL.
  2. The cursor is an opaque, signed token holding session_id and position.
  3. Page 2 reads positions 20 to 39 from the saved list. No re-ranking happens, so ordering cannot change between pages.
  4. Ties are broken by (score desc, post_id desc), so equal scores still have one fixed order.
  5. If the session expired or the user scrolls beyond 200, the server returns 410 (or a fresh session) and the client restarts, excluding items in the "seen" set.

New posts arriving during scrolling do not appear in the middle; they raise the "N new posts" banner, and pulling to refresh starts a new session. Sign the cursor so clients cannot tamper with it.

Interview discussion. Say: "A ranked feed has no natural stable sort key, so I freeze the ranking per session. The cursor points into the frozen list. Fresh content comes in on refresh."

6.5 Privacy checks

Privacy must be enforced on every read, not only at write time, because relationships change after posts are fanned out.

  • At write time (publisher): skip viewers who are blocked or outside the audience. This saves work but is only an optimization.
  • At read time (feed service): after ranking and before returning, check each candidate for the viewer: blocked author, audience (public, friends, group membership), deleted or hidden status. Fetch post audience with hydration, and check blocks and memberships from a cached social-graph lookup.
  • Over-fetch: rank 200 and filter, so removing a few posts still leaves enough for 20 per page.
  • Fail closed: if the privacy service times out, drop the uncertain post rather than show it.

Interview tip. A common mistake is "we checked privacy when fanning out, so we are done". If a user blocks someone a minute later, the old feed entries still exist. The read-time check is what makes unfriend and block effective immediately.

6.6 Ads insertion (high level)

An ad service is separate from organic ranking. It receives the viewer context (coarse interests, location, device) and returns a few ads from an auction, each with a bid-adjusted score.

  • The feed service asks for ads in parallel with ranking, with a strict budget of about 50 ms.
  • Ads are placed by rules, for example after position 3 and then every 5 posts, and always labelled as sponsored.
  • Ads are never stored in the cached feed list; they are added per response so budgets, frequency caps and targeting stay current.
  • If the ad service is slow or down, return the page without ads. Losing revenue for a minute beats a slow feed.
  • Ad impressions use a signed impression_token so billing events cannot be forged.

6.7 Feed freshness versus cost

Every freshness improvement costs money, so tune the knobs deliberately.

  • Fan-out latency: stream plus publisher gives seconds of delay. Cutting it to near zero would need more partitions and consumers.
  • Session lifetime: 15 minutes saves ranking compute (page 2, 3, 4 are cheap) but shows slightly stale scores.
  • Feature freshness: hourly batch affinity, near-real-time counters. Real-time everything is costly with small gain.
  • Cache coverage: only daily users are precomputed; others are built on demand at higher latency.
  • New-post banner: a 60-second poll of new-count gives a feeling of freshness at tiny cost.

6.8 Activity events stream

Every impression, like, comment, hide and dwell time is an event. The client batches them (for example every 10 seconds) and sends one POST /v1/events. The server validates and appends to a partitioned message queue, keyed by user_id, so one user's events stay in order. Consumers then:

  • update post counters (likes, comments) used by engagement_boost,
  • update affinity features,
  • feed the data lake for model training and analytics,
  • feed the "seen" set so already viewed posts are not repeated.

If the queue lags, the feed keeps working with slightly stale features. That is why events are asynchronous.

Step 7: Bottlenecks and Failure Handling

Bottlenecks

  • Celebrity fan-out. Cause: a huge follower count. Mitigation: hybrid rule, pull for big sources.
  • Ranking CPU. Cause: 150,000 peak requests times 500 candidates. Mitigation: two-stage funnel, session snapshots (pages 2+ skip ranking), autoscale by CPU.
  • Hot feature keys. Cause: a viral post's counter read by millions. Mitigation: a few seconds of local caching of counters inside the ranking service.
  • Feed cache memory. Cause: 4 TB of lists. Mitigation: cap length, cache only active users, evict least recently used lists.
  • Event stream lag. Cause: a million events per second. Mitigation: scale consumers by lag, drop low-value events first (for example dwell-time pings) under pressure.
  • Thundering herd after a feed-cache outage. Many cold rebuilds at once. Mitigation: request coalescing (one rebuild per user at a time) and a rate limit on backfill.

Failures and graceful degradation

Graceful degradation means losing quality in steps instead of failing outright. Each step has a fallback:

Degrading in Steps Instead of Failing
Comparison

Level 0: Ranked

everything healthy

  1. 1

    Candidates from cache

    plus big sources

  2. 2

    Features + score

    formula then ML

  3. 3

    Privacy filter and ads

    page with cursor

  • Best engagement
  • Most dependencies to fail

Default

Level 1: Chronological

ranker or features down

  1. 1

    Skip ranking

    after a timeout

  2. 2

    Sort cached IDs by ts

    newest first

  3. 3

    Privacy filter, no ads

    ranking: chronological

  • Fast, fresh, simple
  • Less relevant order

First fallback

Level 2: Pull merge

feed cache down or cold

  1. 1

    List top 100 friends

    from edges

  2. 2

    Fetch their latest posts

    5 each, rate limited

  3. 3

    Merge by time, filter

    coalesce rebuilds

  • Works with only stores
  • Slower, heavier on stores

Last resort before 503

Key point. A chronological feed with a few missing features is far better than an error page.

Each level trades quality for availability; the client is told which level it got.

  • Feature store or ranker down: serve the chronological feed from the feed cache (newest first). Mark ranking: "chronological". Users still get fresh content.
  • Feed cache down or cold: rebuild by pulling the latest posts of the viewer's top 100 friends and merging by time. Slower, so lower the per-friend post limit.
  • Post store slow: serve from the saved feed session or a per-post cache; show fewer posts rather than none.
  • Ad service down: no ads.
  • Privacy service down: fail closed, drop uncertain posts, alert immediately.
  • Event stream down: the client keeps its batch and retries; the feed is unaffected.
  • Availability zone fails: every tier runs in two or three zones; the load balancer drops the dead one.

Protect the fallback with timeouts and a latency budget: of 500 ms, about 50 ms for candidates, 100 ms ranking, 80 ms hydration and privacy, 50 ms ads (parallel), the rest for network. If ranking exceeds its budget, the feed service stops waiting and uses the chronological order.

What to monitor: feed p99 latency, share of requests served degraded, fan-out lag (post time to feed appearance), ranker p99, cache hit rate, event-stream lag, privacy-check timeouts, and engagement per session (a drop signals a bad ranking release).

Interview tip. Pick two failures, say what the user sees and what you monitor. "Ranker down means chronological feed with a metric on degraded share" is a strong sentence.

Step 8: Final Design Walkthrough

Final Design
Architecture
Write pathRead pathClientGateway + LBauth, rate limitPost servicePost storesharded, replicasFeed serviceorchestratesAd service50 ms budgetEvent streamposts + engagementRanking serviceformula + MLFeed publisherfan-out workersFeed cacheIDs + sessionsFeature storeaffinity, countershydrateadscandidatesfeatures

Solid arrows are synchronous requests. The event stream carries posts and engagement asynchronously.

Request flow

Read: client, gateway, feed service, candidates from the feed cache (plus pulled big sources), ranking service scores with features, feed service saves the session, hydrates posts from the post store, filters by privacy, adds ads, returns 20 items and a cursor. Page 2: cursor, saved session, hydrate, privacy, ads, no re-ranking. Publish: client, gateway, post service, post store, event stream, response.

Data flow

Posts live in the post store (source of truth). Friend-post IDs live in the feed cache for active users. Frozen ranked lists live in feed sessions. Affinity and counters live in the feature store. Impressions and engagement flow client, gateway, event stream, consumers.

Background processing

The feed publisher fans out new posts. Consumers update counters and "seen" sets. Batch jobs recompute affinity and train ranking models. A cleanup job removes deleted posts from caches and trims lists to 500.

Critical design decisions

  1. Rank in two stages, cheap formula on about 500 candidates then a model on about 100, because ranking CPU is the main cost.
  2. Store IDs only in the feed cache, so memory stays near 4 TB and edits or deletes do not rewrite lists.
  3. Hybrid fan-out: push for normal authors, pull for big pages and groups, to cap write amplification.
  4. Frozen sessions and signed cursors for stable, duplicate-free pagination.
  5. Privacy at read time, failing closed, because relationships change after fan-out.
  6. Degrade in steps, ranked, chronological, pull merge, so the feed almost never errors.

If time remains, discuss multi-region: replicate the post store and social graph to every region, keep feed caches regional, and let each region build feeds from the global event stream.

Common Interview Questions

Chapter quiz

Social and Messaging Designs · 6 questions

  1. 1.With 500M daily users and 20% connected at peak, roughly how many WebSocket gateways are needed at 100K connections each (before headroom)?

  2. 2.What is the purpose of the session registry?

  3. 3.Why does the client upload photos directly to object storage with a pre-signed URL?

  4. 4.Why does the design push tweet IDs into followers' timelines at write time?

  5. 5.Why does the feed cache store only post IDs rather than full posts?

  6. 6.A page with 5 million followers publishes a post. What does the hybrid design do?

0 of 6 answered

Finished this lesson?

0 of 44 lessons done · 0% of the course