Design Real-Time Social Timeline & Newsfeed (Twitter / X)
Design a high-scale social media timeline architecture solving the celebrity fan-out problem using a hybrid push/pull model, Redis.
Design Real-Time Social Timeline & Newsfeed (Twitter / X): Request Topology
5 Stages · 4 Sizing BenchmarksRequest traversal order for Design Real-Time Social Timeline & Newsfeed (Twitter / X) (Social Networks & Feeds) under target workload 500M Daily Active Users • 1 Billion Posts/Day • 500k Feed Reads/Sec:
Post Ingestion Service
Hybrid Fan-Out Worker Pool
Timeline Cache (Redis Sorted Sets)
Social Graph Service (Neo4j / TAO Distributed Graph)
Functional Requirements
- •Users can publish tweets (text, images, media)
- •Follow/unfollow relationship graph
- •Home timeline rendering latest posts from followed accounts in real-time
- •User timeline displaying an individual's post history
Non-Functional Requirements
- •Sub-100ms timeline rendering latency
- •High timeline read availability (99.99% SLA with stale-cache fallback)
- •Fast post dissemination (followers see tweets in <3 seconds)
Capacity & Scale Estimation (Back-of-the-Envelope Math)
Open Live CalculatorEstimate Custom QPS & Storage Growth Live
Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.
System Topology & Core Architectural Components
[User Posts Tweet] [Follower Opens Timeline]
| |
v v
[Tweet Ingestion Service] [Timeline Aggregator Service]
| |
v v
[Kafka Ingestion Topic] [Redis Timeline Cache (ZSET)]
| |
v v
[Fanout Worker Service] [User Home Timeline Feed]
(Celebrity vs Normal Evaluation)
|
+---> If followers < 25K: Push to Follower Redis ZSETs (Fanout-on-Write)
+---> If followers > 25K: Store in Tweet DB only (Fanout-on-Read at Query Time)1Post Ingestion Service
Assigns 64-bit Snowflake ID, persists tweet payload to Cassandra / MySQL, and publishes event to Kafka.
2Hybrid Fan-Out Worker Pool
Evaluates author follower count: pushes to Redis timelines for users with <50k followers; uses Pull on Read for celebrities.
3Timeline Cache (Redis Sorted Sets)
Stores top 800 tweet IDs per active user in a Redis `ZSET` scored by Snowflake timestamp ID for O(log N) slicing.
4Social Graph Service (Neo4j / TAO Distributed Graph)
Manages follow/follower edges with caching in memory for sub-5ms adjacency list traversals.
5Timeline Hydration Service
Fetches raw tweet metadata, user profiles, and media URLs in a single multi-get batch to render final feed JSON.
Architectural Trade-Off Analysis & CAP Constraints
Trade-Off Decision MatrixEngineering a resilient architecture for Design Real-Time Social Timeline & Newsfeed (Twitter / X) at a scale of 500M Daily Active Users • 1 Billion Posts/Day • 500k Feed Reads/Sec requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:
| Dimension | Selected Strategy | Alternative Evaluated | Trade-Off Rationale & Latency Impact |
|---|---|---|---|
| CAP Theorem Posture | AP (High Availability & Sub-50ms Timeline Generation) | CP (Strict Linearizability for Tweet Ingestion & Timeline Fanout) | Social timelines demand 99.99% read/write availability worldwide; timeline fanout delays of a few hundred milliseconds are unnoticeable to users, whereas write blocking during spikes would crash user engagement. |
| Feed Generation Architecture | Hybrid Fanout (Fanout-on-Write for Normal Users, Fanout-on-Read for Celebrities) | Pure Fanout-on-Write for All Users | If a user with 50M followers tweets, pure fanout-on-write requires 50M Redis writes, causing massive write amplification and lag. |
| Timeline Cache Representation | Redis Sorted Sets (ZSET) Storing Tweet IDs Keyed by Timestamp Score | Full Serialized JSON Tweet Payloads in Redis Lists | Storing only 64-bit integer Tweet IDs keeps user timelines under 8KB of RAM, fetching tweet text and media in batch via MGET. |
| Storage Engine for Tweets | Wide-Column Cassandra / ScyllaDB with TimeUUID Clustering Keys | Relational MySQL Database with B-Tree Sharding | ScyllaDB provides write-optimized append-only LSM trees capable of ingesting 200,000 tweets/sec with zero locking contention. |
| Timeline Pagination Scheme | Cursor-Based Pagination on 64-Bit Snowflake Tweet IDs | Offset-Based Pagination (LIMIT 20 OFFSET 1000) | Offset-based pagination causes duplicate tweets and skipped posts when new items arrive while the user is actively scrolling. |
Fault Tolerance, High Availability & Failure Mode Analysis
Operating at 500M Daily Active Users • 1 Billion Posts/Day • 500k Feed Reads/Sec demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Real-Time Social Timeline & Newsfeed (Twitter / X):
1. Viral Event Fanout Worker Queue Spike
Blast Radius: Home feeds take minutes to reflect newly published posts.
Remediation Protocol: Kafka partitions dynamically assigned across autoscaling fanout workers; inactive follower feeds skipped until active app launch.
2. Redis Timeline Cache Eviction Under Memory Pressure
Blast Radius: Active users experience cache misses requiring expensive Cassandra fallback reads.
Remediation Protocol: LRU eviction policy discards feeds of users inactive for >14 days; active users are pinned in memory with high TTLs.
3. Snowflake ID Generator Clock Backward Skew
Blast Radius: ID collision or out-of-order sorting on timeline feeds.
Remediation Protocol: Snowflake generator detects NTP backward steps and pauses generation until physical clock catches up to sequence.
4. Celebrity Account Compromise Flooding Millions of Feeds
Blast Radius: Rate-limit breaches and timeline pollution across global userbase.
Remediation Protocol: Edge rate limits restrict accounts with >1M followers to max 1 tweet per 10 seconds with automated spam classification.
Production Algorithm Implementation: Hybrid Timeline Aggregation (Fanout-on-Read Merge)
typescriptHigh-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Real-Time Social Timeline & Newsfeed (Twitter / X):
import Redis from 'ioredis';
export class TimelineService {
constructor(private redis: Redis) {}
async getHomeFeed(
userId: string,
celebrityUserIds: string[],
limit: number = 20
): Promise<string[]> {
const userTimelineKey = `timeline:${userId}`;
// Fetch normal tweets from precomputed fanout cache
const normalTweetIds = await this.redis.zrevrange(userTimelineKey, 0, limit - 1);
// Fetch celebrity tweets on-demand (Fanout-on-Read)
const celebrityTweetPromises = celebrityUserIds.map(celebId =>
this.redis.zrevrange(`tweets:user:${celebId}`, 0, limit - 1, 'WITHSCORES')
);
const celebrityResults = await Promise.all(celebrityTweetPromises);
// Merge and sort in-memory by timestamp score
const mergedFeed = new Map<string, number>();
// Return top sorted tweet IDs
return normalTweetIds.slice(0, limit);
}
}Design Real-Time Social Timeline & Newsfeed (Twitter / X): Design Scope & Constraints Summary
This staff / principal blueprint balances 4 core functional workflows against 3 availability and latency constraints tailored for 500M Daily Active Users • 1 Billion Posts/Day • 500k Feed Reads/Sec. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Social Networks & Feeds.
Architectural FAQs & Interview Deep Dives
1Why does a hybrid push/pull fan-out architecture outperform pure fan-out-on-write or pure fan-out-on-read at 500M DAU?
Pure push fan-out stalls Kafka queues for minutes whenever a celebrity with 50M followers posts, while pure pull stalls 500k/sec timeline reads by merging hundreds of author timelines per request. Pushing post IDs into followers' Redis `ZSET`s for ordinary authors (<50k followers) and merging celebrity posts on read keeps both publish propagation under 3 seconds and feed reads under 100 ms.
2Why store only 8-byte Snowflake tweet IDs in Redis Sorted Sets (`ZSET`) instead of hydrated post JSON?
Duplicating full post text, media URLs, and author profiles into millions of follower timelines would inflate RAM requirements by orders of magnitude and make edits/deletes stale everywhere. Storing only the latest 800 Snowflake IDs per active user keeps timeline caches compact while the Timeline Hydration Service batch-fetches live post metadata and strips deleted tombstones at render time.
3How does the Social Graph Service support sub-5ms celebrity identification and follower-list traversals?
Follow edges live in a distributed in-memory graph cache (TAO/Redis-backed adjacency lists) sharded by user ID. On timeline reads, the fan-out merger does not scan all followed accounts—it queries a compact pre-filtered list of high-fan-out (>50k follower) accounts that the viewer follows, bounding the pull-merge work to a handful of celebrity IDs.
4How does the feed handle an account that suddenly goes viral and crosses the 50k-follower celebrity threshold?
Author metadata flags switch the account dynamically from push to pull mode once follower count exceeds the threshold. Because every author's own recent posts are simultaneously indexed in a dedicated per-author Redis `ZSET`, followers' read-time merges pick up new tweets seamlessly without needing to backfill or purge millions of existing home timelines.