← Study paths

Feeds and fan-out

Precomputing what users will read, and keeping it right when the source changes.

6 blocks · about 32 min of reading · ends with News Feed

When you finish, you should be able to say

Explain hybrid fan-out and what happens to a cached timeline when a post is deleted.

The route

6 blocks (2 fundamental, 3 senior, 1 staff), then the practice problem.

  1. Precompute on write, read cheaplySenior
  2. Fix a hot shardSenior
  3. Precompute joinsFundamental
  4. Page results with a cursorFundamental
  5. Rank instead of sorting by timeStaff
  6. Protect against a cache stampedeSenior
  7. News Feed (Twitter / X timeline)
Latency & performanceScaling & loadData processing & searchFundamentalSeniorStaff
Read each block, then tick “I can explain this”: the path remembers where you are.Start with step 1
Your News Feed so far0 of 6 blocks in
AuthorPOST /v1/postsPost serviceAmazon EC2 Auto Scalingassigns Snowflake idPost eventsAmazon MSK (Kafka)Kafka, partitioned byauthor_idFan-out workersAmazon EC2 Auto ScalingZADD per follower, skipcelebritiesPosts storeAmazon Keyspacesposts andposts_by_authorTimeline cacheAmazon ElastiCachehome:{uid} sorted set,800 idsGraph serviceAmazon Keyspacesfollowers andfollowing tablesReaderGET /v1/feed/homeFeed serviceAmazon EC2 Auto Scalingmerge, hydrate, nextcursorCelebrity post keysAmazon ElastiCachelast 50 ids, suffixedcopiesRanking serviceAmazon SageMakerabout 500 candidatesin 50 msStep 1: Precompute on write, read cheaply1Step 3: Precompute joins3Step 1: Precompute on write, read cheaply1Step 3: Precompute joins3Step 3: Precompute joins3Step 4: Page results with a cursor4Step 2: Fix a hot shard2Step 6: Protect against a cache stampede6Step 5: Rank instead of sorting by time5new postpost createdwrite rowfollowers, 5K a pageZADDcursor20 idscelebrity pullscore candidates

Next, step 1 adds Fan-out workers, Timeline cache (outlined). A box fills in when you tick “I can explain this” on the block that introduces it; plain boxes come from the problem itself.

Each block has a diagram. Open one beside its step, or all of them at once.
  1. Precompute on write, read cheaply

    Latency & performancesenior~5 min

    The central idea: do the work on write so a read is one fetch.

    Assembling a page at read time (a feed, a dashboard) is too slow.

    Say it like this: Reads are far more frequent than posts, so I do the work at write time by fanning each post into the timeline cache of every follower, and a feed read becomes one range query.

    Adds to the design: Fan-out workers, Timeline cache

    Check yourself: How do you pick the follower threshold for celebrities?

    From the write budget: the number of ZADDs per post you can afford at peak without delaying ordinary fan-out, divided by posts per second from large accounts. It starts around 10K followers and is tuned from fan-out lag metrics; it should be a config value, not a constant.

    Read this block →

  2. Fix a hot shard

    Scaling & loadsenior~5 min

    The celebrity problem is a hot partition; see it as one before solving it.

    One partition takes most of the traffic (a celebrity, a popular tenant, a time-ordered key).

    Say it like this: The celebrity partition is taking most of the writes, so I salt the key into sub-partitions and read them back together, trading a wider read for an even write load.

    Adds to the design: Celebrity post keys

    Check yourself: How do you detect a hot partition before it becomes an incident?

    Per-partition throughput and latency metrics with an alert on the ratio of the hottest partition to the median. Many stores expose this directly, such as CloudWatch contributor insights for DynamoDB. Alert at 5× the median, which is well before saturation.

    Read this block →

  3. Precompute joins

    Latency & performancefundamental~6 min

    Feeds store copies on purpose; this is the discipline that keeps copies consistent.

    A hot read path needs a multi-table join every time.

    Say it like this: The home timeline is read a thousand times more than it is written, so I denormalise: each post is copied with its author name and avatar into the per-user feed row at write time, and the read is a single range scan with no joins.

    Adds to the design: Posts store, Timeline cache, Graph service

    Check yourself: How do you decide which fields to copy?

    Copy what the page always shows and what changes rarely: post text, author handle, avatar URL. Leave out what changes constantly or is cheap to fetch in a batch: like counts, follow state. Every copied field is a future fix-up job, so copy the minimum that removes the join.

    Read this block →

  4. Page results with a cursor

    Latency & performancefundamental~5 min

    Infinite scroll over a changing list needs cursors, not offsets.

    Users scroll long lists; OFFSET queries get slower the deeper they go.

    Say it like this: Users scroll a long timeline, so I page by cursor rather than offset: the client sends the last (created_at, id) it saw, the query seeks past it on the index, and page 1,000 costs the same as page 1.

    Adds to the design: Feed service

    Check yourself: Why must the cursor include the id as well as the timestamp?

    Timestamps collide, especially at millisecond resolution under load. Without a tiebreaker the comparison created_at < cursor either skips rows that share the cursor timestamp or returns them again. Adding the unique id makes the ordering total and the seek exact.

    Read this block →

  5. Rank instead of sorting by time

    Data processing & searchstaff~6 min

    Where a ranker sits relative to the cache, and what it costs in latency.

    Chronological feeds bury the posts users care about.

    Say it like this: A chronological feed buries what the user cares about, so I fetch a few hundred candidate ids cheaply, score them with features in a ranking service under a strict latency budget, and keep chronological as the fallback when the ranker is slow or down.

    Adds to the design: Ranking service

    Check yourself: Why fetch ids first and bodies last?

    Ids are tiny and the ranker only needs features, not text, so scoring 400 candidates costs a few kilobytes of ids plus feature lookups. Hydrating 400 bodies would be 400 KB and most of it is thrown away; hydrate only the 20 that survive.

    Read this block →

  6. Protect against a cache stampede

    Latency & performancesenior~5 min

    A feed refresh storm at 9am is a stampede; finish with the protections.

    A popular key expires and every request misses at once, flattening the database (dog-piling).

    Say it like this: I stop a hot key from dog-piling the database by letting one request refresh it while everyone else is served the stale value, and I jitter TTLs so keys never expire together.

    Adds to the design: Celebrity post keys

    Check yourself: What is the difference between a cache stampede and a thundering herd?

    A stampede is the specific case of one popular key expiring and all its readers missing at once. A thundering herd is the general pattern of many clients acting at the same instant, such as reconnects after an outage or retries aligned to the same backoff. The fixes overlap: jitter, coalescing, and serving stale.

    Read this block →

  7. Putting it together

    How the blocks above combine into one design for News Feed. The numbers on the boxes are the steps that introduce each part.

    The home timeline, assembled from the path
    AuthorPOST /v1/postsPost serviceAmazon EC2 Auto Scalingassigns Snowflake idPost eventsAmazon MSK (Kafka)Kafka, partitioned byauthor_idFan-out workersAmazon EC2 Auto ScalingZADD per follower, skipcelebritiesPosts storeAmazon Keyspacesposts andposts_by_authorTimeline cacheAmazon ElastiCachehome:{uid} sorted set,800 idsGraph serviceAmazon Keyspacesfollowers andfollowing tablesReaderGET /v1/feed/homeFeed serviceAmazon EC2 Auto Scalingmerge, hydrate, nextcursorCelebrity post keysAmazon ElastiCachelast 50 ids, suffixedcopiesRanking serviceAmazon SageMakerabout 500 candidatesin 50 msStep 1: Precompute on write, read cheaply1Step 3: Precompute joins3Step 1: Precompute on write, read cheaply1Step 3: Precompute joins3Step 3: Precompute joins3Step 4: Page results with a cursor4Step 2: Fix a hot shard2Step 6: Protect against a cache stampede6Step 5: Rank instead of sorting by time5new postpost createdwrite rowfollowers, 5K a pageZADDcursor20 idscelebrity pullscore candidates

    Each number is a step of this path; a box with two numbers is shaped by both blocks. The ring colour is the block's category, as on the route map. Boxes without a number come from the problem itself. Point at a step below, or at a bubble, to see where it appears.

    1. Precompute on write, read cheaply
    2. Fix a hot shard
    3. Precompute joins
    4. Page results with a cursor
    5. Rank instead of sorting by time
    6. Protect against a cache stampede

    A post is written once and fanned out by workers into every follower timeline, except for celebrities, whose recent posts are pulled at read time from a replicated per-author key. The feed service merges both, ranks the candidates and pages with a cursor.

    How each block shows up in the design

    • 1. Precompute on write, read cheaply: fan-out workers copy each new post id into every follower's home timeline, a Redis sorted set capped at 800 ids, so each of the 100K timeline reads per second at peak is one range query instead of a query that assembles the feed.
    • 2. Fix a hot shard: accounts above the follower threshold are never pushed, because one 50M-follower post would be a quarter of the system's steady write load; readers pull those posts at read time from a per-celebrity key copied under several suffixes, so no single cache node or partition takes the load.
    • 3. Precompute joins: each timeline holds the result of joining the follow graph with recent posts ahead of time, and the graph itself is stored twice, as followers and as following, so "who follows X" and "who does Y follow" are each a single-partition read.
    • 4. Page results with a cursor: the feed returns 20 ids per page with a cursor made of the last item's score and post id, which stays stable while new posts land at the top, where an offset would shift and show duplicates.
    • 5. Rank instead of sorting by time: the ranking service scores up to about 500 merged candidates in under 50 ms after the cache, never inside fan-out, so a new model ships without rebuilding a single timeline.
    • 6. Protect against a cache stampede: the per-celebrity keys are the hottest in the cache, so when one expires a single request refreshes it from posts_by_author while the rest are served the old ids, instead of millions of feed reads landing on one partition at once.
  8. ★

    News Feed (Twitter / X timeline)

    Now run the timed practice. The blocks above should appear in your answer without prompting; if one does not, that is the one to reread.

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingPost service, Fan-out workers, Feed service, Writer, Reader, Fix-up job, History APICompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon MSK (Kafka)Post eventsManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon KeyspacesPosts store, Graph serviceBigtableManaged Instance for Apache CassandraApache Cassandra, ScyllaDB
Amazon ElastiCacheTimeline cache, Celebrity post keys, Celebrity recent posts, Merged result cache, Feature store, Post cache, RedisMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon SageMakerRanking serviceVertex AIAzure Machine LearningKServe, Ray Serve, NVIDIA Triton
Amazon Auroraposts (source), profiles (source), DatabaseAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon DynamoDBfeed_item (read model)Firestore, BigtableCosmos DBScyllaDB, Apache Cassandra
Amazon Kinesis Data StreamsImpression logPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar