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.
SETEX 45s) with online/offline hysteresis, paired with hybrid push/pull fan-out for small vs. massive channels.62^7 = 3.52T combinations), pairing collision-free writes with edge-cached HTTP 301/302 redirection.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.
Push Write-Amplification vs Pull Scatter-Gather
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.
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.
Celebrity Threshold Split & Read Merge
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.
- 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.
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?
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.
Parallel Batch Hydration Pipeline
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.
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.
L1 Retrieval + L2 Feature-Store Ranker
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.
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).
Seen-Post Bloom & Diversity Re-Ranker
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.
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.
Snapshot-Backed Opaque 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+.
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.
Cold-Start & Instant Block Filter
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: Make the trade-off yourself.
Why do large social networks switch from Fan-Out-on-Write (Push) to Fan-Out-on-Read (Pull) for celebrity accounts with >100K followers?