StackMonkey
Home / Templates / News Feed

Designing a Scalable Social Timeline & Hybrid Fan-Out Engine

A production-grade news feed must serve cached timelines in sub-100ms while ingesting tens of thousands of new posts every second. Learn how to solve the celebrity fan-out bottleneck using hybrid push-pull architectures, Redis sorted sets, and asynchronous queue dispatching.

Daily Active Users
300M DAU
30B feed queries / day
Peak Timeline Read QPS
350,000 req/s
Sub-50ms cache hits
Post Write Ingress
35,000 req/s
300M new posts daily
Timeline Latency SLA
< 150 ms
p99 initial 20 posts
Step 1 of 4

Capacity Math: Read Heavy 100:1 Asymmetry

Timeline consumption outpaces timeline generation by orders of magnitude. The system must optimize ruthlessly for the read path while preventing fan-out write amplification from overwhelming worker message brokers.

Read & Write QPS Calculations

  • 1. Read Throughput: 300M active users open their feed an average of 10 times daily = 3B total timeline fetches. Baseline average: 3B / 86,400s = 34,700 QPS. Peak load multiplier (10x during viral breaking news) = 350,000 QPS.
  • 2. Write Throughput: 300M posts created daily = 3,470 write QPS average. Peak ingress reaches 35,000 QPS.
  • 3. Fan-Out Amplification: Average user has 200 followers. Standard fan-out requires 3,470 * 200 = 694,000 queue writes/s. Celebrity users with 20M followers would require 20M writes for a single tweet, crashing standard worker queues.

Timeline Cache Memory Footprint

  • 1. Per-User Cache Entry: Rather than caching full post blobs, timelines store only 800 recent post_ids (64-bit integer, 8 bytes) scored by epoch millisecond timestamp in a Redis Sorted Set (ZSET).
  • 2. Storage Per Timeline: 800 posts * (8 bytes ID + 8 bytes score + 24 bytes overhead) ≈ 32 KB per user timeline.
  • 3. Active Working Set: 300M DAU * 20% high-frequency active cohort = 60M cached active timelines. 60M * 32 KB = 1.92 TB RAM. A modest 16-node Redis cluster with 128 GB RAM per node comfortably holds the hot timeline state.
Step 2 of 4

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

Neither pure push nor pure pull scales across asymmetric follower distributions. The production solution is a hybrid architecture that dynamically splits user models based on follower thresholds.

Strategy Read Complexity Write Complexity Failure Mode Production Suitability
Fan-Out on Write (Push) O(1) Redis ZREVRANGE O(N) where N = followers Celebrity write stalls workers; million-follower users trigger backpressure. Ordinary users only (< 25k followers)
Fan-In on Read (Pull) O(M log M) multi-merge O(1) single DB insert High p99 latency; database read amplification degrades cluster under traffic spikes. Celebrities only (> 25k followers)
Hybrid Push-Pull (Recommended) O(1) + O(K) celebrity merge O(N) capped at 25k Requires aggregator proxy layer to merge timeline cache with celebrity feeds. Standard for Twitter / Instagram / Threads

The Celebrity Ingestion Algorithm

When an ordinary user (e.g. 300 followers) posts, async worker queues fan out the post ID directly into each follower's Redis timeline. When a celebrity user (> 25,000 followers) posts, the write fan-out is skipped entirely. Instead, the post is saved only to the celebrity's public post list. When a follower requests their feed, the Aggregator Service pulls their cached timeline and merges the recent posts of any celebrities they follow on the fly using a multi-way k-merge in memory.

# Feed Request Execution Path:
1. Fetch base timeline: cached_ids = redis.zrevrange("timeline:" + user_id, 0, 100)
2. Identify followed celebrities: celebs = db.get_user_celebrities(user_id)
3. Fetch recent celebrity posts: celeb_ids = redis.mget(["posts:" + c for c in celebs])
4. In-memory k-way heap merge by timestamp: final_feed = merge_sorted(cached_ids, celeb_ids)[:20]
5. Hydrate post metadata from Redis MGET / PostgreSQL read replica
Step 3 of 4

Queue Explosion & Little's Law Saturation

Why naive message brokers collapse during major world events. See the mathematical breaking point where queue backlog becomes insurmountable.

The M/M/c/K Ingestion Collapse

Suppose a background task queue has c = 200 workers, each taking an average service time of 1/μ = 2ms to execute a timeline ZADD. Maximum sustainable processing rate is c * μ = 100,000 tasks/s.

During an unexpected global live event, 5 popular accounts post simultaneously, generating 2,500,000 fan-out write tasks in 500ms. Inflow rate λ = 5,000,000 tasks/s exceeds capacity by 50x.

Utilization ρ = λ / (c * μ) = 50.0. By queueing fundamentals, when ρ > 1, queue length L_q grows linearly toward buffer capacity K. Once buffer fills, queue drops tasks, causing silent timeline desynchronization and missing posts.

Production Mitigation Strategies
  • Follower Threshold Capping: Strictly exclude accounts with > 25k followers from the write fan-out pipeline.
  • Active User Filtering: Do not fan-out to followers who have not opened the application in over 14 days. Populate their timelines lazily on login.
  • Priority Queue Partitioning: Separate instant fan-out queues for friends and close contacts from broad public distribution queues to ensure personal notifications remain fast.
Step 4 of 4

Six-Tier Distributed Architecture

The complete component architecture required to maintain sub-150ms p99 latency across 300 million daily active users.

01 · Edge Ingress & Auth
Envoy / Kong API Gateway
Terminates TLS, validates JWT tokens, applies token-bucket rate limits per client IP, and routes feed requests directly to the read aggregator service.
02 · Post Publishing Service
Go / Rust Ingestion Pods
Validates content length, extracts media references, generates 64-bit snowflake ID, and writes post metadata to primary database and Kafka post-created topic.
03 · Async Fan-Out Pipeline
Kafka + Distributed Go Workers
Queries social graph for author's followers. Evaluates follower counts and partitions batches of 1,000 follower IDs to execute pipelined Redis ZADD commands.
04 · In-Memory Timeline Cache
Redis Cluster (Sharded ZSETs)
Stores capped 800-element sorted sets per active user. Serves `ZREVRANGEBYSCORE` queries in sub-5ms with zero relational database disk I/O.
05 · Read Aggregator & Hydration
Timeline Aggregator Proxy
Executes hybrid merge of user's Redis timeline with active celebrity feeds. Batch-hydrates author profiles, media URLs, and like counts via multi-get cache.
06 · Persistent Post & Graph Store
PostgreSQL / ScyllaDB + S3
Durable source of truth partitioned by user ID and timestamp. Raw post text stored in wide-column tables; attached images/videos streamed via CDN backed by S3.
Interactive Discrete Event Simulation

Simulate the News Feed Topology Live

Test push vs pull fan-out trade-offs, trigger celebrity follower posting storms, and observe queue length escalation before tuning worker pool concurrency.