Skip to main content
← CONCEPTS / SYSTEM-DESIGN
An end-to-end domain learning journey

Social Newsfeed Hybrid
Fan-Out & Ranking.

Hybrid newsfeed fan-out combines Fan-Out-on-Write (pushing post IDs to follower Redis timelines for normal users) with Fan-Out-on-Read (pulling celebrity posts at read time), followed by two-stage ML ranking and diversity deduplication.
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, route authors below the celebrity threshold (e.g., <100K followers) via async push workers to Redis Sorted Sets, merge celebrity posts at read time, and rank candidates with a two-stage L1/L2 ML pipeline.

TL;DR30-second simplified summary
▾

Hybrid fan-out routes posts via Kafka through a 100K-follower threshold gate: normal authors push 16-byte (post_id, ts) entries to active followers' 800-item Redis ZSETs, while celebrities write once to a Celebrity Post Cache merged at read time.

The Feed Hydrator batches Redis MGETs, runs L1 Two-Tower + L2 LightGBM ranking in <50ms (with chronological fallback), and filters seen posts via Bloom filters.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out
Real-time presence uses periodic WebSocket heartbeats into TTL-backed Redis keys (SETEX 45s) with online/offline hysteresis, paired with hybrid push/pull fan-out for small vs. massive channels.
Base62 URL Shortening & Edge Redirection
Base62 URL shortening maps 64-bit distributed counter IDs into compact 7-character alphanumeric codes (62^7 = 3.52T combinations), pairing collision-free writes with edge-cached HTTP 301/302 redirection.
Full walkthrough · 7 stages
01
foundation

Fan-Out-on-Write (Push) vs. Fan-Out-on-Read (Pull).

Why this matters: Understand the write-amplification vs. read-latency trade-off at social scale.

Think of Fan-Out-on-Write (Push) vs. Fan-Out-on-Read (Pull) as the intuition layer for Social Newsfeed Hybrid Fan-Out & Ranking: Understand the write-amplification vs. read-latency trade-off at social scale.

In Push (Fan-Out-on-Write), a post triggers N writes to N followers' precomputed Redis timelines, giving O(1) <20ms reads—until a 50M-follower celebrity posts and stalls the queue. In Pull (Fan-Out-on-Read), writes are O(1), but reading a feed requires querying K=500 followed authors' timelines and k-way merging them on every scroll.

Stage 1 - Push vs Pull

Push Write-Amplification vs Pull Scatter-Gather

Push (Write-Time)processor50M-Follower SpikerouterPull (Read-Time)cacheHybrid ThresholdsinkMerge celebrity pull

1.Active-Only Push: Only push into Redis inboxes of followers active in the last 14-30 days.

2.Tiny Payloads: Push only 16-byte (post_id, score) pairs, never full post text or media URLs.

Pure push breaks on celebrities while pure pull breaks on read latency.

02
foundation

The Celebrity Threshold Gate & Hybrid Merge.

Why this matters: Split ingestion dynamically by follower count and merge seamlessly at read time.

When a post is published to Kafka, a Fan-Out Worker queries the Social Graph Service for follower_count.

If < 100K, it pushes (post_id, ts) into followers' Redis ZSETs (capped at ZREMRANGEBYRANK top 800 items). If >= 100K, it appends only to that celebrity's own celeb_posts:<author_id> Redis ZSET.

Stage 2 - Hybrid Fan-Out

Celebrity Threshold Split & Read Merge

Post PublishedsourceFollower Gate(>=100K)routerFollower Redis ZSETcacheCelebrity PostCachestoragePush to active followers

1.Dynamic Promotion: Promote an author to celebrity-pull automatically if they cross 100K followers.

2.Bounded ZSET: Trim inbox ZSETs to 800 IDs; older history falls back to DB pagination.

Threshold gating keeps write amplification bounded while preserving sub-50ms feed candidate fetch.

Engineering Decision Framework
Problem
How to implement Social Newsfeed Hybrid Fan-Out & Ranking without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, route authors below the celebrity threshold (e.g., <100K followers) via async push workers to Redis Sorted Sets, merge celebrity posts at read time, and rank candidates with a two-stage L1/L2 ML pipeline.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Social Newsfeed Hybrid Fan-Out & Ranking experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

Post Hydration & Multi-Get Batching.

Why this matters: Fetch full post text, media metadata, and live like/comment counts without N+1 queries.

After merging candidate post_ids, the Feed Hydrator must turn 500 IDs into renderable objects.

Issuing 500 sequential DB queries causes N+1 latency collapse.

Stage 3 - Feed Hydration

Parallel Batch Hydration Pipeline

500 Candidate IDssourceRedis MGET BatchcacheNoSQL BatchGetstorageHydrated CandidatessinkFill cold misses

1.Filter Deleted/Blocked: Drop deleted posts or muted/blocked authors during hydration before ranking.

2.Separate Counters: Fetch volatile like/reply counts from a dedicated counter cache, not immutable post blobs.

Parallel Redis MGETs and batched NoSQL fallbacks hydrate 500 candidates in <15ms.

04
intermediate

Two-Stage ML Candidate Ranking (L1 Retrieval -> L2 Scorer).

Why this matters: Score 1,000+ in-network and out-of-network candidates within a 50ms ranking budget.

Modern feeds blend in-network posts with out-of-network 'For You' recommendations.

An L1 lightweight Two-Tower / Logistic model narrows 5,000+ candidates down to 300 in <10ms using cached user/post embeddings.

Stage 4 - Two-Stage Ranking

L1 Retrieval + L2 Feature-Store Ranker

In-Net + For-YouPoolsourceL1 Two-Tower FilterprocessorRedis Feature StorecacheL2 LightGBM / DNNsinkHydrate 300 feature rows

1.Graceful Fallback: If the ML Ranker times out at 50ms, fall back to reverse-chronological ZSET order.

2.Negative Signals: Penalize 'hide', 'mute', and fast-scroll-past signals heavily in L2 weights.

Two-stage ranking balances deep personalization accuracy with strict <50ms tail latency.

05
intermediate

Diversity Deduplication & Seen-Post Bloom Filter.

Why this matters: Prevent showing the same author 5 times in a row or repeating already-viewed posts.

Pure ML scoring often clusters 6 posts from one viral author back-to-back.

A post-ranking Diversity Re-Ranker applies sliding-window rules (e.g., max 1 post per author per 5 slots, interleave video/text/ads).

Stage 5 - Diversity & Dedupe

Seen-Post Bloom & Diversity Re-Ranker

L2 Ranked ListsourceSeen-Post BloomrouterDiversity Re-RankerprocessorTop-20 Feed PagesinkEnforce author spacing

1.Soft Decay Penalty: Instead of hard-dropping an author's 2nd post, multiply its score by 0.5x per repeat.

2.Async Seen Write: Mark posts as seen asynchronously via client viewport-impression beacons.

Seen-post Bloom filters and diversity re-ranking turn raw ML scores into engaging timelines.

06
advanced

Cursor-Based Pagination & Snapshot Consistency.

Why this matters: Prevent duplicate or skipped posts when users scroll through a live, mutating feed.

Think of Cursor-Based Pagination & Snapshot Consistency as the intuition layer for Social Newsfeed Hybrid Fan-Out & Ranking: Prevent duplicate or skipped posts when users scroll through a live, mutating feed.

Using OFFSET 20 LIMIT 20 breaks immediately on live feeds: if 5 new posts arrive while you read page 1, page 2 shifts by 5 and repeats items. Instead, the Feed Service caches the user's ranked candidate snapshot (feed_session_id in Redis, TTL 10m) or encodes an opaque (last_score, last_post_id) cursor so scrolling pages 2..N is fast, deterministic, and duplicate-free.

Stage 6 - Cursor Pagination

Snapshot-Backed Opaque Cursor

Page 1 RequestsourceRedis Feed SnapshotcacheOpaque Base64CursorrouterPage 2..N ScrollsinkReturn next_cursor

1.Pull-to-Refresh: Explicit pull-to-refresh invalidates the snapshot and recomputes fresh candidates.

2.Zero Re-Ranking Cost: Pages 2-5 skip the ML ranker entirely, slicing the cached snapshot in <5ms.

Session-cached ranked snapshots eliminate scroll duplicates and skip re-running ML on page 2+.

07
advanced

Cold-Start Onboarding & Backfill on Follow/Unfollow.

Why this matters: Keep timelines populated for new users and clean up immediately on unfollow/block.

A brand-new user with 0 follows sees an empty inbox ZSET.

Cold-start fallback injects trending regional/topic posts and suggested creators until they follow >=5 accounts.

Stage 7 - Lifecycle & Safety

Cold-Start & Instant Block Filter

0-Follow Cold UsersourceTrending Topic PoolcacheInstant Block/MuteSetrouterSafe Populated FeedsinkApply mute/block set

1.Instant Block Guarantee: Hydration-time block filtering takes effect in <1ms without waiting for ZSET pruning.

2.Follow Backfill: Following a new user backfills their last 10 posts asynchronously into your inbox ZSET.

Hydration-time block filtering and trending cold-start pools keep feeds safe and engaging.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why do large social networks switch from Fan-Out-on-Write (Push) to Fan-Out-on-Read (Pull) for celebrity accounts with >100K followers?

Recommended Learning Flow