Skip to content

Feeds: Fan-Out on Write vs Read, Fan-In Aggregation ​

"Pre-materialization or Fan-out-on-write model: Feed for each viewer is pre-computed, materialized and kept ready for retrieval using a simple lookup query." — LinkedIn Engineering, FollowFeed: LinkedIn's Feed Made Faster and Smarter (2016)

Summary: A feed is a read-mostly merge of many people's writes. You either pay at write time (copy each post into every follower's list), pay at read time (collect and merge the followees' posts when the user opens the app), or split by author size; then you fan in ads, recommendations and notifications and rank the result. Focus: Home timeline vs user timeline, fan-out on write (push) with Redis sorted sets, fan-out on read (pull) with a k-way heap merge, the hybrid and the celebrity problem, fan-in aggregation, candidate generation → ranking → re-ranking, cursor pagination over merged streams, feed cache (trimming, TTL, regeneration, backfill), delete/edit/privacy propagation, notification fan-out, sharding and backpressure, observability, and a numeric worked example. Learning goal: Given a follower distribution and a read/post ratio, choose push, pull or hybrid with a number to defend it; implement the write workers, the read merge and the cursor in Go and Laravel 13; and know which metrics (feed latency p99, staleness, fan-out backlog) say the design is failing.

This chapter sits in the Domain Systems group. It owns the system-level decision and the numbers. Sibling pages own the mechanics: Caching for cache patterns, Sharding & Consistent Hashing for partitioning, Backpressure & Flow Control and Competing Consumers for the fan-out queue, Pagination: Offset vs Keyset for the SQL side of cursors, Redis for the data structures, Consistency Models for visibility, and ML Systems for the ranking models. The company-level stories are in Case Study: X / Twitter and Case Study: LinkedIn.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why feeds are a fan-out problemWhy it exists
Twitter, LinkedIn, Facebook TAO sourcesWhere it comes from
Home timeline vs user timeline, requirementsRequirements
Push modelFan-out on write
Pull model, k-way mergeFan-out on read
Celebrity problem, hybridHybrid
Ads, recommendations, notifications mergeFan-in aggregation
Candidate generation, ranking, re-rankingRanking
Post store, social graph, feed cacheStorage
Cursor by (score, id), infinite scrollPagination
ZADD, trimming, TTL, regeneration, backfillFeed cache
Deletes, edits, privacy changesConsistency
Push notifications, digestsNotification fan-out
Sharding, queues, backpressureScaling the pipeline
p99, staleness, backlogObservability
Redis commands, knobs, errorsMechanics
CodeGo, Laravel
Classic failuresSolving the classic problems
Which modelChoosing
Monolith to distributedIn architecture
NumbersWorked example, Lab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three models.

ModelIn plain wordsWhen the work happensRead costWrite costMain risk
Fan-out on write (push model)Copy each new post into every follower's feed listAt post time, in the backgroundOne lookup (ZRANGE on one sorted set)N feed writes per post (N = followers)Write amplification; celebrity posts = millions of writes
Fan-out on read (pull model)Keep posts only with the author; build the feed when the user opens the appAt read timek sub-queries + merge (k = followees)One insertRead amplification; slow for users who follow many accounts
Hybrid fan-outPush for ordinary authors, pull for celebrities, merge both at read timeBothOne lookup + a few celebrity queriesN writes for small authors, 1 for celebritiesTwo code paths, threshold tuning

The pipeline in one table.

StageQuestion it answersTypical product
Post storeWhat was posted, by whom, is it deleted?PostgreSQL, MySQL, Cassandra, Manhattan-style KV
Social graphWho follows whom?Sharded MySQL, Facebook TAO, a graph service
Fan-out workersWhich feeds get this post?Queue (Kafka, RabbitMQ, SQS, Laravel queue) + workers
Feed cacheWhat is this user's precomputed list?Redis sorted set per user (ZADD, ZRANGE)
Candidate sourcesWhat else could be in the feed?Ads, recommendations, notifications, in-network posts
RankerIn which order?Light ranker, heavy ranker, re-ranker
Page cursorWhere did the last page end?Opaque token of (score, id)

Numbers to carry in your head (back-of-envelope, see Worked example).

QuantityValueSource
Feed loads vs postsabout 30 : 1 in the exampleEstimate (inference)
Push writes per postfollowers (200 average)Definition
Pull sub-reads per feed loadfollowees (200 average)Definition
LinkedIn measured data size of push vs pull62 times greaterLinkedIn FollowFeed post (cited)
Share of in-network posts from the search-index source in X's For Youabout 50 percenttwitter/the-algorithm README (cited)

Why it exists ​

A social feed is the read side of a many-to-many relationship. One post is wanted by many readers; one reader wants posts from many authors. The data model is simple; the cost is not. Whichever way you slice it, someone must multiply: either the writer by the followers, or the reader by the followees.

ChoicePaysGets
Precompute (push)Storage, write bandwidth, wasted work for inactive readersFast, cheap, predictable reads
Compute on demand (pull)Read latency, CPU, database load on every openAlways fresh, no storage blowup, easy ranking experiments
MixComplexityBounded cost at both ends of the follower distribution

Everyday picture. A newspaper. Push is the delivery boy who drops the paper in every mailbox at 5 a.m.; it is waiting when you wake up, but papers go to houses where nobody reads. Pull is you walking to the kiosk and assembling your reading from many racks; nothing is wasted, but you stand in the queue. Hybrid is home delivery for most titles and a kiosk visit for the one magazine that has ten million subscribers.

FAN-OUT ON WRITE (push)FAN-OUT ON READ (pull)Author posts1 writefeed:alicefeed:bobfeed:carolfeed:celeb-fanReader1 lookupCost on write: N feed writes (N = followers)Cost on read: ZRANGE of one sorted setCelebrity post = millions of writesReader1 requestposts of Aposts of Bposts of Cposts of Dk-waymergeCost on write: 1 post insertCost on read: k queries + heap mergeFollows 1,000 accounts = 1,000 sub-reads

Three common misunderstandings, up front ​

  1. "Fan-out on write is the right answer, Twitter does it." Twitter's design is a hybrid for exactly the accounts where push breaks, and LinkedIn chose pull for its relevance-heavy feed (see Where it comes from). Neither is universal.
  2. "The feed is a database query." At scale the home timeline is a cache of ids, a merge of several candidate sources and a ranker. The SQL join is the prototype, not the product.
  3. "Page 2 is OFFSET 20." A feed changes while you scroll. Offset duplicates and skips items; use a cursor.

Where it comes from ​

Twitter, 2012. Raffi Krikorian's QCon talk Timelines at Scale (InfoQ, saved text) describes Twitter's architecture for thousands of events per second: tweets, social-graph mutations and direct messages. The widely taught shape of that design (a tweet is written once, then inserted into follower timeline caches asynchronously, and reads are cache reads) is the push model; this page treats that description as common knowledge and an inference, because only the InfoQ summary page was saved and read, so no figures from the talk are reproduced. Twitter's later open-sourced recommendation code (twitter/the-algorithm) lists the candidate sources of the For You timeline: "search-index: Find and rank In-Network posts. ~50% of posts come from this candidate source", plus out-of-network candidates coordinated by tweet-mixer, a light-ranker, a heavy-ranker neural network and home-mixer described as the "Main service used to construct and serve the Home Timeline" (README, read and saved).

LinkedIn, 2016. The FollowFeed post compares the two strategies directly and chooses fan-out on read: "data size with this model was 62 times greater than pull based architecture", and relevance experiments are easier because "relevance scores can be computed on the fly with each query". Read it as a worked example of choosing pull for ranking agility, not as a proof that pull is always better.

Facebook, 2013. The TAO paper (ATC 2013) describes the social-graph store behind the feed: objects and associations, a leader/follower cache tier, and "TAO provides eventual consistency ... by asynchronously sending cache maintenance messages from the leader to the followers". It is the model for the social graph store in this chapter, not a feed design.

Instagram. Instagram's engineering blog has feed posts, but the site returned no machine-readable page to curl in this session, so nothing from it is quoted here.

The concept catalogue ​

Requirements: home timeline, user timeline, ranking, freshness Must-know ​

In plain words: A feed is two different products. The user timeline is "everything this one person posted". The home timeline is "what the people I follow posted, plus other things the system thinks I like".

Common misunderstanding: "They are the same query with a different user id." The user timeline is a single-key range scan on (author_id, id DESC): cheap, always pull. The home timeline is a merge across authors and sources; that is where fan-out and ranking live.

Definition: News feed and timeline are used interchangeably; this page says user timeline for one author's posts and home timeline for the personalised merge.

user timeline  : SELECT ... FROM posts WHERE author_id = ? ORDER BY id DESC LIMIT 20
home timeline  : merge( posts of every followee , ads , recommendations , notifications ) -> rank -> page

Real scenarios: profile page (user timeline); app open on a phone (home timeline); a push notification deep-links to one post; a list or "following only" tab filters the home timeline to in-network posts.

RequirementTypical target (assumption, not a standard)Design consequence
Read latency p99200 to 500 ms for the whole pagePrecomputed ids + batched hydration
Freshness of a friend's postsecondsAsync push or pull; no hourly batch
AvailabilityReads up when writes are degradedFeed cache serves stale rather than error
OrderingChronological or rankedDecides what the sort key (score) is
Read : write ratio10 : 1 up to 100 : 1Optimise reads, accept write cost
Deletes and privacyVisible quickly, not instantlyTombstones, read-time filter

Fix / how to use it: write the targets down before choosing a model; the number that decides is the follower distribution (see Hybrid).

Fan-out on write (push model) Must-know ​

In plain words: When a post is created, a background worker copies its id into the feed list of every follower. Opening the app is then a single read of one list.

Common misunderstanding: "Push means the post body is copied N times." No: only the id (and a score) goes into each feed; bodies stay in the post store and are fetched in one batch at read time. LinkedIn's 62x figure comes from persisting full records per viewer; an id-only feed is far smaller.

Definition: For post p by author a with follower set F(a), fan-out on write performs |F(a)| insertions ZADD feed:u score p for u in F(a), usually followed by a trim to the newest M entries.

T0  author POST /posts            -> insert into post store            (sync, 1 write)
T1  publish PostCreated(id=981)   -> queue partition(author)           (async)
T2  worker loads followers(a)     -> 200 follower ids
T3  worker pipelines 200 x ZADD feed:u 981 981 + ZREMRANGEBYRANK trim
T4  follower opens app            -> ZRANGE feed:u 0 19 REV -> ids -> MGET posts

Real scenarios: a typical user with 200 followers (200 writes, trivial); a company page with 2 million followers (2 million writes, minutes of backlog); a user who goes viral overnight (graph changes under your threshold).

AspectPush
Read costO(log N + page) on one sorted set
Write amplificationfactor = follower count
Wasted workWrites for users who never return (mitigate with TTL and AddIfPresent)
FreshnessDelay = queue lag + worker time
RankingFeed order fixed at write time unless re-ranked on read
StorageM entries per active user

Fix / how to use it: bounded feed (keep newest M, e.g. 800), id-only entries, write only to users who already have a feed, workers behind a bounded queue (see Go and Scaling).

Fan-out on read (pull model) Must-know ​

In plain words: Posts stay with their author. When you open the app the server asks every account you follow for their latest posts and merges the answers newest-first.

Common misunderstanding: "Pull means sorting all followees' posts." You never sort everything. Each author's posts are already ordered by id, so a k-way merge with a heap takes the top page in O(page * log k) after one bounded fetch per author.

Definition: Fan-out on read computes merge_k( latest(a_i, page) ) for each followee a_i at request time, deduplicates by post id, and returns the first page plus a cursor.

T0  user opens app
T1  graph.following(u)                  -> [a1 .. ak]   (k = 200)
T2  200 x SELECT ... WHERE author_id=ai AND id < cursor ORDER BY id DESC LIMIT 20   (parallel)
T3  heap of 200 heads: pop max, push that author's next, repeat 20 times
T4  hydrate 20 posts, return page + cursor(last.score, last.id)

Real scenarios: LinkedIn FollowFeed (pull with index-node fan-out via a broker service); an early-stage product with 10k users; a ranking experiment where scores must be computed on the fly.

AspectPull
Read costk sub-reads per page; mitigate by caching hot authors' latest posts
Write costOne insert
StoragePosts only once
FreshnessImmediate
Tail latencyMax of k parallel reads: the p99 of the page is roughly the p99.9 of one read for k = 100 (inference from Tail latency)
Ranking agilityHigh: compute scores per request

Fix / how to use it: index (author_id, id DESC), cap per-author fetch at the page size, cache each author's recent post ids (their timeline is shared by all their readers), and use the heap merge in Go.

Hybrid fan-out and the celebrity problem Must-know ​

In plain words: Push for people with a normal number of followers, pull for the few accounts with millions; combine at read time.

Common misunderstanding: "Hybrid means two systems." It is one feed service with one extra input: after reading the pushed list, it also queries the handful of celebrities the user follows and merges.

Definition: The celebrity problem is write amplification on a power-law graph: a few authors have followers in the millions, so push cost per post is dominated by them. A threshold (follower count, or follower count weighted by activity) splits authors into pushed and pulled.

T0  celeb posts (50,000,000 followers)  -> post store insert only, fan-out skipped
T1  reader opens app                    -> ZRANGE feed:u (pushed ids from normal authors)
T2  reader follows 3 celebrities        -> 3 indexed queries (author_id, id DESC) LIMIT 20
T3  merge pushed + pulled by (score,id) -> hydrate, rank, page

Real scenarios: a pop star posts during a match (without hybrid: tens of millions of writes in seconds); an account crosses the threshold mid-life (switch it to pull and let old pushed entries age out); a mutual-follow cluster with all accounts below threshold (push is fine).

Threshold choiceEffectRisk
Low (e.g. 10k followers)Fewer fan-out writesMore pulls per read; more read amplification
High (e.g. 1M)Fast readsLarge bursts of write work
Dynamic (by recent post rate x followers)Matches actual costMore moving parts

Fix / how to use it: cheap follower count in the graph store, a threshold in configuration, and pull sources cached (the celebrity's last 50 post ids in Redis is shared by every follower). The tested implementation is fanout.Pusher.IsCelebrity plus hybrid.Reader in Go.

Post APIQueueFan-out workersFeed cacheRedis ZSET per userCelebrity: skip pushTrim to N, TTLRead APIFeed servicePushed idsCelebrity pullAds, recs, notifsSocial graphRank, dedupPage + cursor(score, id)WRITE PATH (top) | READ PATH = fan-in (bottom)

Fan-in aggregation Must-know ​

In plain words: Fan-out is one post going to many feeds. Fan-in is many sources going into one page: the pushed list, pulled celebrity posts, ads, recommendations, a "who to follow" card.

Common misunderstanding: "Ads and recommendations are just rows in the feed table." They are separate services with their own latency and failure modes; the feed service calls them in parallel with a deadline and degrades by omitting them.

Definition: Fan-in (aggregation) is the read path stage that gathers candidates from several sources, deduplicates, filters, ranks and mixes them into one ordered page. It is the API composition pattern from Service Communication applied to a feed.

T0  feed service receives GET /home?cursor=C
T1  parallel, deadline 150 ms:  pushed ids | celebrity pull | recommendations | ads | notifications badge
T2  any source that misses its deadline is dropped (partial result, not an error)
T3  dedup by post id; remove blocked, muted, deleted (visibility filter)
T4  rank -> mix ads at fixed slots -> hydrate -> return page + next cursor

Real scenarios: the same post both pushed and recommended (dedup keeps one, marks it in-network); a recommendation service outage (the feed still loads, only chronological candidates); an ad every fifth slot.

SourceLatency budgetIf it fails
Feed cache (Redis)5 to 10 msRebuild by pull; or stale page
Celebrity pull20 to 50 msSkip celebrities (log it)
Recommendations50 to 100 msOmit
Ads50 to 100 msOmit (revenue impact, not an outage)
Hydration (post bodies)10 to 30 msFail the page

The budgets are design assumptions; compute your own with Latency Budget & Tail Latency.

Fix / how to use it: a deadline per source, hedge only idempotent reads, a dedup set keyed by post id, and a partial-result flag in the response so clients and metrics see degradation.

Ranking: chronological vs ranked, candidate generation, re-ranking Important ​

In plain words: Chronological sorts by time. A ranked feed first finds a few hundred plausible posts, scores them with a model, then adjusts the order for variety and policy.

Common misunderstanding: "Ranking replaces the feed cache." The cache supplies one candidate source (in-network posts); the ranker consumes it plus others.

Definition: The standard three-stage funnel is candidate generation (thousands, cheap, recall-oriented), ranking (hundreds, a light then a heavy model, precision-oriented) and re-ranking (tens, business rules: diversity, no three posts from one author in a row, ad slots, safety filtering). The twitter/the-algorithm README names exactly this shape: candidate sources, light-ranker, heavy-ranker, and home-mixer with visibility-filters.

T0  candidate generation : in-network (feed cache) + out-of-network (graph traversal, embeddings)  ~ 1500
T1  light ranker         : cheap model on every candidate                                         ~ 500
T2  heavy ranker         : neural network on survivors                                            ~ 100
T3  re-ranking           : diversity, author caps, ads, visibility filters                        ~ 20 shown

Real scenarios: "Following" tab (chronological, in-network only); "For you" (ranked); a notification digest (ranked by predicted interest); an A/B test of a new model (cheap in pull, a re-sort of the cached list in push).

Signal familyExamplesWhere computed
Authorfollower count, relationship strength, mutualsGraph service, offline
Postage, media type, early engagement rateStream aggregates
Viewerpast engagement with this author, session timeFeature store (ML Systems)
Contexttime of day, device, networkRequest

Fix / how to use it: store only ids and a base score in the feed cache, rank on read for the first page, and keep the chronological sort available as a fallback when the ranker is down.

Storage: post store, social graph, feed cache, hot users Must-know ​

In plain words: Three different stores with three access patterns: posts by id and by author; edges by follower and by followee; precomputed lists by user.

Common misunderstanding: "One database for all three." The graph is read an order of magnitude more than posts are written and needs two indexes (both directions); the feed cache is derived and disposable.

Definition: The post store is the source of truth for content and tombstones. The social graph (follow graph) stores directed edges. The feed cache is derived, bounded and rebuildable.

posts      (id PK, author_id, body, visibility, deleted_at)    index (author_id, id DESC)
follows    (follower_id, followee_id) PK + index (followee_id, follower_id)
feed:{uid} ZSET member=post_id score=post_id (time-ordered id)

Real scenarios: Facebook's TAO (objects and associations, leader/follower caches) as the graph tier; MySQL sharded by author_id for posts; Redis Cluster for feeds; a Kafka topic as the fan-out log.

StoreKeyAccessTypical productSharded by
Post storepost idby id, by author rangeMySQL, PostgreSQL, Cassandraauthor id (user timeline locality)
Social graph(follower, followee)both directionsSharded MySQL, TAO, a graph DBfollower id, with a reverse copy
Feed cacheuser idZRANGE by scoreRedis Cluster, Memcached listsuser id
Counters (likes, followers)post / user idincrement, readRedis, sharded countersid
sql
-- Both directions of the graph, so push ("who follows me") and pull ("whom do I follow") are index seeks.
CREATE INDEX follows_followee ON follows (followee_id, follower_id);
SELECT follower_id FROM follows WHERE followee_id = 42 ORDER BY follower_id LIMIT 1000;

Fix / how to use it: full SQL schema in Go imports (schema.sql); hot users (celebrities) get a dedicated replicated cache of their latest post ids; use Sharded Counters for follower and like counts.

Cursor pagination, stable ordering, infinite scroll Must-know ​

In plain words: Instead of "page 3", the client sends "give me items older than this one". Because new posts arrive at the top, "older than X" stays correct while "skip 40" does not.

Common misunderstanding: "Cursor pagination is just a fancy offset." An offset is a position that moves when rows are inserted; a cursor is a value that does not.

Definition: Cursor pagination returns the first limit items strictly older than the sort key (score, id) of the last item the client saw. The pair gives stable ordering under inserts and ties; the token is opaque (base64) so the server can change its content.

T0  GET /home                       -> items 90, 85, 80   cursor=(80,80)
T1  someone posts item 95           -> top of the feed
T2  GET /home?cursor=(80,80)        -> items 75, 70, 60   (no repeat of 80, no skip)
T2' OFFSET 3 version                -> items 85? 80? repeated: offset moved by one

Real scenarios: infinite scroll in a mobile app; a client that returns after an hour and prepends "new posts" with a second cursor pointing at the newest known item; a merged stream where each source contributes its own sub-cursor.

PropertyOffsetCursor (score, id)
Insert at top while scrollingduplicates or skipsstable
Deep page costgrows with offsetconstant (index seek)
Works over merged streamsnoyes, as a global bound
Random access to "page 7"yesno
Laravel APIpaginatecursorPaginate

Fix / how to use it: merge.EncodeCursor / DecodeCursor in Go; Laravel's cursorPaginate for single-source timelines; the global (score, id) bound for merged feeds (every source is queried with "strictly older than the cursor").

A: 90 · 70 · 40 ...B: 85 · 60 · 55 ...C: 80 · 75 · 20 ...max-heap of heads(90) (85) (80)pop max, advance thatstream, push its next headO(limit x log k)Dedup bypost idPage of Nlast = cursorNext page asks: items strictly older than (score, id) of the last item.A new post at the top changes nothing below the cursor; OFFSET would shift and repeat items.

The feed cache: sorted sets, trimming, TTL, regeneration, backfill Must-know ​

In plain words: Each active user has a Redis sorted set of post ids, newest first. It is kept short, thrown away when the user is inactive, and rebuilt from the post store on a miss.

Common misunderstanding: "The cache must never lose data." It is derived; losing it costs a rebuild, not data. The danger is a thundering herd of rebuilds, not a missing key.

Definition: A Redis sorted set is a collection of unique members ordered by score. ZADD inserts, ZRANGE ... BYSCORE REV (the modern form of ZREVRANGEBYSCORE, deprecated since Redis 6.2.0) reads newest first, ZREMRANGEBYRANK implements trimming (bounded feed), EXPIRE gives the TTL, and regeneration is the rebuild on a miss. Backfill fills the feed of a new follower with the followee's recent posts.

T0  worker: ZADD feed:42 981 981            -> inserted
T1  worker: ZREMRANGEBYRANK feed:42 0 -801  -> keep the newest 800
T2  reader: ZRANGE feed:42 (500 -inf BYSCORE REV LIMIT 0 20   -> ids older than 500
T3  user idle for 7 days: key expires (TTL) -> next open is a miss
T4  reader miss: pull + merge, ZADD up to 800 ids, EXPIRE 604800  -> regeneration

Real scenarios: user follows someone new (backfill their latest 50 posts into the feed); a Redis node fails (mass regeneration; protect with a single-flight lock per user); a user goes quiet (TTL reclaims memory).

OperationCommandCostUse
InsertZADD key score member (XX = only if exists)O(log N)Push
Read pageZRANGE key max min BYSCORE REV LIMIT 0 nO(log N + n)Home timeline
TrimZREMRANGEBYRANK key 0 -(M+1)O(log N + removed)Bounded feed
DeleteZREM key memberO(log N)Delete propagation
ExpireEXPIRE key secondsO(1)Inactive users
SizeZCARD keyO(1)Metrics

Fix / how to use it: feed.Cache (Go) mirrors these semantics (Add, AddIfPresent, Page, Rebuild, Evict); the Laravel job uses a Lua script so "exists, add, trim" is atomic per feed.

Consistency: eventual visibility, deletes, edits, privacy changes Important ​

In plain words: A new post shows up in followers' feeds a little later, not instantly. A deleted post must stop showing quickly, but it will linger in some caches for a moment unless you filter at read time.

Common misunderstanding: "Delete means remove it from every feed list." Finding the post in N feeds is the same fan-out again. The cheap, safe way is a tombstone in the post store plus a filter at hydration time.

Definition: Eventual visibility is the delay between the post commit and the post appearing in each feed (fan-out lag). Delete propagation is how a delete reaches caches; a tombstone is the marker (deleted_at) that wins over any cached id. A privacy change (block, mute, private account, audience change) must be applied at read time because it is cheaper than rewriting feeds.

T0  author deletes post 981            -> posts.deleted_at = now()  (tombstone, sync)
T1  publish PostDeleted(981)           -> workers ZREM best effort from known feeds (async)
T2  reader reads feed:42 (still has 981) -> hydration query drops it (deleted_at IS NOT NULL)
T3  after TTL / trim, the id disappears for good

Real scenarios: user blocks another (their posts must vanish at once, so filter by block list on read); account goes private (followers who are not approved lose access: read-time check); an edit (feed holds ids only, so the next hydration returns the new text).

EventEager fixRead-time fixRecommended
DeleteZREM from followers' feedsFilter by deleted_at on hydrateRead-time filter + best-effort ZREM
Editnone needed (ids only)Hydrate freshIds only
Block / muteRewrite feedFilter by block listRead-time filter
Privacy changeRewrite feedAuthorise per post on hydrateRead-time authorisation
UnfollowZREM author's postsFilter by current follow setRead-time filter, lazy cleanup

Fix / how to use it: keep ids only in the feed, hydrate from the post store with deleted_at IS NULL and a visibility check; accept seconds of lag for push and call it out in the product requirements. Consistency vocabulary is in Consistency Models and Eventual Consistency in Databases; TAO's asynchronous cache invalidation is the same pattern for the graph.

Notification fan-out Important ​

In plain words: The same "post created" event can also trigger a push notification to some followers. It is another fan-out, with stricter limits because phones are not Redis.

Common misunderstanding: "Notify everyone who follows." A notification for every post from every followed account trains users to turn them off; and vendors rate-limit device push (APNs, FCM).

Definition: Notification fan-out sends in-app badges, mobile push and email for events. Batching groups many events into one send; a digest summarises a period; per-user rate limits cap volume.

T0  PostCreated(981)                   -> notification planner
T1  planner selects opted-in followers (notify=on for this author)
T2  per user: rate limit check (max N pushes/hour), quiet hours, dedup key (user, post)
T3  enqueue batch of 500 device tokens -> push gateway (APNs, FCM)
T4  low-priority events fall into the daily digest instead

Real scenarios: a close-friends post (immediate push); a normal follow (digest); a breaking live event (burst: rate limit and spread over minutes).

TacticPurposeWhere
Opt-in per authorCut volumeGraph edge attribute
Per-user token bucketFatigue limitSee Rate Limiting Algorithms
Batching 500 tokens per requestThroughputPush gateway
Digest jobMerge many low-value eventsScheduled worker
Dedup key (user, post)Idempotent re-deliveryAPI Idempotency

Fix / how to use it: a separate queue and worker pool from feed fan-out, so a notification storm cannot starve feed writes.

Scaling the pipeline: sharding, async workers, backpressure, read replicas Must-know ​

In plain words: Spread feeds across machines by user id, do the copying in background workers, and refuse or slow down when the queue is full instead of letting memory fill.

Common misunderstanding: "More workers fix backlog." Workers write to Redis and read the graph; past a point they move the bottleneck. A bounded queue and a decision for overflow matter more than worker count.

Definition: Sharding by user places feed:{uid} on a Redis Cluster slot by key hash. An async worker consumes post events from a queue. Backpressure is the signal from a full queue that makes producers slow, drop, or degrade (here: a celebrity post is not pushed, it is pulled). Read replicas serve the graph and post store reads.

T0  burst: 3 big posts arrive in one second (300,000 follower writes)
T1  queue depth rises from 0 to 40,000 fan-out chunks
T2  depth crosses high-water mark -> Submit returns ErrBackpressure
T3  producer reacts: mark author "pull-only for 10 min", return 202 to client
T4  workers drain; depth falls below low-water mark; normal push resumes

Real scenarios: a TV event spikes posts 10x; a Redis shard failover pauses writes for 20 seconds; a deploy restarts all workers (the queue buffers).

MechanismProtectsProduct examples
Bounded queueWorker memoryGo buffered channel, Kafka partitions with retention, RabbitMQ x-max-length, SQS
Chunked jobs (1,000 followers)Retry granularityLaravel Bus::batch
Partition by authorPer-author orderingKafka key = author id
Priority lanesNormal users never wait behind a celebritySeparate queue fanout-hot
Read replicasGraph read loadMySQL, PostgreSQL replicas (Replication)
Load sheddingOverloadLoad Shedding

Fix / how to use it: see fanout.Pusher.Submit and Pusher.Rejected in Go, and Bus::batch(...)->allowFailures() in Laravel. The mechanics of brokers and flow control belong to Backpressure & Flow Control.

Observability: p99, staleness, fan-out backlog Important ​

In plain words: Three numbers tell you whether the feed is healthy: how long a page takes, how old the newest post in a feed is, and how far behind the fan-out workers are.

Common misunderstanding: "Average latency is fine, we are OK." A feed page is a fan-in: the slowest source decides it, so p99 matters.

Definition: Feed latency p99 is the 99th-percentile of the full page request. Staleness is now - time of newest post by anyone I follow versus what the feed shows. Fan-out backlog is queue depth or consumer lag in fan-out chunks or seconds.

T0  alert: feed_page_latency_seconds{quantile="0.99"} > 0.5 for 10 min
T1  check: fanout_backlog_seconds rising? -> workers or Redis
T2  check: partial_result_total{source="recs"} rising? -> dependency
T3  check: feed_cache_miss_ratio rising? -> eviction or TTL too short
MetricTypeAlert when
feed_page_latency_secondshistogramp99 above target 10 min
feed_staleness_secondsgauge (sampled)above 60 s
fanout_backlog_secondsgaugeabove 30 s
fanout_rejected_totalcounterrate above 0 for 5 min
feed_cache_miss_ratioratioabove 5 percent
feed_partial_result_total{source}counterspikes by source

Fix / how to use it: define SLOs (SLO, SLI & Error Budgets), instrument per source, and follow Observability for histograms and exemplars.

Mechanics ​

Redis commands and knobs ​

ItemDetail
Sorted-set readZRANGE key max min BYSCORE REV LIMIT offset count; ZREVRANGEBYSCORE is deprecated as of Redis 6.2.0 (docs)
Exclusive boundprefix ( : (500 means strictly below 500
Insert if existsZADD key XX score member
TrimZREMRANGEBYRANK key 0 -(M+1) keeps the newest M when score ascends
Small encodingzset-max-listpack-entries (default 128) and zset-max-listpack-value (default 64) keep small sets compact
Evictionmaxmemory + maxmemory-policy allkeys-lru makes feeds disposable; noeviction fails writes
Clusterone key per slot; pipeline per node, not across slots
Persistenceusually RDB or none: feeds are derived

Error messages you will meet ​

WhereMessage or codeMeaningAction
RedisOOM command not allowed when used memory > 'maxmemory'noeviction and fullChange policy, shorten feeds, add memory
RedisWRONGTYPE Operation against a key holding the wrong kind of valueKey is not a sorted setKey naming bug; delete key
Redis ClusterMOVED 3999 192.0.2.10:6379Slot lives elsewhereClient refresh; keep one key per command
Redis ClusterCROSSSLOT Keys in request don't hash to the same slotMulti-key command spans slotsOne key per command or hash tags
HTTP429 Too Many Requests / 503 Service UnavailableBackpressure at the APIClient retry with jitter
LaravelIlluminate\Queue\MaxAttemptsExceededExceptionJob exceeded $triesInvestigate failing job, move to failed_jobs

Limits and defaults worth knowing ​

KnobTypical valueWhy
Feed length M300 to 1000Few users scroll deeper; older = pull
Page size10 to 30Latency and payload
Fan-out chunk500 to 1,000 followersRetry granularity and Redis pipeline size
Celebrity threshold10^5 to 10^6 followersDepends on write capacity
Inactive TTL7 to 30 daysMemory vs miss rate
Per-source deadline50 to 150 msWhole-page budget

Go ​

Example ​

Four small packages with tests, stdlib only. feed mirrors a bounded sorted set. fanout is the write path: bounded queue, worker pool, celebrity threshold, backpressure counters.

go
// Package feed models a per-user feed cache with the semantics of a Redis
// sorted set: unique members ordered by score, ties broken by member.
package feed

import (
	"sort"
	"sync"
)

// Item is one entry in a feed: Score is the sort key (post time or a
// time-ordered ID), ID is the member.
type Item struct {
	Score int64
	ID    int64
}

// newer reports whether a sorts before b in newest-first order.
func newer(a, b Item) bool {
	if a.Score != b.Score {
		return a.Score > b.Score
	}
	return a.ID > b.ID
}

// Cache keeps one bounded sorted set per user.
type Cache struct {
	mu     sync.RWMutex
	maxLen int
	sets   map[int64][]Item // newest first
}

// NewCache bounds every feed to maxLen items (the ZREMRANGEBYRANK trim).
func NewCache(maxLen int) *Cache {
	return &Cache{maxLen: maxLen, sets: make(map[int64][]Item)}
}

// Add is ZADD key score member followed by a trim to maxLen.
// Adding an existing member updates its score, like ZADD.
func (c *Cache) Add(user int64, it Item) {
	c.mu.Lock()
	defer c.mu.Unlock()
	s := c.sets[user]
	for i := range s {
		if s[i].ID == it.ID {
			s = append(s[:i], s[i+1:]...)
			break
		}
	}
	i := sort.Search(len(s), func(i int) bool { return !newer(s[i], it) })
	s = append(s, Item{})
	copy(s[i+1:], s[i:])
	s[i] = it
	if len(s) > c.maxLen {
		s = s[:c.maxLen]
	}
	c.sets[user] = s
}

// Remove is ZREM: used for delete propagation.
func (c *Cache) Remove(user, id int64) {
	c.mu.Lock()
	defer c.mu.Unlock()
	s := c.sets[user]
	for i := range s {
		if s[i].ID == id {
			c.sets[user] = append(s[:i], s[i+1:]...)
			return
		}
	}
}

// Page returns up to limit items strictly older than the cursor
// (score, id), newest first. A nil cursor starts at the top. This is
// ZRANGE key max min BYSCORE REV LIMIT 0 n with an exclusive bound.
// The second result is false when the user has no cached feed (cache miss).
func (c *Cache) Page(user int64, after *Item, limit int) ([]Item, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	s, ok := c.sets[user]
	if !ok {
		return nil, false
	}
	out := make([]Item, 0, limit)
	for _, it := range s {
		if after != nil && !newer(*after, it) {
			continue
		}
		out = append(out, it)
		if len(out) == limit {
			break
		}
	}
	return out, true
}

// Len returns the cached length for a user.
func (c *Cache) Len(user int64) int {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return len(c.sets[user])
}

// Evict drops a user's feed (TTL expiry for inactive users).
func (c *Cache) Evict(user int64) {
	c.mu.Lock()
	defer c.mu.Unlock()
	delete(c.sets, user)
}

// AddIfPresent writes only when the user already has a cached feed, so
// fan-out does not create feeds for users who never come back.
func (c *Cache) AddIfPresent(user int64, it Item) {
	c.mu.RLock()
	_, ok := c.sets[user]
	c.mu.RUnlock()
	if ok {
		c.Add(user, it)
	}
}

// Rebuild replaces a user's feed with items (regeneration on a miss).
func (c *Cache) Rebuild(user int64, items []Item) {
	c.mu.Lock()
	defer c.mu.Unlock()
	s := append([]Item(nil), items...)
	sort.Slice(s, func(i, j int) bool { return newer(s[i], s[j]) })
	if len(s) > c.maxLen {
		s = s[:c.maxLen]
	}
	c.sets[user] = s
}
go
// Package fanout implements fan-out on write: a bounded queue, a worker
// pool, a celebrity threshold and explicit backpressure.
package fanout

import (
	"errors"
	"sync"
	"sync/atomic"

	"academy/feeds-fanout-fanin/feed"
)

// ErrBackpressure is returned when the queue is full; the caller decides
// whether to retry later, drop to pull-only, or shed the work.
var ErrBackpressure = errors.New("fanout queue full")

// Graph is the social-graph read side.
type Graph interface {
	// Followers returns the follower IDs of an author.
	Followers(author int64) []int64
	// FollowerCount is the cheap count used for the celebrity decision.
	FollowerCount(author int64) int
}

// Post is the event that triggers fan-out.
type Post struct {
	ID, Author, Score int64
}

// Pusher fans posts out into follower feeds.
type Pusher struct {
	graph     Graph
	cache     *feed.Cache
	threshold int
	queue     chan Post
	wg        sync.WaitGroup

	Pushed   atomic.Int64 // feed writes performed (write amplification)
	Skipped  atomic.Int64 // posts not pushed because the author is a celebrity
	Rejected atomic.Int64 // posts refused by backpressure
}

// New starts workers goroutines draining a queue of size queueSize.
// Authors with threshold or more followers are never pushed.
func New(g Graph, c *feed.Cache, workers, queueSize, threshold int) *Pusher {
	p := &Pusher{graph: g, cache: c, threshold: threshold, queue: make(chan Post, queueSize)}
	for i := 0; i < workers; i++ {
		p.wg.Add(1)
		go p.run()
	}
	return p
}

// Submit enqueues a post without blocking. A full queue is backpressure.
func (p *Pusher) Submit(post Post) error {
	select {
	case p.queue <- post:
		return nil
	default:
		p.Rejected.Add(1)
		return ErrBackpressure
	}
}

// IsCelebrity is the hybrid decision: pull, do not push.
func (p *Pusher) IsCelebrity(author int64) bool {
	return p.graph.FollowerCount(author) >= p.threshold
}

// Close stops accepting work and waits for the workers to drain.
func (p *Pusher) Close() {
	close(p.queue)
	p.wg.Wait()
}

func (p *Pusher) run() {
	defer p.wg.Done()
	for post := range p.queue {
		if p.IsCelebrity(post.Author) {
			p.Skipped.Add(1)
			continue
		}
		for _, f := range p.graph.Followers(post.Author) {
			// Only users who already have a cached feed are written;
			// inactive users are rebuilt on their next read.
			p.cache.AddIfPresent(f, feed.Item{Score: post.Score, ID: post.ID})
			p.Pushed.Add(1)
		}
	}
}

merge is the read path: k-way merge with container/heap, dedup and an opaque (score, id) cursor. hybrid joins the cache, celebrity pulls and regeneration on a miss.

go
// Package merge implements fan-out on read: a k-way merge of per-author
// streams with container/heap, plus an opaque (score, id) cursor.
package merge

import (
	"container/heap"
	"encoding/base64"
	"errors"
	"fmt"

	"academy/feeds-fanout-fanin/feed"
)

// Source yields one author's posts, newest first, strictly older than the
// cursor. In production this is an indexed query on (author_id, id DESC).
type Source interface {
	Next(after *feed.Item, limit int) []feed.Item
}

type cursorState struct {
	src   int
	items []feed.Item
	pos   int
}

type maxHeap []*cursorState

func (h maxHeap) Len() int { return len(h) }
func (h maxHeap) Less(i, j int) bool {
	a, b := h[i].items[h[i].pos], h[j].items[h[j].pos]
	if a.Score != b.Score {
		return a.Score > b.Score
	}
	return a.ID > b.ID
}
func (h maxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *maxHeap) Push(x any)   { *h = append(*h, x.(*cursorState)) }
func (h *maxHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

// Merge returns the newest limit items across all sources, strictly older
// than after, with duplicate IDs removed. Cost: O(limit log k) after one
// bounded fetch per source, instead of sorting every follower's posts.
func Merge(sources []Source, after *feed.Item, limit int) []feed.Item {
	h := &maxHeap{}
	for i, s := range sources {
		if items := s.Next(after, limit); len(items) > 0 {
			*h = append(*h, &cursorState{src: i, items: items})
		}
	}
	heap.Init(h)
	out := make([]feed.Item, 0, limit)
	seen := make(map[int64]struct{}, limit)
	for h.Len() > 0 && len(out) < limit {
		top := (*h)[0]
		it := top.items[top.pos]
		if _, dup := seen[it.ID]; !dup {
			seen[it.ID] = struct{}{}
			out = append(out, it)
		}
		top.pos++
		if top.pos == len(top.items) {
			heap.Pop(h)
		} else {
			heap.Fix(h, 0)
		}
	}
	return out
}

// EncodeCursor turns the last item of a page into an opaque token.
func EncodeCursor(it feed.Item) string {
	return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d:%d", it.Score, it.ID)))
}

// ErrBadCursor is returned for tokens that do not decode.
var ErrBadCursor = errors.New("invalid cursor")

// DecodeCursor parses a token; the empty string means "first page".
func DecodeCursor(tok string) (*feed.Item, error) {
	if tok == "" {
		return nil, nil
	}
	raw, err := base64.RawURLEncoding.DecodeString(tok)
	if err != nil {
		return nil, ErrBadCursor
	}
	var it feed.Item
	if _, err := fmt.Sscanf(string(raw), "%d:%d", &it.Score, &it.ID); err != nil {
		return nil, ErrBadCursor
	}
	return &it, nil
}
go
// Package hybrid is the read path of a hybrid feed: pushed items from the
// feed cache, merged at read time with the posts of followed celebrities.
package hybrid

import (
	"academy/feeds-fanout-fanin/feed"
	"academy/feeds-fanout-fanin/merge"
)

// cacheSource adapts the feed cache to merge.Source.
type cacheSource struct {
	c    *feed.Cache
	user int64
}

func (s cacheSource) Next(after *feed.Item, limit int) []feed.Item {
	items, _ := s.c.Page(s.user, after, limit)
	return items
}

// Reader builds home timelines.
type Reader struct {
	Cache *feed.Cache
	// CelebritiesOf lists the celebrity authors a user follows.
	CelebritiesOf func(user int64) []int64
	// PostsOf returns one celebrity's source (indexed by author).
	PostsOf func(author int64) merge.Source
	// Rebuild regenerates a missing feed from the post store.
	Rebuild func(user int64) []feed.Item
}

// Page returns one page and the next cursor ("" when exhausted).
func (r *Reader) Page(user int64, cursor string, limit int) ([]feed.Item, string, error) {
	after, err := merge.DecodeCursor(cursor)
	if err != nil {
		return nil, "", err
	}
	if _, ok := r.Cache.Page(user, nil, 1); !ok {
		r.Cache.Rebuild(user, r.Rebuild(user)) // regeneration on a miss
	}
	srcs := []merge.Source{cacheSource{r.Cache, user}}
	for _, a := range r.CelebritiesOf(user) {
		srcs = append(srcs, r.PostsOf(a))
	}
	items := merge.Merge(srcs, after, limit)
	next := ""
	if len(items) == limit {
		next = merge.EncodeCursor(items[len(items)-1])
	}
	return items, next, nil
}

Tests prove trimming, exclusive cursors, dedup, backpressure, skipping celebrities and inactive users, and stability when a post arrives between pages.

go
package hybrid

import (
	"testing"

	"academy/feeds-fanout-fanin/feed"
	"academy/feeds-fanout-fanin/merge"
)

type slice []feed.Item

func (s slice) Next(after *feed.Item, limit int) []feed.Item {
	var out []feed.Item
	for _, it := range s {
		if after != nil && !(it.Score < after.Score || (it.Score == after.Score && it.ID < after.ID)) {
			continue
		}
		out = append(out, it)
		if len(out) == limit {
			break
		}
	}
	return out
}

func TestHybridPagesWithoutGapsOrDuplicates(t *testing.T) {
	c := feed.NewCache(100)
	celeb := slice{{Score: 50, ID: 50}, {Score: 30, ID: 30}, {Score: 10, ID: 10}}
	r := &Reader{
		Cache:         c,
		CelebritiesOf: func(int64) []int64 { return []int64{9} },
		PostsOf:       func(int64) merge.Source { return celeb },
		Rebuild: func(int64) []feed.Item {
			return []feed.Item{{Score: 40, ID: 40}, {Score: 20, ID: 20}, {Score: 30, ID: 30}}
		},
	}
	var got []int64
	cursor := ""
	for {
		items, next, err := r.Page(1, cursor, 2)
		if err != nil {
			t.Fatal(err)
		}
		for _, it := range items {
			got = append(got, it.ID)
		}
		if next == "" {
			break
		}
		cursor = next
	}
	want := []int64{50, 40, 30, 20, 10}
	if len(got) != len(want) {
		t.Fatalf("got %v want %v", got, want)
	}
	for i := range want {
		if got[i] != want[i] {
			t.Fatalf("got %v want %v", got, want)
		}
	}
}

func TestStableUnderInsert(t *testing.T) {
	c := feed.NewCache(100)
	r := &Reader{
		Cache:         c,
		CelebritiesOf: func(int64) []int64 { return nil },
		Rebuild:       func(int64) []feed.Item { return []feed.Item{{Score: 3, ID: 3}, {Score: 2, ID: 2}, {Score: 1, ID: 1}} },
	}
	first, next, _ := r.Page(1, "", 1)
	c.Add(1, feed.Item{Score: 9, ID: 9}) // new post arrives between pages
	second, _, _ := r.Page(1, next, 1)
	if first[0].ID != 3 || second[0].ID != 2 {
		t.Fatalf("offset-style shifting: first=%v second=%v", first, second)
	}
}
go
package fanout

import (
	"errors"
	"testing"

	"academy/feeds-fanout-fanin/feed"
)

type graph map[int64][]int64

func (g graph) Followers(a int64) []int64 { return g[a] }
func (g graph) FollowerCount(a int64) int { return len(g[a]) }

func TestPushSkipsCelebritiesAndInactiveUsers(t *testing.T) {
	c := feed.NewCache(10)
	c.Add(100, feed.Item{Score: 1, ID: 1}) // user 100 is active, 101 is not
	g := graph{1: {100, 101}, 2: {100, 101, 102, 103}}
	p := New(g, c, 2, 8, 4) // threshold 4: author 2 is a celebrity
	_ = p.Submit(Post{ID: 10, Author: 1, Score: 10})
	_ = p.Submit(Post{ID: 20, Author: 2, Score: 20})
	p.Close()
	if c.Len(100) != 2 || c.Len(101) != 0 {
		t.Fatalf("len100=%d len101=%d", c.Len(100), c.Len(101))
	}
	if p.Skipped.Load() != 1 {
		t.Fatalf("skipped=%d", p.Skipped.Load())
	}
}

func TestBackpressureWhenQueueFull(t *testing.T) {
	p := &Pusher{queue: make(chan Post, 1)} // no workers: nothing drains
	if err := p.Submit(Post{ID: 1}); err != nil {
		t.Fatal(err)
	}
	if err := p.Submit(Post{ID: 2}); !errors.Is(err, ErrBackpressure) {
		t.Fatalf("got %v", err)
	}
	if p.Rejected.Load() != 1 {
		t.Fatal("rejected counter")
	}
}

SQL for the stores (posts with tombstones, both-direction follow indexes, a durable feed table, the keyset pull query and the backfill insert):

sql
-- PostgreSQL schema for posts, the follow graph and a durable feed_items table.
CREATE TABLE posts (
    id          bigint PRIMARY KEY,                -- time-ordered ID (Snowflake-style)
    author_id   bigint      NOT NULL,
    body        text        NOT NULL,
    visibility  text        NOT NULL DEFAULT 'public',
    deleted_at  timestamptz,                       -- tombstone, not DELETE
    created_at  timestamptz NOT NULL DEFAULT now()
);
-- Pull path: newest posts of one author, keyset-paginated by id.
CREATE INDEX posts_author_id_desc ON posts (author_id, id DESC) WHERE deleted_at IS NULL;

CREATE TABLE follows (
    follower_id bigint      NOT NULL,
    followee_id bigint      NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (follower_id, followee_id)         -- "whom do I follow" (pull path)
);
CREATE INDEX follows_followee ON follows (followee_id, follower_id); -- "who follows me" (push path)

-- Optional durable materialised feed (the cache is the fast copy).
CREATE TABLE feed_items (
    user_id bigint NOT NULL,
    post_id bigint NOT NULL,
    PRIMARY KEY (user_id, post_id)
);

-- Home timeline read, pull path, keyset cursor (no OFFSET):
SELECT p.id, p.author_id, p.body
FROM follows f
JOIN posts p ON p.author_id = f.followee_id AND p.deleted_at IS NULL
WHERE f.follower_id = $1 AND p.id < $2           -- $2 = cursor from the previous page
ORDER BY p.id DESC
LIMIT 20;

-- Backfill for a new follow: copy the followee's latest posts into the feed.
INSERT INTO feed_items (user_id, post_id)
SELECT $1, id FROM posts
WHERE author_id = $2 AND deleted_at IS NULL
ORDER BY id DESC LIMIT 50
ON CONFLICT DO NOTHING;

The Go angle ​

  • A buffered chan is the simplest bounded queue; select with default is non-blocking submit and gives backpressure for free. In a real system the same decision is made at the broker (Kafka producer buffer, RabbitMQ x-max-length).
  • container/heap needs five methods; heap.Fix(h, 0) after advancing the top stream is cheaper than pop and push.
  • Use atomic.Int64 counters for amplification and rejection so they can be exported as metrics without locks.
  • For real Redis use github.com/redis/go-redis/v9 with Pipeline(); ZRangeArgs with ByScore and Rev is the modern read.

Laravel ​

Example ​

Publishing a post chunks followers into jobs and dispatches them as a batch. Celebrities are skipped (hybrid).

php
<?php

namespace App\Actions;

use App\Jobs\FanOutPostJob;
use App\Models\Post;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;

class PublishPost
{
    public const CELEBRITY_THRESHOLD = 100_000;

    public function __invoke(int $authorId, string $body): Post
    {
        $post = Post::create(['author_id' => $authorId, 'body' => $body]);

        $count = DB::table('follows')->where('followee_id', $authorId)->count();
        if ($count >= self::CELEBRITY_THRESHOLD) {
            return $post; // hybrid: celebrities are pulled at read time
        }

        // Chunk followers so one job writes ~1,000 feeds; the batch tracks completion.
        $jobs = [];
        DB::table('follows')->where('followee_id', $authorId)->orderBy('follower_id')
            ->chunk(1000, function ($rows) use (&$jobs, $post) {
                $jobs[] = new FanOutPostJob($post->id, $post->id, $rows->pluck('follower_id')->all());
            });

        Bus::batch($jobs)->name("fanout:{$post->id}")->onQueue('fanout')->allowFailures()->dispatch();

        return $post;
    }
}

Each job pipelines Lua scripts so a feed is written only if it exists and trimmed in the same atomic step.

php
<?php

namespace App\Jobs;

use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Redis;

/** Push one post into a chunk of follower feeds (fan-out on write). */
class FanOutPostJob implements ShouldQueue
{
    use Batchable, Queueable;

    public int $tries = 3;

    /** @param list<int> $followerIds */
    public function __construct(
        public int $postId,
        public int $score,
        public array $followerIds,
        public int $maxLen = 800,
    ) {
        $this->onQueue('fanout');
    }

    public function handle(): void
    {
        if ($this->batch()?->cancelled()) {
            return;
        }

        // One atomic script per feed: write only if the feed exists (XX semantics for
        // inactive users, who are rebuilt on read), then trim to the newest maxLen.
        $script = <<<'LUA'
        if redis.call('EXISTS', KEYS[1]) == 1 then
            redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2])
            redis.call('ZREMRANGEBYRANK', KEYS[1], 0, -(tonumber(ARGV[3]) + 1))
        end
        LUA;

        Redis::pipeline(function ($pipe) use ($script) {
            foreach ($this->followerIds as $uid) {
                $pipe->eval($script, 1, "feed:{$uid}", $this->score, $this->postId, $this->maxLen);
            }
        });
    }
}

The hybrid read path: Redis sorted set via the facade, regeneration on a miss with a TTL, celebrity posts pulled by index, merged by id.

php
<?php

namespace App\Feeds;

use App\Models\Post;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/** Hybrid read path: pushed ids from Redis + pulled celebrity posts, merged by id. */
class HomeTimeline
{
    private const MAX_LEN = 800;

    /** @return array{items: list<Post>, next: ?int} */
    public function page(int $userId, ?int $before, int $limit = 20): array
    {
        $key = "feed:{$userId}";
        if (! Redis::exists($key)) {
            $this->regenerate($userId, $key); // regeneration on a miss
        }

        $max = $before === null ? '+inf' : '('.$before; // '(' = exclusive bound
        // ZRANGE ... BYSCORE REV is the modern form of ZREVRANGEBYSCORE (deprecated since Redis 6.2).
        $pushed = array_map('intval', Redis::zrevrangebyscore($key, $max, '-inf', ['limit' => [0, $limit]]));

        $celebrityIds = DB::table('follows')->join('users', 'users.id', '=', 'follows.followee_id')
            ->where('follows.follower_id', $userId)->where('users.is_celebrity', true)
            ->pluck('follows.followee_id');

        $pulled = Post::whereIn('author_id', $celebrityIds)->whereNull('deleted_at')
            ->when($before !== null, fn ($q) => $q->where('id', '<', $before))
            ->orderByDesc('id')->limit($limit)->pluck('id')->all();

        $ids = collect($pushed)->merge($pulled)->unique()->sortDesc()->take($limit)->values();
        $posts = Post::whereIn('id', $ids)->whereNull('deleted_at')->get()->sortByDesc('id')->values();

        return ['items' => $posts->all(), 'next' => $ids->count() === $limit ? $ids->last() : null];
    }

    private function regenerate(int $userId, string $key): void
    {
        $ids = Post::whereIn('author_id', DB::table('follows')->where('follower_id', $userId)->select('followee_id'))
            ->orderByDesc('id')->limit(self::MAX_LEN)->pluck('id');
        if ($ids->isEmpty()) {
            return;
        }
        Redis::pipeline(function ($pipe) use ($ids, $key) {
            foreach ($ids as $id) {
                $pipe->zadd($key, [$id => $id]);
            }
            $pipe->expire($key, 60 * 60 * 24 * 7); // TTL for inactive users
        });
    }
}

A user timeline with cursorPaginate:

php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class CursorTimelineController extends Controller
{
    /** User timeline (one author): cursorPaginate encodes the last row's ordering columns. */
    public function show(Request $request, int $authorId)
    {
        return Post::where('author_id', $authorId)
            ->whereNull('deleted_at')
            ->orderByDesc('id') // unique, time-ordered: stable under inserts
            ->cursorPaginate(20);
    }
}

The Laravel angle ​

  • Bus::batch([...])->allowFailures()->dispatch() and Batchable with $this->batch()?->cancelled() are documented in the Laravel 13 queue docs (job batching); then, catch and finally callbacks give completion hooks.
  • cursorPaginate is documented in the Laravel 13 pagination docs and requires a unique, ordered column set; it avoids OFFSET, but it cannot jump to page 7 and does not know the total.
  • The Redis facade forwards commands to phpredis or Predis; Redis::pipeline batches round trips, Redis::eval runs Lua. Option shapes for zadd differ between clients, which is why the example uses a script.
  • Put fan-out on its own queue (onQueue('fanout')) with its own workers so a viral post cannot starve other jobs; run Horizon or queue:work --queue=fanout with separate concurrency.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost
Celebrity posts melt the workersHybrid thresholdSkip push when followers at or above TBounded write costRead-time pulls
New follower sees an empty feedBackfillCopy followee's latest 50 post idsImmediate contentOne extra write per follow
Inactive users waste memoryTTL + AddIfPresentExpire; rebuild on next readMemory proportional to active usersFirst read after absence is slower
Cache loss causes stampedeSingle-flight regenerationLock per user (SET NX), others wait or serve pullProtects DBLock handling
Page 2 repeats itemsCursor (score, id)Strictly older than last itemStableNo random page jump
Deleted post still visibleTombstone + read-time filterdeleted_at check on hydrateImmediateExtra hydrate predicate
Recommendations slow the feedPer-source deadlineDrop source on timeoutBounded p99Partial feeds
Queue backlog after viral postPriority lanes + backpressureSeparate queue, pull-only fallbackNormal users unaffectedMore operational parts

Celebrity burst ​

Symptom: backlog grows without bound after one post. Cause: threshold too high or follower count cached stale. Fix: dynamic threshold from recent post rate, and a pull-only flag set when Submit returns ErrBackpressure.

Empty feed after follow ​

Symptom: a new user sees nothing for minutes. Cause: no backfill and the cache does not exist. Fix: on a miss run the pull query once (the INSERT ... SELECT in schema.sql) and fill the cache.

Duplicate or missing items ​

Symptom: the same post appears twice across pages. Cause: two sources (pushed and recommended) or an offset. Fix: dedup set by post id in the merge, cursor bound for every source.

Choosing ​

SituationRecommendationExtra techniqueReason
Under 100k users, chronologicalPull (SQL join, keyset)Index (author_id, id DESC)Simplest, no cache to invalidate
Read-heavy, followers mostly under 10kPushBounded feed, TTL, AddIfPresentReads become one lookup
Power-law graph with accounts above 100kHybridThreshold, shared cache of celebrity postsBounds write amplification
Relevance-heavy, frequent model experimentsPull (LinkedIn FollowFeed)Index nodes, on-the-fly scoresExperiment velocity
Strong deletes/privacy requirementsRead-time filter regardlessTombstonesCorrectness over speed
Many sources (ads, recs)Fan-in service with deadlinesPartial resultsAvailability
Push notificationsSeparate pipelineRate limits, digestsFatigue and vendor limits

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One PostgreSQL database, the three tables from schema.sql, a home timeline query that joins follows and posts with a keyset condition. Up to hundreds of thousands of users this is correct and cheap. A single Laravel route calls cursorPaginate on a query joined through follows.

Modular monolith / multiple databases ​

The feed module owns feed_items and the Redis keys; the posts and graph modules expose interfaces (Followers, FollowerCount, PostsOf). Fan-out is an in-process queue (Laravel database or redis driver). Ownership: only the feed module writes feed:{uid}.

Microservices ​

Post service, graph service, feed service, ranking service, notification service. Flow: POST /posts -> post service commits -> publishes PostCreated through the outbox (Outbox Pattern) -> fan-out workers -> feed cache; the feed service composes at read time and degrades per source. The contract between them is events plus ids; no service joins another service's tables.

Distributed data (replicas, caches, sharding, multi-region) ​

Redis Cluster shards feeds by user; graph reads go to replicas with lag (a follow may take seconds to appear in fan-out; accept it or read the primary for the author's own follow list). Multi-region: write posts in the author's home region, replicate the event, and fan out to followers in each region locally; a cross-region follower sees the post after replication lag. The read-your-writes rule for the author is served by inserting the new id into the author's own feed synchronously.

Scaling path: 1x, 10x, 100x ​

ScaleDesignWhat breaks next
1x (10^5 users)SQL pull + keysetJoin cost per open
10x (10^6 to 10^7)Push into Redis, bounded feed, TTLCelebrities
100x (10^8 +)Hybrid, sharded Redis, priority queues, ranker with candidate sourcesCache memory and ranker cost

Worked example: a Twitter-scale estimate ​

All numbers below are a back-of-envelope estimate (inference), not Twitter's published figures.

QuantityAssumptionResult
Daily active users300 million
Posts per day100 million1,160 per second average, 3,500 peak (3x)
Average followers200
Push writes1,160 x 200232,000 feed writes per second average, 700,000 peak
Feed loads per day300M x 103 billion = 35,000 per second, 100,000 peak
Pull sub-reads if pure pull35,000 x 200 followees7 million per second (avg), 20 million peak
Feed cache size100M active x 800 ids x about 50 bytesabout 4 TB (before replication)
One celebrity post50 million followers50M writes; at 500,000 writes per second = 100 seconds

Reading it: push is 232k writes per second against 7 million sub-reads per second for pure pull, a 30x difference that is exactly the 30:1 read to post ratio. The celebrity row shows why a pure push system needs a threshold: one post is 100 seconds of the entire fan-out capacity.

Lab ​

Expected, not run (the Redis commands require a Redis server; the Go program in the snippets is tested with go test). Use redis-cli against a local Redis 7.

  1. Seed three feeds and trim:
    redis-cli ZADD feed:1 100 100 90 90 80 80 70 70
    redis-cli ZREMRANGEBYRANK feed:1 0 -4        # keep the newest 3
    # expected: (integer) 1   (removed id 70)
  2. Read a page with an exclusive cursor:
    redis-cli ZRANGE feed:1 "(100" -inf BYSCORE REV LIMIT 0 2
    # expected: 1) "90"  2) "80"
  3. Insert at the top between pages; repeat the same command with (90:
    redis-cli ZADD feed:1 120 120
    redis-cli ZRANGE feed:1 "(90" -inf BYSCORE REV LIMIT 0 2
    # expected: 1) "80"   (no repeat, no skip)
  4. Update only if present (XX) and expire:
    redis-cli ZADD feed:2 XX 50 50      # expected: (integer) 0 (no feed, nothing created)
    redis-cli EXPIRE feed:1 604800      # expected: (integer) 1
  5. Run the Go tests: cd docs/snippets/system-design/feeds-fanout-fanin/go && go test ./...; expected ok for four packages (this was run).
  6. Measure amplification: after a run of fanout.Pusher, Pushed / posts equals the average follower count; raise the threshold until Skipped is zero and watch Pushed jump.

Common misconceptions ​

BeliefReality
Fan-out on write is always betterIt fails for accounts with millions of followers; hybrid exists for that
Fan-out on read is always slowLinkedIn FollowFeed chose it; with indexes and caching it is fast enough
The feed stores post bodiesIt stores ids; bodies are hydrated
Deleting means removing from all feedsTombstone + read-time filter is cheaper and safer
Offset pagination is fineInserts shift offsets; use a cursor
More workers always drain the backlogRedis and the graph store become the limit
Ranking replaces the cacheThe cache is one candidate source
The cache is the source of truthIt is derived and rebuildable
Average latency tells you the feed is healthyp99 of the fan-in decides user experience
Celebrity threshold is set onceFollower counts and post rates change; tune it

Cheat sheet ​

TopicRemember
PushN writes per post; one read
PullOne write; k reads + heap merge
HybridThreshold on followers; merge pushed + pulled at read
Feed entryid + score, not body
BoundTrim to M (300 to 1000)
TTLExpire inactive feeds; rebuild on miss
BackfillCopy followee's latest posts on follow
Cursor(score, id), strictly older, opaque
DeleteTombstone, filter at hydrate
Fan-inDeadline per source, partial results, dedup
RankingCandidates, light ranker, heavy ranker, re-rank
BackpressureBounded queue; overflow -> pull-only
Metricsp99 page latency, staleness, fan-out backlog
RedisZADD, ZRANGE BYSCORE REV, ZREMRANGEBYRANK, EXPIRE

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is write amplification a problem for push and what bounds it? Important ​

Answer

Answer: Each post costs one write per follower. Bound it with a celebrity threshold, a bounded feed and writing only to users with a cached feed.

2 — How does a k-way merge produce a page without sorting everything? Important ​

Answer

Answer: A max-heap holds one head per source; pop the max, advance that source, repeat limit times: O(limit log k).

3 — Why is OFFSET wrong for infinite scroll? Must-know ​

Answer

Answer: New posts shift positions, causing repeats or skips; a (score, id) cursor is a value, not a position.

4 — What does the hybrid model do at read time? Must-know ​

Answer

Answer: Reads the pushed list, queries the celebrities the user follows, merges by (score, id), ranks and pages.

5 — How do you propagate a delete? Important ​

Answer

Answer: Write a tombstone in the post store, filter on hydration, and ZREM best-effort.

6 — What is the role of ZREMRANGEBYRANK in a feed? Good to know ​

Answer

Answer: Trimming: it keeps only the newest M entries so memory per user is bounded.

7 — What happens when the fan-out queue is full? Important ​

Answer

Answer: Submit returns ErrBackpressure; the producer degrades (pull-only for that author, or 429/503) instead of buffering without limit.

8 — Name three metrics that show feed health. Must-know ​

Answer

Answer: Feed latency p99, staleness, fan-out backlog.

9 — Why does LinkedIn choose fan-out on read? Good to know ​

Answer

Answer: Per the FollowFeed post: pre-materialization made data 62 times larger in their experiments, and on-the-fly relevance scoring speeds experimentation.

10 — Which source decides a feed's p99? Important ​

Answer

Answer: The slowest required source in the fan-in (usually hydration or the ranker); optional sources are cut by deadline.

Glossary ​

TermMeaning
News feedThe stream of posts shown to a user
TimelineA feed; user timeline = one author, home timeline = personalised
Home timelineMerge of followees' posts and other sources
User timelineOne author's posts, newest first
Fan-out on writePush model: copy a post into each follower's feed at post time
Push modelSynonym of fan-out on write
Fan-out on readPull model: merge at read time
Pull modelSynonym of fan-out on read
Hybrid fan-outPush for normal authors, pull for celebrities
Celebrity problemWrite amplification from accounts with huge follower counts
Write amplificationWrites performed per logical write
Read amplificationSub-reads per logical read
Bounded feedFeed trimmed to a fixed length
BackfillFill a new follower's feed with recent posts
K-way mergeMerge k sorted streams
HeapPriority queue used for the merge
Fan-inAggregating many sources into one page
AggregationCollect, dedup, filter and mix candidates
Ranking serviceService that scores candidates
Candidate generationCheap first stage that proposes items
Re-rankingFinal adjustment for diversity and policy
Cursor paginationPage by "after this key" instead of offset
Stable orderingOrder unchanged by inserts, via unique (score, id)
Infinite scrollUI that loads the next page on scroll
DedupRemove duplicate ids across sources
Post storeSource of truth for posts
Social graphFollow edges
Follow graphSynonym of social graph
Feed cacheDerived per-user list in Redis
Sorted setRedis ordered-by-score unique set
ZADDInsert into a sorted set
ZREVRANGEBYSCOREDeprecated read command; use ZRANGE ... BYSCORE REV
TrimmingRemove old entries beyond M
TTLTime to live of a key
RegenerationRebuild a feed on a miss
Eventual visibilityPost appears after fan-out lag
Delete propagationMaking a delete reach caches
TombstoneMarker that a record was deleted
Privacy changeBlock, mute or audience change applied at read
Notification fan-outSending events to devices
DigestPeriodic summary of events
BatchingGrouping work into one request
Sharding by userPartition by user id
Async workerBackground consumer
QueueBuffer between producer and workers
BackpressureOverload signal that slows producers
Read replicaReplica serving reads
StalenessAge of newest data seen
p99 latency99th percentile latency
Fan-out backlogUnprocessed fan-out work
ChronologicalSorted by time only
Ranked feedSorted by a model score
cursorPaginateLaravel cursor pagination method

References ​

  1. LinkedIn Engineering, FollowFeed: LinkedIn's Feed Made Faster and Smarter — https://engineering.linkedin.com/blog/2016/03/followfeed--linkedin-s-feed-made-faster-and-smarter
  2. Raffi Krikorian, Timelines at Scale, QCon via InfoQ — https://www.infoq.com/presentations/Twitter-Timeline-Scalability/
  3. Bronson et al., TAO: Facebook's Distributed Data Store for the Social Graph, USENIX ATC 2013 — https://www.usenix.org/system/files/conference/atc13/atc13-bronson.pdf
  4. twitter/the-algorithm README — https://github.com/twitter/the-algorithm
  5. Redis docs, Sorted sets — https://redis.io/docs/latest/develop/data-types/sorted-sets/
  6. Redis docs, ZADD — https://redis.io/docs/latest/commands/zadd/
  7. Redis docs, ZREVRANGEBYSCORE (deprecated) — https://redis.io/docs/latest/commands/zrevrangebyscore/
  8. Redis docs, ZREMRANGEBYRANK — https://redis.io/docs/latest/commands/zremrangebyrank/
  9. Laravel 13 docs, Pagination (cursor) — https://laravel.com/docs/13.x/pagination
  10. Laravel 13 docs, Queues (job batching) — https://laravel.com/docs/13.x/queues
  11. Laravel 13 docs, Redis — https://laravel.com/docs/13.x/redis

Built by Morteza Negahi