Case study: design a news feed
A senior-level walkthrough of a social feed: estimates that expose the fan-out problem, push versus pull versus hybrid with a cost rule, a merge that paginates without repeats, ranking with a fallback, and fan-out lag as a queue.
Case studyApplied37 min readUpdated
- 1 architecture diagram
- 2 sequence flows
- 4 data models
- 2 API designs
- 10 code samples
- 8 interviewer follow-ups
- 2 decision checkpoints
- 1 capacity calculator
- 3 self-checks
On this page17 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Caching, Replication and sharding, Queues and asynchronous work, Latency, throughput and queues
- Run the full framework on a read-heavy social product, with numbers that expose the fan-out problem.
- Choose between push, pull and hybrid with a cost rule and a burst rule, not a follower count.
- Design the timeline store and a merge that paginates without repeats, gaps or deleted posts.
- Size the fan-out workers with Little's Law and explain what a single huge job does to a shared queue.
- Answer the senior follow-ups: celebrities, deletes and blocks, ranking, freshness, multi-region and cost.
9 code samples (366 lines), collapsed so the explanation stays in focus.
A news feed answers one question, for hundreds of millions of people, many times a day: what should this person see now? It is one of the most reused designs in interviews because every social product has one, and because it hides a trap. The obvious design works at small scale and falls over at the first account with millions of followers. This lesson builds the version that survives: the high-level design (HLD) first, then the low-level design (LLD) with tested C#, then the follow-ups a senior round uses to push.
It leans on the caching and queues lessons, and on the performance section: Little's Law and queueing size the fan-out pool, and tail latency explains why a page that waits on many lists is slow.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| Newest first, ranked, or both? | Newest first is a merge of sorted lists. A ranked feed adds a scoring stage, a latency budget and a fallback. Build the simple feed first, then add ranking on top |
| Is the follow graph one-way (follow) or mutual (friends)? Is there a cap? | One-way graphs produce accounts with millions of followers, which is the whole fan-out problem. Mutual graphs with a cap of a few thousand friends are far kinder |
| How soon must a post reach followers, and the author? | "Visible to most followers within five seconds" sets the fan-out capacity. The author must always see their own post at once |
| Text only, or media? Edits and deletes? | Media lives in object storage behind a CDN and the feed carries references. A delete must apply to every timeline immediately |
| Privacy: blocks, mutes, private accounts? | Decides what is checked at read time instead of baked into stored timelines |
| Scale: daily users, posts per day, followers per account, average and maximum? | The maximum matters more than the average |
| What about people who have not opened the app for weeks? | Whether you precompute timelines for everyone or only for active users |
Functional: publish a post, follow and unfollow, read a feed in pages that continue where the last one stopped, see your own post immediately, hide deleted and blocked content. Non-functional: feed page in a few hundred milliseconds at p99, new posts visible to most followers within seconds, no repeated or skipped posts while scrolling, high availability for reads (a stale feed beats an error), and cost that does not grow with the follower count of the biggest account. Out of scope: the recommendation models themselves, ads, and notifications (a separate pipeline with the same burst problem, designed in the notification service case study).
State assumptions out loud; they are illustrative and the interviewer may change them. The goal is to find where the cost sits.
people: 300M daily users, each opens the feed 10 times a day
feed reads: 300M x 10 / 86,400 s = ~35,000 pages/s, ~100,000 at peak (x3)
posts: 100M a day / 86,400 s = ~1,200/s, ~3,500/s at peak
followers: 200 on average; a few accounts have tens of millions
fan-out: 1,200 posts/s x 200 followers = ~240,000 inserts/s
3,500 posts/s x 200 followers = ~700,000 inserts/s at peak
one post: an account with 50M followers = 50M inserts for one post
timeline: 800 post IDs x 16 B = ~13 KB per user
x 300M users = ~3.8 TB, twice that with a replicaChange the assumptions yourself: the estimator starts from this estimate (a post is about 1 KB, a feed page about 20 KB). The calculator counts posts and pages; for fan-out, multiply the write rate by the followers per account, which is the number that makes this design hard.
Try it · capacity estimatorFeed posts and pages
Four conclusions:
- Reads are modest (100,000 pages a second at peak), but precomputing multiplies the writes: 240,000 timeline inserts a second is about seven for every page read. That ratio is the price of fast reads, and it is only worth paying for followers who will actually look.
- The worst case is not the average. One post from one account is 50 million inserts, more than the whole fleet does in a minute at the average rate. Averages hide the problem; the maximum is the design.
- Memory, not throughput, sets the size of the timeline cache: about 4 TB of post IDs, so tens of shards of tens of gigabytes each. Keep timelines only for people who were active recently, and rebuild the rest on return.
- Fan-out must be asynchronous. A post returns as soon as it is stored; followers' timelines catch up in the background, and the lag is a number you watch.
The feed endpoint takes a cursor, never a page number. The reason is in the pagination section below, and it is a favourite follow-up (the API design lesson measures the drift of offset pagination).
- auth
- bearer token
- idempotency
- Idempotency-Key header, the same key returns the same post
- body
- { "text": "…", "media_ids": ["…"] }
- 201created, returns { "id": "1790234871234567168" }
- 429posting rate limit exceeded
- auth
- bearer token
- query
- cursor (opaque, from the previous response), limit (default 20, maximum 50)
- note
- the cursor encodes the last post examined, so a page continues exactly where the previous one stopped
- 200returns { "posts": [...], "next_cursor": "…", "has_more": true }
Each access pattern gets the store shaped for it. Posts are read by ID in bulk (hydration). A large account's recent posts are read by author. Follow edges are read in both directions. Timelines are read by user, newest first.
idbigint
time-sortable ID, so a bigger ID is a newer post
PKSHARD KEYauthor_idbigint
INDEXbodytext
mediajson
references only; the bytes are in object storage
NULLcreated_attimestamptz
deleted_attimestamptz
a tombstone: the feed filters on it at read time
NULL
Sharded by post id for even load. Hydration is a multi-get of up to a few dozen ids.
author_idbigint
the shard key, so one author's list lives on one node
PKSHARD KEYpost_idbigint
sorted newest first
PK
The source for pulled authors and for the author's own posts. Capped, for example the last 800.
follower_idbigint
"who do I follow", used to rebuild a timeline
PKSHARD KEYfollowee_idbigint
PKcreated_attimestamptz
The reverse copy, keyed by followee, answers "who follows this author" for fan-out workers.
user_idbigint
PKSHARD KEYpost_idslist
newest first, capped at 800, ids only; bodies are fetched at read time
Idempotent insert (sorted-set semantics): adding the same id twice changes nothing.
The timeline holds IDs only. It is small, an edit or a delete needs no timeline update, and the one place that decides whether a post is still visible is the read path.
A cursor that is one number needs IDs that order by time, so "older than this ID" means "older than this post". The standard shape is a Snowflake-style ID: milliseconds in the high bits, then a worker number, then a sequence. It gives you uniqueness without coordination and time order without a timestamp column.
C# · SnowflakeIds
using System;
public sealed class SnowflakeIds
{
// 41 bits of milliseconds | 10 bits of worker | 12 bits of sequence: 4,096 IDs per worker per millisecond.
private const int WorkerBits = 10, SequenceBits = 12;
private const long SequenceMask = (1L << SequenceBits) - 1;
private readonly long _worker;
private readonly Func<long> _nowMs; // injected, so a test controls the clock
private readonly object _gate = new object();
private long _lastMs = -1, _sequence;
public SnowflakeIds(int worker, Func<long> nowMs)
{
if (worker < 0 || worker >= (1 << WorkerBits)) throw new ArgumentOutOfRangeException(nameof(worker));
_worker = worker;
_nowMs = nowMs;
}
public static long MillisecondsOf(long id) => id >> (WorkerBits + SequenceBits);
public long Next()
{
lock (_gate)
{
long ms = Math.Max(_nowMs(), _lastMs); // a clock that steps backwards must not make smaller IDs
if (ms == _lastMs)
{
_sequence = (_sequence + 1) & SequenceMask;
if (_sequence == 0) ms++; // 4,096 used in this millisecond: borrow the next one
}
else _sequence = 0;
_lastMs = ms;
return (ms << (WorkerBits + SequenceBits)) | (_worker << SequenceBits) | _sequence;
}
}
}C#
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
long clockMs = 1_000;
var workerA = new SnowflakeIds(worker: 1, nowMs: () => clockMs);
var workerB = new SnowflakeIds(worker: 2, nowMs: () => clockMs);
var seen = new HashSet<long>();
long previousId = -1;
bool rising = true;
for (int i = 0; i < 5_000; i++) // more than 4,096 IDs inside one millisecond
{
long id = workerA.Next();
rising &= id > previousId;
previousId = id;
seen.Add(id);
}
for (int i = 0; i < 100; i++) seen.Add(workerB.Next());
Debug.Assert(rising, "IDs from one worker rise strictly, even when a millisecond runs out of sequence numbers");
Debug.Assert(seen.Count == 5_100, "two workers never produce the same ID");
clockMs = 900; // the clock steps back by 100 ms
long afterStepBack = workerA.Next();
Debug.Assert(afterStepBack > previousId, "a clock that steps back cannot make an older ID");
clockMs = 5_000;
long later = workerB.Next();
Debug.Assert(later > afterStepBack, "a later millisecond sorts after every earlier ID, whichever worker made it");
Debug.Assert(SnowflakeIds.MillisecondsOf(later) == 5_000, "the creation time is in the high bits");Two details a senior round likes. A clock that steps backwards (an NTP correction) must not produce an older ID, so the generator never goes below its last millisecond. And IDs are roughly time ordered across workers, not exactly: two workers' clocks differ by a few milliseconds, which is fine for a feed and wrong for anything that needs strict ordering.
Read it as two paths that meet in the timeline. The write path stores the post, returns, and enqueues a fan-out job. Workers read the author's followers from the graph store and add the post ID to each follower's timeline. The read path reads the viewer's timeline, merges the lists of any large accounts they follow (pulled at read time), drops hidden posts, fetches the bodies, ranks, and returns a page with a cursor.
There are three ways to build the answer, and the interview is mostly about choosing among them with a reason. Before the table, commit to one.
Decision checkpoint · pick one
Your fan-out writes just hit 50,000 inserts a second because accounts with tens of millions of followers are posting. Reads are modest and a post should reach followers within seconds. Which design do you pick?
Commit to an answer first. The reasoning for every option appears after you pick.
| Strategy | Write cost | Read cost | Freshness | Weakness |
|---|---|---|---|---|
| Fan-out on write (push) | One insert per active follower | One timeline read | Seconds, set by queue lag | A huge account is a huge burst, and most inserts are for people who never look |
| Fan-out on read (pull) | One insert into the author's own list | One lookup per account followed, merged | Immediate | Read cost grows with the number followed, and the page waits on the slowest list |
| Hybrid | Push for most accounts, nothing for the largest and the chattiest | One timeline read plus a few pulled lists | Immediate for pulled, seconds for pushed | Two paths to keep correct, and an explicit rule |
Public descriptions of Twitter's timelines (Krikorian's talk, and the account in Kleppmann's Designing Data-Intensive Applications) describe exactly this path: fan-out on write into cached timelines, then a move to a hybrid where accounts with very many followers are fetched at read time and merged in. The useful question is not "what did they do" but "what rule picks the author?"
A cost rule, and a burst rule. Count per active follower per day. Pushing an author's posts costs PostsPerDay × InsertCost. Pulling costs ReadsPerDay × LookupCost, because every time that follower opens the feed, the author's list is consulted. The follower count is on both sides and cancels out. So push wins when an author posts less often, in cost terms, than followers read. That is the surprising result: a small news bot that posts every five minutes should be pulled, while a quiet account with 400,000 followers can be pushed. The follower count enters only through the second rule, the burst: one post must reach every active follower within the freshness target using only a share of the spare fan-out capacity, or the account is pulled.
C# · FanoutMode, Author, FanoutPolicy, …
using System;
public enum FanoutMode { Push, Pull }
public readonly record struct Author(long Id, long Followers, double ActiveShare, double PostsPerDay);
public sealed class FanoutPolicy
{
public double ReadsPerActiveFollowerPerDay; // how often an active follower opens the feed
public double InsertCost; // cost of adding one id to one timeline (relative units)
public double LookupCost; // cost of reading one author's cached recent posts
public double SpareInsertsPerSecond; // fan-out capacity left after the ordinary load
public double FreshnessSeconds; // how soon a post must be visible
public double MaxShareOfSpare; // the most of that capacity one post may take
public (FanoutMode Mode, string Reason) Decide(Author a)
{
// Cost rule: the follower count appears on both sides, so compare the per-follower cost.
if (a.PostsPerDay * InsertCost > ReadsPerActiveFollowerPerDay * LookupCost)
return (FanoutMode.Pull, "posts more often than followers read");
// Burst rule: every active follower must be reached inside the freshness target, using a bounded share of the spare capacity.
double burstBudget = SpareInsertsPerSecond * FreshnessSeconds * MaxShareOfSpare;
if (a.Followers * a.ActiveShare > burstBudget)
return (FanoutMode.Pull, "one post is too big a burst");
return (FanoutMode.Push, "cheaper to precompute, and the burst fits");
}
}
public static class FollowerModel
{
/// <summary>A heavy tail in its simplest form: the account at popularity rank r has top / r followers.</summary>
public static double Followers(int rank, double top) => Math.Max(1.0, top / rank);
}C#
var policy = new FanoutPolicy
{
ReadsPerActiveFollowerPerDay = 10, InsertCost = 50, LookupCost = 20, // relative costs: measure yours
SpareInsertsPerSecond = 260_000, FreshnessSeconds = 5, MaxShareOfSpare = 0.25,
};
var ordinary = policy.Decide(new Author(1, 200, 0.3, 0.33)); // a typical account
var newsBot = policy.Decide(new Author(2, 3_000, 0.3, 288)); // posts every five minutes
var bigAccount = policy.Decide(new Author(3, 400_000, 0.3, 2)); // 120,000 active followers
var celebrity = policy.Decide(new Author(4, 40_000_000, 0.3, 3)); // 12 million active followers
Debug.Assert(ordinary.Mode == FanoutMode.Push);
Debug.Assert(newsBot.Mode == FanoutMode.Pull && newsBot.Reason.StartsWith("posts more often"), "a small account can still be a pull account");
Debug.Assert(bigAccount.Mode == FanoutMode.Push, "a large account that posts rarely can still be pushed");
Debug.Assert(celebrity.Mode == FanoutMode.Pull && celebrity.Reason.StartsWith("one post"), "the burst rule catches the celebrity");
// How much of the push work do the biggest accounts create? A world of a million accounts; the account at rank r has 500,000 / r followers.
const int worldSize = 1_000_000;
double worldEdges = 0;
for (int rank = 1; rank <= worldSize; rank++) worldEdges += FollowerModel.Followers(rank, 500_000);
double[] expectedShare = { 0.353, 0.509, 0.666 };
int cutoffIndex = 0;
foreach (int topAccounts in new[] { 100, 1_000, 10_000 })
{
double inTop = 0;
for (int rank = 1; rank <= topAccounts; rank++) inTop += FollowerModel.Followers(rank, 500_000);
double share = inTop / worldEdges; // share of all push work if every account posts equally often
double pulledStreamsPerReader = inTop / worldSize; // extra lists each reader merges, on average
double largestRemainingBurst = FollowerModel.Followers(topAccounts + 1, 500_000);
Debug.Assert(Math.Abs(share - expectedShare[cutoffIndex++]) < 0.002, "the top accounts produce a third to two thirds of the push work");
Debug.Assert(pulledStreamsPerReader < 5.0 && largestRemainingBurst <= 5_000, "while the reader merges a few lists and the biggest burst collapses");
}In that toy world (a Zipf distribution, the simplest heavy tail, with every account posting equally often), the top 100 accounts, 0.01 percent of the world, produce 35 percent of all push work; the top 1,000 produce 51 percent; the top 10,000 produce 67 percent. Pulling them costs each reader a few extra lists to merge (2.6, 3.7 and 4.9 on average), and the largest remaining burst falls from 500,000 inserts to 4,950, 500 and 50. Real follower counts are not exactly Zipf, but they are heavy-tailed in the same way, which is why the maximum, not the average, drives the design. Measure your own distribution.
Details that make the hybrid work:
- Skip dormant users. Push only to followers who were active in the last week or so. Anyone else rebuilds a timeline when they return, by pulling their followees' recent posts, capped (the last day, at most 800 entries) and rate limited so a morning of returning users cannot flatten the post store.
- Follows and unfollows. On a follow, backfill the followee's last few posts into the follower's timeline. On an unfollow, do not rewrite the timeline: filter by the current follow set when reading, and let old entries fall off the end.
- Changing an author's mode needs no cleanup. Timelines keep their old entries, the reader merges both sources, and the merge drops duplicates by ID. Add hysteresis (switch to pull above one threshold, back to push only well below it) so an account near the line does not flap.
- Cap the pulled streams. A viewer who follows thousands of large accounts cannot merge thousands of lists per page. Merge the most recently active few dozen, and let the rest arrive through the pushed path or on a refresh.
Fan-out is a queueing system, so the performance lessons apply directly.
Sizing. At the 700,000 inserts a second peak, if one pipelined worker spends 0.1 ms per insert, Little's Law (L = λW) gives 700,000 × 0.0001 = 70 busy workers. Plan for 60 percent utilization and you need 117. Run the pool hotter and the queue grows faster than the load, the same hockey stick as any service.
Head-of-line blocking. The failure that matters is not a slow average but a single huge job in a shared queue. Suppose capacity is 500,000 inserts a second, ordinary posts need 240,000, and at one moment a 50-million-insert job arrives.
C# · FanoutLanes, Job
using System;
using System.Collections.Generic;
using System.Linq;
public static class FanoutLanes
{
private sealed class Job { public double Arrived, Left; public bool Ordinary; }
/// <summary>Simulates fan-out work in 0.1 second steps. Ordinary posts arrive steadily, and one huge job arrives at `burstAtSecond`.</summary>
public static (double WorstOrdinaryDelay, double BurstDelay) Run(
bool ordinaryFirst, double capacityPerSecond, double ordinaryPerSecond, double burstInserts, int burstAtSecond, int seconds)
{
const double Step = 0.1;
var queue = new List<Job>(); // in arrival order
double worst = 0, burstDelay = double.NaN;
for (int tick = 0; tick < seconds * 10; tick++)
{
double now = tick * Step;
if (tick == burstAtSecond * 10) queue.Add(new Job { Arrived = now, Left = burstInserts });
queue.Add(new Job { Arrived = now, Left = ordinaryPerSecond * Step, Ordinary = true });
double budget = capacityPerSecond * Step;
var order = ordinaryFirst ? queue.OrderBy(j => j.Ordinary ? 0 : 1).ToList() : queue.ToList(); // OrderBy is stable
foreach (var job in order)
{
if (budget <= 0) break;
double used = Math.Min(budget, job.Left);
job.Left -= used;
budget -= used;
if (job.Left > 1e-9) continue;
double waited = now + Step - job.Arrived;
if (job.Ordinary) worst = Math.Max(worst, waited); else burstDelay = waited;
}
queue.RemoveAll(j => j.Left <= 1e-9);
}
return (worst, burstDelay);
}
}var oneQueue = FanoutLanes.Run(ordinaryFirst: false, 500_000, 240_000, 50_000_000, burstAtSecond: 10, seconds: 400);
var lanes = FanoutLanes.Run(ordinaryFirst: true, 500_000, 240_000, 50_000_000, burstAtSecond: 10, seconds: 400);
Debug.Assert(oneQueue.WorstOrdinaryDelay > 95 && oneQueue.WorstOrdinaryDelay < 105, "one queue: ordinary posts wait ~100 s behind the burst");
Debug.Assert(lanes.WorstOrdinaryDelay <= 0.2, "ordinary posts first: they wait one step");
Debug.Assert(lanes.BurstDelay > 190 && lanes.BurstDelay < 195, "but the burst gets only the 260,000 a second left over, so it takes ~192 s");
Debug.Assert(Math.Ceiling(700_000 * 0.0001 / 0.6) == 117, "70 busy workers at 60 percent utilization is 117");With one queue, every ordinary post waits about 100 seconds behind the burst, while the pool is, by any CPU graph, healthy. Serving ordinary posts first fixes them (they wait one step), but the celebrity's own fan-out then takes about 192 seconds on the capacity left over. Both numbers miss a five-second target, which is the real argument for not pushing that account at all.
What the design does about it:
- Chunk every job. One job per 1,000 followers, so nothing occupies a worker for long, a failure retries a chunk and not a post, and a scheduler can interleave jobs.
- Lanes with priority or weighted fair shares. Ordinary posts never queue behind a big job, and no author may take more than a set share of capacity.
- Measure lag as the age of the oldest unprocessed job, per lane. Queue depth means nothing without the rate; age is the freshness the user feels.
- Make inserts idempotent. With at-least-once delivery, a duplicate job adds the same ID to a sorted structure and nothing changes. Order does not matter, because timelines sort by ID.
- Shed in a fixed order when behind. Dormant followers first, then move the largest push accounts to pull. A policy that reads live spare capacity does this automatically, with hysteresis. Remember the pull path needs capacity too, exactly when you are short of it.
Decision checkpoint · pick one
A reader is on page 3 of their feed when five new posts arrive. They tap "next page". How should the server find page 4?
Commit to an answer first. The reasoning for every option appears after you pick.
One page does five things, in order: read the viewer's pushed timeline, read the lists of the large accounts they follow and their own recent posts, merge them by ID, filter what they may not see, then hydrate the survivors with one multi-get. The merge is a k-way merge of lists that are each sorted newest first.
C# · IPostSource, Timeline, FeedPage, …
using System;
using System.Collections.Generic;
public interface IPostSource
{
/// <summary>Post IDs strictly older than the cursor, newest first.</summary>
IEnumerable<long> Before(long cursor);
}
/// <summary>One sorted, capped list of post IDs: a user's pushed timeline, or one author's recent posts.</summary>
public sealed class Timeline : IPostSource
{
private readonly List<long> _newestFirst = new List<long>();
private readonly int _capacity;
public Timeline(int capacity) { _capacity = capacity; }
public int Count => _newestFirst.Count;
/// <summary>Idempotent: adding an ID that is already there changes nothing, so a retried fan-out job is safe.</summary>
public bool Add(long postId)
{
int at = FirstSmallerThan(postId);
if (at > 0 && _newestFirst[at - 1] == postId) return false;
if (at >= _capacity) return false; // older than everything this capped list keeps
_newestFirst.Insert(at, postId);
if (_newestFirst.Count > _capacity) _newestFirst.RemoveAt(_newestFirst.Count - 1);
return true;
}
public IEnumerable<long> Before(long cursor)
{
for (int i = FirstSmallerThan(cursor); i < _newestFirst.Count; i++) yield return _newestFirst[i];
}
// The list is in descending order; this is the index of the first ID below `id`.
private int FirstSmallerThan(long id)
{
int low = 0, high = _newestFirst.Count;
while (low < high)
{
int middle = (low + high) / 2;
if (_newestFirst[middle] >= id) low = middle + 1; else high = middle;
}
return low;
}
}
public readonly record struct FeedPage(IReadOnlyList<long> PostIds, long NextCursor, bool HasMore);
public static class FeedReader
{
public const long Start = long.MaxValue; // the cursor of the first page: newer than anything
/// <summary>
/// Merges newest-first sources, drops duplicates and posts the viewer may not see, and returns up to `limit` visible IDs.
/// The next cursor is the last ID examined, hidden or not, so a page never repeats and never skips.
/// </summary>
public static FeedPage NextPage(IReadOnlyList<IPostSource> sources, long cursor, int limit, Func<long, bool> visible)
{
var heads = new List<IEnumerator<long>>();
var newestHead = new PriorityQueue<int, long>(Comparer<long>.Create((a, b) => b.CompareTo(a)));
var page = new List<long>();
long last = cursor;
try
{
for (int i = 0; i < sources.Count; i++)
{
var source = sources[i].Before(cursor).GetEnumerator();
heads.Add(source);
if (source.MoveNext()) newestHead.Enqueue(i, source.Current);
}
while (page.Count < limit && newestHead.TryDequeue(out int from, out long id))
{
if (heads[from].MoveNext()) newestHead.Enqueue(from, heads[from].Current);
if (id == last) continue; // the same post arrived from two sources
last = id;
if (visible(id)) page.Add(id);
}
return new FeedPage(page, last, newestHead.Count > 0);
}
finally
{
foreach (var head in heads) head.Dispose();
}
}
}The reader asks each source lazily, so a page costs about limit × log k comparisons, however long the lists are. Now the properties that matter.
C# · The viewer's pushed timeline holds the ordinary authors' posts; one large account (every…
// The viewer's pushed timeline holds the ordinary authors' posts; one large account (every third post) is pulled from its own list.
var pushed = new Timeline(capacity: 800);
var largeAccount = new Timeline(capacity: 800);
for (long post = 1; post <= 100; post++) (post % 3 == 0 ? largeAccount : pushed).Add(post);
bool retried = pushed.Add(50); // a retried fan-out job
pushed.Add(99); // this post reached both sources, for example just after a mode change
Debug.Assert(!retried, "adding an ID twice changes nothing");
var sources = new IPostSource[] { pushed, largeAccount };
Func<long, bool> everything = id => true;
var scrolled = new List<long>();
long position = FeedReader.Start;
int pageCount = 0;
bool more = true;
while (more)
{
var page = FeedReader.NextPage(sources, position, 10, everything);
scrolled.AddRange(page.PostIds);
position = page.NextCursor;
more = page.HasMore;
pageCount++;
}
Debug.Assert(pageCount == 10 && scrolled.Count == 100, "all 100 posts in ten pages");
Debug.Assert(scrolled.SequenceEqual(Enumerable.Range(1, 100).Select(i => (long)(101 - i))), "each post once, newest first, with the duplicate dropped");
// A new post arrives between page 1 and page 2.
var firstPage = FeedReader.NextPage(sources, FeedReader.Start, 10, everything); // 100 down to 91
pushed.Add(101);
var byCursor = FeedReader.NextPage(sources, firstPage.NextCursor, 10, everything); // continues after 91
var byOffset = FeedReader.NextPage(sources, FeedReader.Start, 20, everything).PostIds.Skip(10).ToList(); // "page 2" by position
Debug.Assert(byCursor.PostIds[0] == 90, "the cursor continues exactly where page 1 stopped");
Debug.Assert(byOffset[0] == 91, "an offset shifts when a post arrives, so 91 would be shown twice");
// Hidden posts: one is deleted, and every fifth post belongs to a blocked author. Pages stay full and the cursor steps over them.
var deleted = new HashSet<long> { 85 };
Func<long, bool> visible = id => !deleted.Contains(id) && id % 5 != 4;
var filtered = new List<long>();
position = FeedReader.Start;
more = true;
bool everyPageFull = true;
while (more)
{
var page = FeedReader.NextPage(sources, position, 10, visible);
more = page.HasMore;
if (more) everyPageFull &= page.PostIds.Count == 10;
filtered.AddRange(page.PostIds);
position = page.NextCursor;
}
Debug.Assert(everyPageFull, "hidden posts do not leave short pages behind");
Debug.Assert(!filtered.Contains(85) && filtered.All(id => id % 5 != 4), "deleted and blocked posts never appear");
Debug.Assert(filtered.Count == 80 && filtered.Distinct().Count() == 80, "and everything else appears exactly once");Three decisions are worth saying aloud.
- Cursor, not offset. An offset is a position in a list that changes while the person scrolls. The demonstration above is the bug: with a new post at the top, "page 2 by position" starts at 91, which page 1 already showed. A cursor is "older than this post", which new arrivals cannot move.
- IDs, not timestamps. Two posts can share a millisecond and clocks disagree across servers. A time-sortable ID is unique, so "older than this ID" is a precise cut.
- The cursor is the last post examined, not the last returned. Hidden posts are stepped over, so a run of deleted posts cannot stall pagination or return an empty page that looks like the end.
When the cursor passes the oldest ID a capped timeline still holds, the reader has run off the end of the cache. The feed service then takes the slow path: rebuild the older part by pulling followees' recent posts from the store. That path must be rate limited, because it is also what a returning dormant user triggers.
Hydration and tail latency. After the merge, one multi-get fetches the bodies and authors, mostly from cache. A page waits on its slowest dependency, so give each call a deadline, omit a post whose body failed to load instead of failing the page, and hedge the slow stragglers as in the tail latency lesson. An illustrative budget for a 300 ms p99: timeline and pulled lists in parallel (about 20 ms), hydration (about 40 ms), ranking (about 50 ms, with a hard deadline), the rest for the network and serialization.
A ranked feed is a funnel. The timeline and the pulled lists provide candidates (hundreds). A cheap stage prunes them; a heavier model scores the survivors using features such as the viewer's affinity for the author, the post's age and early engagement; and a final stage applies policy: diversity, demoting content that violates rules, mixing in ads and recommendations from accounts the viewer does not follow. Twitter's 2023 description of its open-sourced algorithm has this shape: candidate sourcing, ranking, then filters and mixing.
The design points are mostly about the system around the model:
- Cache candidates, not the ranked page. A re-rank is then cheap, and an experiment can change the ranker without invalidating storage.
- The ranker is optional. It has a deadline, and when it is slow or down the feed falls back to newest first. Degrading is better than failing.
- Features must be available in milliseconds, so they come from a feature store or from counters kept up to date by a stream, not from queries at request time.
- Log what was shown (impressions, with the model version) so the next model can be trained and a regression found.
C# · Candidate, FeedRanker
using System;
using System.Collections.Generic;
using System.Linq;
public readonly record struct Candidate(long PostId, long AuthorId, double AgeHours, double Engagement);
public static class FeedRanker
{
/// <summary>Engagement fades with age: the score halves every `halfLifeHours`.</summary>
public static double Score(Candidate c, double halfLifeHours) => c.Engagement * Math.Pow(0.5, c.AgeHours / halfLifeHours);
/// <summary>Greedy re-rank: the best remaining candidate wins, but every earlier pick by the same author discounts the next one.</summary>
public static List<Candidate> Rank(IReadOnlyList<Candidate> candidates, int take, double halfLifeHours, double authorDiscount)
{
var remaining = candidates.ToList();
var picked = new List<Candidate>();
var perAuthor = new Dictionary<long, int>();
while (picked.Count < take && remaining.Count > 0)
{
var best = remaining
.OrderByDescending(c => Score(c, halfLifeHours) * Math.Pow(authorDiscount, perAuthor.GetValueOrDefault(c.AuthorId)))
.ThenByDescending(c => c.PostId)
.First();
remaining.Remove(best);
picked.Add(best);
perAuthor[best.AuthorId] = perAuthor.GetValueOrDefault(best.AuthorId) + 1;
}
return picked;
}
/// <summary>Degrade, never fail: if the ranker throws (in production, or runs past its deadline), serve newest first.</summary>
public static IReadOnlyList<Candidate> RankOrFallback(
IReadOnlyList<Candidate> candidates, int take, Func<IReadOnlyList<Candidate>, int, IReadOnlyList<Candidate>> ranker)
{
try { return ranker(candidates, take); }
catch (Exception) { return candidates.OrderByDescending(c => c.PostId).Take(take).ToList(); }
}
}C#
var pool = new[]
{
new Candidate(PostId: 5, AuthorId: 1, AgeHours: 1, Engagement: 10),
new Candidate(4, 1, 2, 9),
new Candidate(3, 1, 3, 8),
new Candidate(2, 2, 12, 6),
new Candidate(1, 3, 0.5, 1),
};
var plain = FeedRanker.Rank(pool, 3, halfLifeHours: 6, authorDiscount: 1.0).Select(c => c.PostId).ToArray();
var varied = FeedRanker.Rank(pool, 3, halfLifeHours: 6, authorDiscount: 0.5).Select(c => c.PostId).ToArray();
Debug.Assert(plain.SequenceEqual(new long[] { 5, 4, 3 }), "without a discount one author fills the top three");
Debug.Assert(varied.SequenceEqual(new long[] { 5, 4, 2 }), "with a discount a second author gets a place");
var stale = new Candidate(10, 1, AgeHours: 48, Engagement: 100); // 100 x 0.5^8 = 0.39
var fresh = new Candidate(11, 2, AgeHours: 0, Engagement: 1);
Debug.Assert(FeedRanker.Score(fresh, 6) > FeedRanker.Score(stale, 6), "decay beats raw engagement for an old post");
var broken = FeedRanker.RankOrFallback(pool, 3, (c, n) => throw new InvalidOperationException("model server unavailable"));
Debug.Assert(broken.Select(c => c.PostId).SequenceEqual(new long[] { 5, 4, 3 }), "when the ranker fails the feed is still newest first");- Read your own writes. The author's recent posts are one more source in the merge, read from their own list. They see the post at once, even while fan-out is still running.
- Late arrivals are fine. Timelines sort by ID, so a post that lands late slots into the right place. A reader who has already scrolled past that point simply does not see it until a refresh. Say that out loud; it is acceptable.
- Deletes. Set a tombstone on the post. The read path drops tombstoned IDs and the hydration step drops missing bodies, so no timeline needs rewriting. Cached bodies need explicit invalidation, and for legal takedowns the invalidation must be immediate, not a TTL.
- Blocks, mutes and private accounts. Check them at read time against the viewer's small, cached lists. Baking them into stored timelines would mean rewriting millions of lists whenever one person changes a setting.
- Edits. Timelines store IDs, so an edit is a change to the body and a cache invalidation.
| Case | What goes wrong | Response |
|---|---|---|
| Fan-out workers fall behind | Posts reach followers late, and the lag keeps growing if arrivals exceed capacity | Alert on the age of the oldest job; shed dormant followers first, then move the largest push accounts to pull; add workers |
| A timeline cache node is lost | Those users' timelines are gone | Rebuild on demand from followees' recent posts, with a rate limit; replicate if rebuild cost is too high |
| Region failover or cold cache | Everyone rebuilds at once and floods the post store | Concurrency limits on rebuild, request coalescing, a smaller window while warming |
| A hot author's list expires | Millions of readers miss at the same moment | Refresh ahead of expiry with jitter, one in-flight refill per key, replicate hot keys, a one-second in-process copy |
| A follow races a fan-out | A new follower misses a post, or an unfollower still gets one | Backfill on follow; filter by the current follow set at read time |
| Duplicate or reordered fan-out jobs | The same ID twice, or out of order | Idempotent sorted insert; order is irrelevant |
| Ranker slow or down | Slow pages or errors | Deadline and a newest-first fallback |
| A viral post | One post body and one counter get enormous traffic | Replicate hot keys, batch counter writes, approximate counts |
| Deleted or blocked content still visible | A trust and legal problem | Filter at read time against tombstones and block lists; explicit cache invalidation |
| A timeline outgrows its cap | Memory grows without bound | Cap per user, trim on insert, fall back to the slow path past the end |
Interviewer follow-upL5A user follows 5,000 accounts. What changes?How to answer
Their pushed timeline receives far more inserts and is trimmed to the cap sooner, so older posts fall off the end faster. The read path should not merge thousands of pulled lists: cap the pulled streams to the most recently active few dozen and rely on the pushed path for the rest. The fan-out cost this user adds is real, so a follow cap or a smaller timeline for heavy followers is a product decision worth naming.
Interviewer follow-upL5Why a cursor and not page numbers?How to answer
Pages are positions, and the list changes while the person scrolls: a new post at the top shifts every position by one, so a page repeats an item. A cursor is "older than this post", which insertions cannot move. Use a time-sortable ID so the cut is exact, and let the cursor carry the last post examined, not returned, so hidden posts cannot stall it.
Interviewer follow-upL6A celebrity with 50 million followers posts. Walk through the first minute.How to answer
The post is stored and added to the author's own recent list, which is a hot key: replicate it over several cache nodes and keep a one-second copy in each feed server's memory, with refresh ahead and a single refill. There is no per-follower fan-out; each follower's next feed read merges the list. Notifications are a separate pipeline with the same burst, so they are rate limited and spread over minutes, in their own lane. Check the read side too: the pull path adds a lookup per large account followed to every page, and that is where the capacity goes.
Interviewer follow-upL6How do you decide, and then keep deciding, which authors are pushed?How to answer
Use a cost rule and a burst rule, not a follower count. Per active follower, compare the cost of inserting each post with the cost of one lookup per feed open; then require that one post fits the freshness target within a bounded share of spare capacity. Re-evaluate on a schedule with hysteresis, and feed the burst rule live capacity so the system moves the largest accounts to pull under stress. Switching modes needs no cleanup, because the reader merges both and drops duplicates by ID.
Interviewer follow-upL6How do you add a "new posts" banner without hurting the feed?How to answer
Do not insert at the top while the person reads, because it shifts the layout and the cursor. Poll cheaply with the newest ID the client holds (or push a signal over the existing real-time connection) and show a count. Tapping it reloads from the start. The count is approximate on purpose.
Interviewer follow-upL7Run this across regions.How to answer
Keep a user's timeline in their home region and replicate the post stream and the graph to every region. Fan out locally in each region for the followers who live there, so there is no cross-region write per follower. Authors' recent lists are replicated globally, since they are the pulled source. The freshness target becomes replication lag plus local fan-out, and read-your-writes holds because the author's own region serves their own list first. Cross-region failover then starts cold, so the rebuild limits matter.
Interviewer follow-upL7Product wants a "for you" feed, mostly from accounts the viewer does not follow. What changes?How to answer
The candidates no longer come from follow edges. They come from retrieval: embeddings and graph walks that return accounts and posts similar to what the viewer engages with, run as separate candidate sources next to the timeline. The stored timeline still holds in-network posts. Everything after the merge (ranking, filters, mixing) is the same funnel, so the work is retrieval infrastructure, a feature store with low latency, and a stricter latency budget, since retrieval adds calls to every page.
Interviewer follow-upL7Cut the feed's infrastructure cost by a third. Where do you look?How to answer
Measure cost per post and per read by author class first. The usual levers are not pushing to dormant users, tightening the timeline cap, raising the pull threshold only where the read path has spare capacity, serving the candidate set from cache across ranking experiments, and shrinking timeline entries (IDs delta-encoded in blocks). Each has a user-visible cost (rebuild latency, shorter scroll depth, a slower page), so name it with the saving.
- Clarify: ranked or newest first, graph shape and maximum followers, freshness target, deletes and blocks, scale.
- Estimate: show that fan-out multiplies writes seven to one, and that one post from one account is tens of millions of inserts.
- Contract and model: a cursor endpoint, time-sortable IDs, timelines of IDs only, a graph in both directions.
- Draw the two paths: post then queue then workers then timelines; read then merge then filter then hydrate then rank.
- Go deep on the choice: push, pull and hybrid with the cost rule and the burst rule, dormant users, and mode changes.
- Treat fan-out as a queue: Little's Law, chunking, lanes, lag as age.
- Prove the read path: merge, cursor, hidden posts, and the offset bug.
- Name failures and follow-ups: workers behind, cold caches, hot keys, ranker down, regions.
A feed is a precomputed answer, and the design is the decision of when to compute it. Push into cached timelines of post IDs for most authors, pull the largest and chattiest at read time, and decide by a cost rule and a burst rule rather than by a follower count. Treat fan-out as a queue: size it with Little's Law, chunk its jobs, keep ordinary posts in their own lane, and watch lag as the age of the oldest job. Read with a k-way merge over time-sortable IDs and a cursor that stands for the last post examined, filter deleted and blocked posts at read time, and keep the ranker optional with a newest-first fallback.
Try answering out loud before you reveal each answer.
QuestionWhy does the follower count alone not decide whether an author is pushed or pulled?Reveal answer
Because the follower count appears on both sides of the cost comparison and cancels: pushing costs posts per day times the insert cost for each active follower, and pulling costs feed opens per day times the lookup cost for the same follower. An account that posts every five minutes is cheaper to pull however few followers it has. The follower count matters only for the burst rule: whether one post can reach every active follower inside the freshness target using a bounded share of spare capacity.
QuestionA user has scrolled to page 3 while new posts arrive. Why does page-number pagination repeat a post, and what does a cursor do instead?Reveal answer
A new post at the top shifts every position down by one, so "page 3 by position" starts with the last item of page 2. A cursor means "older than this post ID", and IDs sort by time, so insertions at the top cannot change which posts are older than the last one shown. Carrying the last post examined, not the last returned, also keeps hidden posts from stalling the cursor.
QuestionA 50-million-insert fan-out job shares one FIFO queue with ordinary posts. What happens to the ordinary posts, and what are two fixes?Reveal answer
They wait behind the burst, about 100 seconds when capacity is 500,000 inserts a second, even though the pool looks healthy. Fixes: serve ordinary posts in their own higher-priority lane and chunk big jobs so nothing holds a worker long; and the better fix for that account, pull it at read time so there is no per-follower burst at all.
- Raffi Krikorian, Timelines at Scale (opens in a new tab), QCon San Francisco 2012 (InfoQ): how Twitter built home timelines with fan-out on write into a cache of per-user timelines.
- Martin Kleppmann, Designing Data-Intensive Applications, O'Reilly, 2017, chapter 1: the home timeline as a worked example of describing load, and the move to a hybrid for accounts with very many followers.
- Nathan Bronson and others, TAO: Facebook's Distributed Data Store for the Social Graph (opens in a new tab), USENIX ATC 2013: a read-optimised graph store with a cache tier over MySQL, the kind of store the follow graph lives in.
- Twitter, the-algorithm (opens in a new tab), 2023: the open-sourced home timeline pipeline, from candidate sourcing through ranking to filters and mixing.