AlgoViz

Design a news feed like Facebook's

hard 50 min

Show each person the best recent posts from everyone they follow, in a fifth of a second.

Deep dives

Compare the options before you open them, then say which you would pick.

Deep dive 1

Fan-out

A post is written. How does it reach feeds?

BreaksPush to everyone
How
Write the ID into every follower's list, whoever the author is.
Limit
100 million inserts for one post take 100 seconds of a million inserts a second, and all other posts wait behind them.
Choose when
Only when follower counts are limited.
WorksPull for everyone
How
On each read, ask for recent posts of all followed accounts and merge.
Limit
116 million partition reads a second on average, and the slowest of 500 decides the latency.
Choose when
Small products, or people who rarely open the app.
StrongSplit by follower count
How
Push under 10,000 followers, pull above, skip cold feeds, merge at read.
Limit
Two paths. Accounts that cross the limit need care: for a while, their posts may be in both places, so remove duplicates by ID.
Choose when
Follower counts are very uneven, as here.

Two paths, one merge

A post event enters Kafka. Workers read the follow graph and write IDs into ready feeds in Redis for normal accounts. For big accounts the event only updates the list in each feed server's memory. A reader's feed service merges both.

Who gets which path

FollowersOn writeOn read
Up to 10,000Push to every warm feedNothing extra
10,000 to 1 millionPush to followers active in the last day (say 15,000 of 50,000), keep once for the restMerge, drop duplicates
Over 1 millionKeep onceMerge
The middle row is optional: add it if active followers of mid-size accounts must get posts and hints sooner.

How workers behave

  1. 1

    Split

    One post becomes tasks of up to 1,000 recipients, so one task never blocks a worker for long.

  2. 2

    Batch

    Send many inserts in one round trip to each Redis node. A pipeline is not a transaction: if half succeeds, repeat it all. Adding an ID again is harmless.

  3. 3

    Commit after

    Move the Kafka position only after Redis confirms. Retry three times, then park the task and alert.

  4. 4

    Enough partitions

    A partition has one consumer in a group. 694 workers at peak need at least 694 partitions; we take 1,024.

  5. 5

    Slow down safely

    Watch the delay in seconds, not only the backlog. Add workers; skip feeds that are cold; delay large accounts first.

Deep dive 2

What a ready feed holds

What do you store for each person?

BreaksFull posts
How
Copy the 3 KB post into each follower's feed.
Limit
500 × 3 KB × 2.5B is 3.75 PB of memory, and each like changes 500 copies.
Choose when
Never at this size.
WorksIDs with a rank score
How
Sorted set, the score is the predicted interest.
Limit
Interest changes by the minute. Scores written yesterday put stale posts on top, and rewriting them is another fan-out.
Choose when
The rank depends only on slow facts.
StrongIDs with the time, ranked on read
How
The newest 500 IDs are candidates. Ranking happens once for each visit.
Limit
Ranking costs compute on each visit and needs a time limit.
Choose when
Order depends on the viewer and the moment, as here.

Deep dive 3

Ranking in passes

From 500 to 20

Meta's engineering blog describes a similar shape: a light pass to about 500, a main scoring pass, then a contextual pass for diversity.

A score you can explain

score=0.4 affinity+0.3 recency+0.2 engagement+0.1 type\text{score} = 0.4\,\text{affinity} + 0.3\,\text{recency} + 0.2\,\text{engagement} + 0.1\,\text{type}
Weights are examples. A real system predicts each reaction and combines the predictions, with a negative weight for "hide". One simple variety rule: if the author was just shown, multiply by 0.8.

Features

AboutExamplesHow fresh
The viewerInterests, session age, device, connectionDaily batch, plus the last minutes
The postAge, type, likes a minute, author's reach, topicSeconds, from a stream
The pairHow often this viewer reacts to this author and this typeHours
Features are computed ahead, kept in a low-latency store and fetched in one batch. Streaming counts come from stream processing.

When there is little data

CaseShow
New person, no followsA shared popular list for the region and chosen interests, friend suggestions; one cache entry for many people
A few followsThose posts first, then gradually less of the shared list
Back after monthsRebuild the feed, weight the best posts of the gap
New postAuthor's usual response, content type, a small first audience, then wider
Uncertain choicesKeep about 10% of places for exploration, so the model keeps learning

Run models on machines that score many candidates in one batch, cache slow-changing inputs, and release a new model to 5% of people first. The 60 ms limit includes everything: at the limit, newest first is used.

Deep dive 4

Cursor and order

The user asks for page 2. Which posts?

BreaksOffset 20
How
Skip 20, take 20 of the current order.
Limit
Five new posts arrived, so five repeat. A deletion makes one vanish unseen.
Choose when
Lists that never change.
WorksCursor of score and ID
How
Continue below the last score seen.
Limit
Re-ranking moves posts between requests: one can be shown twice, another never.
Choose when
Order is by time or another fixed value.
StrongRank once, keep the order
How
Store 100 IDs for the visit; the cursor is session and position.
Limit
42 GB of sessions, and posts newer than the visit wait for the banner.
Choose when
Order is personal and moving, as here.

Deep dive 5

Privacy and removal

Alice blocks Bob. Bob's post is in Alice's ready feed, and Alice's in Bob's.

BreaksClean the caches
How
Find and remove the IDs, then trust the feed.
Limit
It takes minutes, some tasks fail, and until then the wrong person sees a post.
Choose when
Never as the guarantee.
WorksCheck at fan-out time
How
Only push to people allowed at that moment.
Limit
Permission changes later. Everything already delivered stays visible.
Choose when
As a saving, together with a read check.
StrongCheck every post on every read
How
Load the viewer's follows and blocks once (about 4 KB), the post's audience and status with its header, and drop what does not match.
Limit
A little work on each read, and permission data must itself be fresh: an unfriend updates the store and deletes the cached list before it answers.
Choose when
Always. Cleaning is a background saving.

Post status

StatusWho sees itFeed does
ActiveIts audienceRank normally
RestrictedIts audience, not recommendedLower the score
In reviewThe authorSkip for others
Removed or deletedNobodySkip; background cleaning; hard delete later

Moderation beside the feed

  1. 1

    Before wide delivery

    Automatic checks of text, images and links run in the background, under about 500 ms. Example limits: over 95% sure, remove; 70 to 95%, reduce and send to a person; below, allow and watch.

  2. 2

    After delivery

    Reports, hides and unusual reaction patterns open a review. One report alone should not hide a post, or groups will abuse it: weigh who reports.

  3. 3

    Appeals

    A person sees the post and the model's reason, then upholds, overturns or escalates. An overturned post becomes active and can be ranked again. Outcomes are training data; a bad model version can be switched off and its decisions reversed together.

  4. 4

    Coordinated fakes

    Signals: young accounts, near-duplicate posts, the same accounts reacting together, odd graph shapes. Do not count their reactions; limit reach; remove when confirmed.

Deep dive 6

Hints

How does an open app learn that new posts exist?

BreaksPoll every 30 seconds
How
Each app asks for updates.
Limit
500M / 30 s is 16.7M requests a second, almost all answered "nothing".
Choose when
As a fallback, with longer gaps.
WorksWebSocket with whole posts
How
Send every new post into the open app.
Limit
Two-way connections we do not need, and the server must filter and rank for each push.
Choose when
The product also has chat on the same connection.
StrongServer-sent events with a count
How
One-way stream, grouped for 10 seconds, only while the feed is visible.
Limit
Connection servers and presence. Delivery is at least once; the browser sends the last event ID when it reconnects.
Choose when
One-way, small, tolerant of delay, as here.

Reconnect after 1, 2, 4 and up to 30 seconds with some randomness; after three failures poll every 30 seconds. If a stream server dies, clients reconnect elsewhere and presence corrects itself within 30 seconds. Offline people need nothing: their next read is fresh. Mentions may send a phone notification, see notification service.

Deep dive 7

Keeping caches alive

A miss on a ready feed

One rebuild per user, and a limit on rebuilds in total. Give the lock a time limit longer than a rebuild.

Protections

  • Hot post

    Keep it in each server's memory for a second or two, or under several cache keys.

  • Old is fine

    Serve the last known page while a rebuild runs.

  • Breaker

    When the store is slow, stop asking. Return fewer posts, newest first.

  • Counts

    Likes go to sharded counters and reach the post cache every few seconds.

Edge cases

What can go wrong

CaseProblemAnswer
Own post missingFan-out is not finished when the author refreshesAdd the author's recent posts at read time
Feed jumps while readingNew posts arrive on topBanner, fixed order for the visit
Ranking downNo scoresNewest first, announced to nobody, alerted to us
Graph slowNo follow listFollow list up to a minute old may choose candidates; blocks must be fresh, or the post is left out
Viral normal postHot key and counterIn-process copy, sharded counts, pull beyond active users
Hot partitionOne author's posts on one shardPartition posts by post ID, author index by month
Audience narrowedCopies remain with people who lost accessAudience is read from the post, not the feed entry
Account crosses the limitPost in both pathsRemove duplicates by ID; change path with a gap between raise and lower limits
Follow a new accountFeed has none of its postsPull its last few posts into the feed at once
Store write failsPost not durableReturn an error; never claim success after a queue write alone

Failure drill: say it before you read it

  1. 1

    Half the feed cache is lost

    Replicas take over for single nodes. For the rest, rebuilds are limited: at 20,000 rebuilds a second and 500 reads each, the store sees 10M reads a second, so measure before choosing the limit. Others get the shared list.

  2. 2

    Kafka is behind by ten minutes

    Reads work, posts arrive late. Own posts still show. Add workers, drop tasks for cold feeds, tell nobody to repost.

  3. 3

    Ranking is slow

    The 60 ms limit trips. Newest first, cheaper, so capacity returns. Watch the fallback rate.

  4. 4

    Load is ten times normal

    Shorter pages (20 to 10), longer visit life, no heavy ranking, hints every minute, background refresh off. Each step is tested beforehand.