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 for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why feeds are a fan-out problem | Why it exists |
| Twitter, LinkedIn, Facebook TAO sources | Where it comes from |
| Home timeline vs user timeline, requirements | Requirements |
| Push model | Fan-out on write |
| Pull model, k-way merge | Fan-out on read |
| Celebrity problem, hybrid | Hybrid |
| Ads, recommendations, notifications merge | Fan-in aggregation |
| Candidate generation, ranking, re-ranking | Ranking |
| Post store, social graph, feed cache | Storage |
| Cursor by (score, id), infinite scroll | Pagination |
| ZADD, trimming, TTL, regeneration, backfill | Feed cache |
| Deletes, edits, privacy changes | Consistency |
| Push notifications, digests | Notification fan-out |
| Sharding, queues, backpressure | Scaling the pipeline |
| p99, staleness, backlog | Observability |
| Redis commands, knobs, errors | Mechanics |
| Code | Go, Laravel |
| Classic failures | Solving the classic problems |
| Which model | Choosing |
| Monolith to distributed | In architecture |
| Numbers | Worked example, Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three models.
| Model | In plain words | When the work happens | Read cost | Write cost | Main risk |
|---|---|---|---|---|---|
| Fan-out on write (push model) | Copy each new post into every follower's feed list | At post time, in the background | One 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 app | At read time | k sub-queries + merge (k = followees) | One insert | Read amplification; slow for users who follow many accounts |
| Hybrid fan-out | Push for ordinary authors, pull for celebrities, merge both at read time | Both | One lookup + a few celebrity queries | N writes for small authors, 1 for celebrities | Two code paths, threshold tuning |
The pipeline in one table.
| Stage | Question it answers | Typical product |
|---|---|---|
| Post store | What was posted, by whom, is it deleted? | PostgreSQL, MySQL, Cassandra, Manhattan-style KV |
| Social graph | Who follows whom? | Sharded MySQL, Facebook TAO, a graph service |
| Fan-out workers | Which feeds get this post? | Queue (Kafka, RabbitMQ, SQS, Laravel queue) + workers |
| Feed cache | What is this user's precomputed list? | Redis sorted set per user (ZADD, ZRANGE) |
| Candidate sources | What else could be in the feed? | Ads, recommendations, notifications, in-network posts |
| Ranker | In which order? | Light ranker, heavy ranker, re-ranker |
| Page cursor | Where did the last page end? | Opaque token of (score, id) |
Numbers to carry in your head (back-of-envelope, see Worked example).
| Quantity | Value | Source |
|---|---|---|
| Feed loads vs posts | about 30 : 1 in the example | Estimate (inference) |
| Push writes per post | followers (200 average) | Definition |
| Pull sub-reads per feed load | followees (200 average) | Definition |
| LinkedIn measured data size of push vs pull | 62 times greater | LinkedIn FollowFeed post (cited) |
| Share of in-network posts from the search-index source in X's For You | about 50 percent | twitter/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.
| Choice | Pays | Gets |
|---|---|---|
| Precompute (push) | Storage, write bandwidth, wasted work for inactive readers | Fast, cheap, predictable reads |
| Compute on demand (pull) | Read latency, CPU, database load on every open | Always fresh, no storage blowup, easy ranking experiments |
| Mix | Complexity | Bounded 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.
Three common misunderstandings, up front
- "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.
- "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.
- "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 -> pageReal 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.
| Requirement | Typical target (assumption, not a standard) | Design consequence |
|---|---|---|
| Read latency p99 | 200 to 500 ms for the whole page | Precomputed ids + batched hydration |
| Freshness of a friend's post | seconds | Async push or pull; no hourly batch |
| Availability | Reads up when writes are degraded | Feed cache serves stale rather than error |
| Ordering | Chronological or ranked | Decides what the sort key (score) is |
| Read : write ratio | 10 : 1 up to 100 : 1 | Optimise reads, accept write cost |
| Deletes and privacy | Visible quickly, not instantly | Tombstones, 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 postsReal 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).
| Aspect | Push |
|---|---|
| Read cost | O(log N + page) on one sorted set |
| Write amplification | factor = follower count |
| Wasted work | Writes for users who never return (mitigate with TTL and AddIfPresent) |
| Freshness | Delay = queue lag + worker time |
| Ranking | Feed order fixed at write time unless re-ranked on read |
| Storage | M 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.
| Aspect | Pull |
|---|---|
| Read cost | k sub-reads per page; mitigate by caching hot authors' latest posts |
| Write cost | One insert |
| Storage | Posts only once |
| Freshness | Immediate |
| Tail latency | Max 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 agility | High: 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, pageReal 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 choice | Effect | Risk |
|---|---|---|
| Low (e.g. 10k followers) | Fewer fan-out writes | More pulls per read; more read amplification |
| High (e.g. 1M) | Fast reads | Large bursts of write work |
| Dynamic (by recent post rate x followers) | Matches actual cost | More 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.
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 cursorReal 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.
| Source | Latency budget | If it fails |
|---|---|---|
| Feed cache (Redis) | 5 to 10 ms | Rebuild by pull; or stale page |
| Celebrity pull | 20 to 50 ms | Skip celebrities (log it) |
| Recommendations | 50 to 100 ms | Omit |
| Ads | 50 to 100 ms | Omit (revenue impact, not an outage) |
| Hydration (post bodies) | 10 to 30 ms | Fail 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 shownReal 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 family | Examples | Where computed |
|---|---|---|
| Author | follower count, relationship strength, mutuals | Graph service, offline |
| Post | age, media type, early engagement rate | Stream aggregates |
| Viewer | past engagement with this author, session time | Feature store (ML Systems) |
| Context | time of day, device, network | Request |
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.
| Store | Key | Access | Typical product | Sharded by |
|---|---|---|---|---|
| Post store | post id | by id, by author range | MySQL, PostgreSQL, Cassandra | author id (user timeline locality) |
| Social graph | (follower, followee) | both directions | Sharded MySQL, TAO, a graph DB | follower id, with a reverse copy |
| Feed cache | user id | ZRANGE by score | Redis Cluster, Memcached lists | user id |
| Counters (likes, followers) | post / user id | increment, read | Redis, sharded counters | id |
-- 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 oneReal 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.
| Property | Offset | Cursor (score, id) |
|---|---|---|
| Insert at top while scrolling | duplicates or skips | stable |
| Deep page cost | grows with offset | constant (index seek) |
| Works over merged streams | no | yes, as a global bound |
| Random access to "page 7" | yes | no |
| Laravel API | paginate | cursorPaginate |
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").
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 -> regenerationReal 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).
| Operation | Command | Cost | Use |
|---|---|---|---|
| Insert | ZADD key score member (XX = only if exists) | O(log N) | Push |
| Read page | ZRANGE key max min BYSCORE REV LIMIT 0 n | O(log N + n) | Home timeline |
| Trim | ZREMRANGEBYRANK key 0 -(M+1) | O(log N + removed) | Bounded feed |
| Delete | ZREM key member | O(log N) | Delete propagation |
| Expire | EXPIRE key seconds | O(1) | Inactive users |
| Size | ZCARD key | O(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 goodReal 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).
| Event | Eager fix | Read-time fix | Recommended |
|---|---|---|---|
| Delete | ZREM from followers' feeds | Filter by deleted_at on hydrate | Read-time filter + best-effort ZREM |
| Edit | none needed (ids only) | Hydrate fresh | Ids only |
| Block / mute | Rewrite feed | Filter by block list | Read-time filter |
| Privacy change | Rewrite feed | Authorise per post on hydrate | Read-time authorisation |
| Unfollow | ZREM author's posts | Filter by current follow set | Read-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 insteadReal scenarios: a close-friends post (immediate push); a normal follow (digest); a breaking live event (burst: rate limit and spread over minutes).
| Tactic | Purpose | Where |
|---|---|---|
| Opt-in per author | Cut volume | Graph edge attribute |
| Per-user token bucket | Fatigue limit | See Rate Limiting Algorithms |
| Batching 500 tokens per request | Throughput | Push gateway |
| Digest job | Merge many low-value events | Scheduled worker |
| Dedup key (user, post) | Idempotent re-delivery | API 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 resumesReal scenarios: a TV event spikes posts 10x; a Redis shard failover pauses writes for 20 seconds; a deploy restarts all workers (the queue buffers).
| Mechanism | Protects | Product examples |
|---|---|---|
| Bounded queue | Worker memory | Go buffered channel, Kafka partitions with retention, RabbitMQ x-max-length, SQS |
| Chunked jobs (1,000 followers) | Retry granularity | Laravel Bus::batch |
| Partition by author | Per-author ordering | Kafka key = author id |
| Priority lanes | Normal users never wait behind a celebrity | Separate queue fanout-hot |
| Read replicas | Graph read load | MySQL, PostgreSQL replicas (Replication) |
| Load shedding | Overload | Load 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| Metric | Type | Alert when |
|---|---|---|
feed_page_latency_seconds | histogram | p99 above target 10 min |
feed_staleness_seconds | gauge (sampled) | above 60 s |
fanout_backlog_seconds | gauge | above 30 s |
fanout_rejected_total | counter | rate above 0 for 5 min |
feed_cache_miss_ratio | ratio | above 5 percent |
feed_partial_result_total{source} | counter | spikes 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
| Item | Detail |
|---|---|
| Sorted-set read | ZRANGE key max min BYSCORE REV LIMIT offset count; ZREVRANGEBYSCORE is deprecated as of Redis 6.2.0 (docs) |
| Exclusive bound | prefix ( : (500 means strictly below 500 |
| Insert if exists | ZADD key XX score member |
| Trim | ZREMRANGEBYRANK key 0 -(M+1) keeps the newest M when score ascends |
| Small encoding | zset-max-listpack-entries (default 128) and zset-max-listpack-value (default 64) keep small sets compact |
| Eviction | maxmemory + maxmemory-policy allkeys-lru makes feeds disposable; noeviction fails writes |
| Cluster | one key per slot; pipeline per node, not across slots |
| Persistence | usually RDB or none: feeds are derived |
Error messages you will meet
| Where | Message or code | Meaning | Action |
|---|---|---|---|
| Redis | OOM command not allowed when used memory > 'maxmemory' | noeviction and full | Change policy, shorten feeds, add memory |
| Redis | WRONGTYPE Operation against a key holding the wrong kind of value | Key is not a sorted set | Key naming bug; delete key |
| Redis Cluster | MOVED 3999 192.0.2.10:6379 | Slot lives elsewhere | Client refresh; keep one key per command |
| Redis Cluster | CROSSSLOT Keys in request don't hash to the same slot | Multi-key command spans slots | One key per command or hash tags |
| HTTP | 429 Too Many Requests / 503 Service Unavailable | Backpressure at the API | Client retry with jitter |
| Laravel | Illuminate\Queue\MaxAttemptsExceededException | Job exceeded $tries | Investigate failing job, move to failed_jobs |
Limits and defaults worth knowing
| Knob | Typical value | Why |
|---|---|---|
| Feed length M | 300 to 1000 | Few users scroll deeper; older = pull |
| Page size | 10 to 30 | Latency and payload |
| Fan-out chunk | 500 to 1,000 followers | Retry granularity and Redis pipeline size |
| Celebrity threshold | 10^5 to 10^6 followers | Depends on write capacity |
| Inactive TTL | 7 to 30 days | Memory vs miss rate |
| Per-source deadline | 50 to 150 ms | Whole-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.
// 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
}// 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.
// 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
}// 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.
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)
}
}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):
-- 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
chanis the simplest bounded queue;selectwithdefaultis non-blocking submit and gives backpressure for free. In a real system the same decision is made at the broker (Kafka producer buffer, RabbitMQx-max-length). container/heapneeds five methods;heap.Fix(h, 0)after advancing the top stream is cheaper than pop and push.- Use
atomic.Int64counters for amplification and rejection so they can be exported as metrics without locks. - For real Redis use
github.com/redis/go-redis/v9withPipeline();ZRangeArgswithByScoreandRevis the modern read.
Laravel
Example
Publishing a post chunks followers into jobs and dispatches them as a batch. Celebrities are skipped (hybrid).
<?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
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
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
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()andBatchablewith$this->batch()?->cancelled()are documented in the Laravel 13 queue docs (job batching);then,catchandfinallycallbacks give completion hooks.cursorPaginateis documented in the Laravel 13 pagination docs and requires a unique, ordered column set; it avoidsOFFSET, but it cannot jump to page 7 and does not know the total.- The
Redisfacade forwards commands to phpredis or Predis;Redis::pipelinebatches round trips,Redis::evalruns Lua. Option shapes forzadddiffer 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 orqueue:work --queue=fanoutwith separate concurrency.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost |
|---|---|---|---|---|
| Celebrity posts melt the workers | Hybrid threshold | Skip push when followers at or above T | Bounded write cost | Read-time pulls |
| New follower sees an empty feed | Backfill | Copy followee's latest 50 post ids | Immediate content | One extra write per follow |
| Inactive users waste memory | TTL + AddIfPresent | Expire; rebuild on next read | Memory proportional to active users | First read after absence is slower |
| Cache loss causes stampede | Single-flight regeneration | Lock per user (SET NX), others wait or serve pull | Protects DB | Lock handling |
| Page 2 repeats items | Cursor (score, id) | Strictly older than last item | Stable | No random page jump |
| Deleted post still visible | Tombstone + read-time filter | deleted_at check on hydrate | Immediate | Extra hydrate predicate |
| Recommendations slow the feed | Per-source deadline | Drop source on timeout | Bounded p99 | Partial feeds |
| Queue backlog after viral post | Priority lanes + backpressure | Separate queue, pull-only fallback | Normal users unaffected | More 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Under 100k users, chronological | Pull (SQL join, keyset) | Index (author_id, id DESC) | Simplest, no cache to invalidate |
| Read-heavy, followers mostly under 10k | Push | Bounded feed, TTL, AddIfPresent | Reads become one lookup |
| Power-law graph with accounts above 100k | Hybrid | Threshold, shared cache of celebrity posts | Bounds write amplification |
| Relevance-heavy, frequent model experiments | Pull (LinkedIn FollowFeed) | Index nodes, on-the-fly scores | Experiment velocity |
| Strong deletes/privacy requirements | Read-time filter regardless | Tombstones | Correctness over speed |
| Many sources (ads, recs) | Fan-in service with deadlines | Partial results | Availability |
| Push notifications | Separate pipeline | Rate limits, digests | Fatigue 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
| Scale | Design | What breaks next |
|---|---|---|
| 1x (10^5 users) | SQL pull + keyset | Join cost per open |
| 10x (10^6 to 10^7) | Push into Redis, bounded feed, TTL | Celebrities |
| 100x (10^8 +) | Hybrid, sharded Redis, priority queues, ranker with candidate sources | Cache 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.
| Quantity | Assumption | Result |
|---|---|---|
| Daily active users | 300 million | |
| Posts per day | 100 million | 1,160 per second average, 3,500 peak (3x) |
| Average followers | 200 | |
| Push writes | 1,160 x 200 | 232,000 feed writes per second average, 700,000 peak |
| Feed loads per day | 300M x 10 | 3 billion = 35,000 per second, 100,000 peak |
| Pull sub-reads if pure pull | 35,000 x 200 followees | 7 million per second (avg), 20 million peak |
| Feed cache size | 100M active x 800 ids x about 50 bytes | about 4 TB (before replication) |
| One celebrity post | 50 million followers | 50M 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.
- 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) - Read a page with an exclusive cursor:
redis-cli ZRANGE feed:1 "(100" -inf BYSCORE REV LIMIT 0 2 # expected: 1) "90" 2) "80" - 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) - 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 - Run the Go tests:
cd docs/snippets/system-design/feeds-fanout-fanin/go && go test ./...; expectedokfor four packages (this was run). - Measure amplification: after a run of
fanout.Pusher,Pushed/ posts equals the average follower count; raise the threshold untilSkippedis zero and watchPushedjump.
Common misconceptions
| Belief | Reality |
|---|---|
| Fan-out on write is always better | It fails for accounts with millions of followers; hybrid exists for that |
| Fan-out on read is always slow | LinkedIn FollowFeed chose it; with indexes and caching it is fast enough |
| The feed stores post bodies | It stores ids; bodies are hydrated |
| Deleting means removing from all feeds | Tombstone + read-time filter is cheaper and safer |
| Offset pagination is fine | Inserts shift offsets; use a cursor |
| More workers always drain the backlog | Redis and the graph store become the limit |
| Ranking replaces the cache | The cache is one candidate source |
| The cache is the source of truth | It is derived and rebuildable |
| Average latency tells you the feed is healthy | p99 of the fan-in decides user experience |
| Celebrity threshold is set once | Follower counts and post rates change; tune it |
Cheat sheet
| Topic | Remember |
|---|---|
| Push | N writes per post; one read |
| Pull | One write; k reads + heap merge |
| Hybrid | Threshold on followers; merge pushed + pulled at read |
| Feed entry | id + score, not body |
| Bound | Trim to M (300 to 1000) |
| TTL | Expire inactive feeds; rebuild on miss |
| Backfill | Copy followee's latest posts on follow |
| Cursor | (score, id), strictly older, opaque |
| Delete | Tombstone, filter at hydrate |
| Fan-in | Deadline per source, partial results, dedup |
| Ranking | Candidates, light ranker, heavy ranker, re-rank |
| Backpressure | Bounded queue; overflow -> pull-only |
| Metrics | p99 page latency, staleness, fan-out backlog |
| Redis | ZADD, ZRANGE BYSCORE REV, ZREMRANGEBYRANK, EXPIRE |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| News feed | The stream of posts shown to a user |
| Timeline | A feed; user timeline = one author, home timeline = personalised |
| Home timeline | Merge of followees' posts and other sources |
| User timeline | One author's posts, newest first |
| Fan-out on write | Push model: copy a post into each follower's feed at post time |
| Push model | Synonym of fan-out on write |
| Fan-out on read | Pull model: merge at read time |
| Pull model | Synonym of fan-out on read |
| Hybrid fan-out | Push for normal authors, pull for celebrities |
| Celebrity problem | Write amplification from accounts with huge follower counts |
| Write amplification | Writes performed per logical write |
| Read amplification | Sub-reads per logical read |
| Bounded feed | Feed trimmed to a fixed length |
| Backfill | Fill a new follower's feed with recent posts |
| K-way merge | Merge k sorted streams |
| Heap | Priority queue used for the merge |
| Fan-in | Aggregating many sources into one page |
| Aggregation | Collect, dedup, filter and mix candidates |
| Ranking service | Service that scores candidates |
| Candidate generation | Cheap first stage that proposes items |
| Re-ranking | Final adjustment for diversity and policy |
| Cursor pagination | Page by "after this key" instead of offset |
| Stable ordering | Order unchanged by inserts, via unique (score, id) |
| Infinite scroll | UI that loads the next page on scroll |
| Dedup | Remove duplicate ids across sources |
| Post store | Source of truth for posts |
| Social graph | Follow edges |
| Follow graph | Synonym of social graph |
| Feed cache | Derived per-user list in Redis |
| Sorted set | Redis ordered-by-score unique set |
| ZADD | Insert into a sorted set |
| ZREVRANGEBYSCORE | Deprecated read command; use ZRANGE ... BYSCORE REV |
| Trimming | Remove old entries beyond M |
| TTL | Time to live of a key |
| Regeneration | Rebuild a feed on a miss |
| Eventual visibility | Post appears after fan-out lag |
| Delete propagation | Making a delete reach caches |
| Tombstone | Marker that a record was deleted |
| Privacy change | Block, mute or audience change applied at read |
| Notification fan-out | Sending events to devices |
| Digest | Periodic summary of events |
| Batching | Grouping work into one request |
| Sharding by user | Partition by user id |
| Async worker | Background consumer |
| Queue | Buffer between producer and workers |
| Backpressure | Overload signal that slows producers |
| Read replica | Replica serving reads |
| Staleness | Age of newest data seen |
| p99 latency | 99th percentile latency |
| Fan-out backlog | Unprocessed fan-out work |
| Chronological | Sorted by time only |
| Ranked feed | Sorted by a model score |
cursorPaginate | Laravel cursor pagination method |
References
- 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
- Raffi Krikorian, Timelines at Scale, QCon via InfoQ — https://www.infoq.com/presentations/Twitter-Timeline-Scalability/
- 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
twitter/the-algorithmREADME — https://github.com/twitter/the-algorithm- Redis docs, Sorted sets — https://redis.io/docs/latest/develop/data-types/sorted-sets/
- Redis docs,
ZADD— https://redis.io/docs/latest/commands/zadd/ - Redis docs,
ZREVRANGEBYSCORE(deprecated) — https://redis.io/docs/latest/commands/zrevrangebyscore/ - Redis docs,
ZREMRANGEBYRANK— https://redis.io/docs/latest/commands/zremrangebyrank/ - Laravel 13 docs, Pagination (cursor) — https://laravel.com/docs/13.x/pagination
- Laravel 13 docs, Queues (job batching) — https://laravel.com/docs/13.x/queues
- Laravel 13 docs, Redis — https://laravel.com/docs/13.x/redis