CodeWithYash
DSA
Spring Boot
System Design
Series
Articles
Leaderboard
Sign In

Subscribe to Newsletter

Get the latest articles, DSA sheets, and system design challenges delivered to your inbox.

<CODEWITHYASH/>

The ultimate sanctuary for software engineers seeking deep mastery of core technical principles.

Library

  • Articles
  • DSA Sheets
  • Roadmaps

Connect

  • GitHub
  • LinkedIn
  • About
  • Contact

Legal

  • Privacy
  • Terms
  • Support

© 2026 CodeWithYash Global Systems.

Status: OperationalVersion: 4.2.0
System Design
OverviewTheory lessonsHLDLLD
All SeriesSeries
Distributed Systems

System Design Series

0%

0 of 33 topics completed

Progress
Scalable URL Shortener (TinyURL & Bitly)Theory
30 min
Planetary Distributed Rate Limiter (Cloudflare & Stripe)Theory
35 min
Pastebin & Ephemeral Blob StorageTheory
40 min
Social Timeline & Newsfeed (Twitter/X & Meta Feed)Theory
35 min
Global Real-Time Chat & Messaging (Discord & WhatsApp)Theory
35 min
High-Throughput Video Streaming & Ingestion (Netflix & YouTube)Theory
35 min
Ride-Sharing Proximity Dispatch (Uber & Lyft)Theory
35 min
Distributed Key-Value Store (Amazon Dynamo & Cassandra)Theory
45 min
Flash Sale & High-Concurrency Inventory ReservationTheory
35 min
Distributed Search Autocomplete & Typeahead EngineTheory
40 min
System DesignHigh-Level Design (HLD) Real-World Case StudiesSocial Timeline & Newsfeed (Twitter/X & Meta Feed)

Complex Systems · Phase 4: High-Level Design (HLD)

Social Timeline & Newsfeed (Twitter/X & Meta Feed)

Architect a planetary newsfeed supporting 500M DAU: Fanout-on-Write (push for normal users) vs Fanout-on-Read (pull for celebrities), hybrid fanout engines, and Redis timeline lists.

Primary specification: Timelines at Scale (Twitter Engineering)

Written & reviewed by Yash Patel 35 minBaseline 2026.1 Curated Blueprint· Verified 2026-09-14

Lesson 27 of 33

1d streak

The Architectural Question

When a celebrity with 80M followers posts, a naive fanout-on-write pushes 80 million timeline updates, creating a multi-minute queue backlog that delays messages globally.

Core Engineering Objectives

  • Fanout-on-Write (Push model): fast reads, but high write amplification for celebrity accounts
  • Fanout-on-Read (Pull model): zero write amplification, but expensive query-time aggregation
  • The Hybrid Fanout Engine: push for normal users (<5,000 followers) and pull dynamically for celebrities

Step 1: Problem Statement & Operational Context

Hybrid feed write and read flow
  1. 1. Author

    Publishes one canonical post.

  2. 2. Event log

    Buffers fan-out work and supports replay.

  3. 3. Fan-out workers

    Push normal-author post IDs into follower inboxes.

  4. 4. Feed service

    Pulls celebrity posts and merges ranked candidates.

  5. 5. Reader

    Receives a cursor-based page of hydrated posts.

Store post IDs in inboxes; hydrate current post data after ranking so edits and deletions remain manageable.

A planetary social newsfeed engine aggregates, ranks, and delivers personalized streams of content to hundreds of millions of daily active users (DAU). Every time a user opens their application, the feed must assemble a chronological or algorithmically curated sequence of recent posts authored by accounts they follow, complete with media attachments, reply counts, and engagement metrics.

The Core Asymmetric Fanout Dilemma

Posting a 280-character text tweet requires negligible compute and storage. However, delivering that post to followers creates extreme computational divergence. If a user with 50 followers posts, delivering the tweet requires 50 simple writes. If an account with 100 million followers (e.g., a global celebrity or world leader) posts, that single event triggers 100 million simultaneous timeline mutations. Without architectural safeguards, a single viral tweet crashes message queues and stalls timeline delivery for the entire platform.

Fanout-on-Write (Push Model)

When an author posts, a background worker proactively inserts the post ID into the pre-computed home timeline cache of every single follower. Reads are blazing fast (O(1)), but writes suffer massive amplification.

Fanout-on-Read (Pull Model)

When a user opens their timeline, the system dynamically queries the latest posts of everyone they follow and merges them in real time. Writes are O(1), but reads suffer severe computational and network fanout.

Hybrid Fanout Engine

The production standard (used by Twitter/X): push fanout is applied to normal users (<25,000 followers), while celebrity accounts bypass push fanout entirely and are merged dynamically at read time.

Step 2: Requirements (Functional & Non-Functional)

The timeline engine must deliver sub-150ms read latency while surviving extreme burst traffic during global live events.

CategoryRequirement SpecificationArchitectural Target
Functional: Post CreationUsers can post tweets (text up to 280 chars, images, video links)Write to sharded tweet DB + publish event to Kafka within <100ms
Functional: Home TimelineView chronological or algorithmic stream of followed accountsPre-computed Redis Sorted Sets (ZSET) merged with celebrity feeds
Functional: User Profile FeedView all historical tweets authored by a specific userQuery author-sharded database index with read-through caching
Functional: Social GraphFollow and unfollow users; block and mute accountsGraph edge cache (Meta TAO-style / Neo4j / Redis Graph) with fast neighbor lookups
Non-Functional: Read Latencyp99 home timeline delivery latency < 150msO(1) Redis ZREVRANGEBYSCORE lookups + parallel hydration
Non-Functional: Availability99.99% availability for timeline reading; 99.9% for postingActive-active multi-region deployment with stale cache fallbacks
Non-Functional: Scale300M DAU, 500M tweets/day, 50B daily timeline loads100:1 read:write ratio requiring aggressive in-memory caching
Non-Functional: ConsistencyEventual consistency for timeline updates (acceptable lag: <5s)Asynchronous Kafka consumer workers driving timeline fanout

Use it when

Adopt the Hybrid Fanout architecture when your social graph exhibits extreme power-law (Pareto) distributions where 0.1% of users possess millions of followers.

Reconsider when

Use pure Fanout-on-Read when all users have uniform follower counts (e.g., enterprise team collaboration tools like Slack or enterprise project boards) and write volume matches read volume.

Step 3: Detailed Back-of-the-Envelope Capacity Estimations

Back-of-the-envelope calculations determine the computational throughput, storage sizing, and memory working set required for 300M DAU.

Metric DimensionMathematical DerivationBaseline NumberPeak Load (2.5x)
Daily Active Users (DAU)Baseline given300,000,000 DAU350,000,000 DAU
Tweet Creation Volume500,000,000 tweets / 86,400 seconds~5,787 tweets/sec~14,500 tweets/sec
Timeline Read Volume3,000,000,000 timeline views / 86,400s (~10 views/DAU/day)~34,700 reads/sec~90,000 reads/sec
Read-to-Write Ratio3 Billion reads : 500 Million writes6 : 1Up to 30 : 1 during breaking global events
Average Follower CountIndustry average across platform~200 followers/userN/A (Power-law distributed)
Pure Push Write Amplification5,787 tweets/s * 200 followers1,157,400 writes/sec2,900,000 writes/sec to Redis
Tweet Record FootprintID (8B) + User (8B) + Text (200B) + Metadata (84B)~300 bytes~500 bytes with indexing
5-Year Storage (Metadata)500M * 365 days * 5 yrs * 300B~273.7 Terabytes~1.6 Petabytes with 3x replicas
Timeline Working Set (Redis)300M DAU * 800 tweet IDs * 8 bytes (ZSET)~1.92 Terabytes RAM~3.8 TB provisioned cluster RAM
Egress Bandwidth578,700 reads/s * 20 tweets/page * 300B~3.47 Gigabytes/sec~8.7 GB/sec (~70 Gbps)

Why Cache Only the Top 800 Tweet IDs Per User?

Retaining the newest 800 IDs per active user is an illustrative product assumption that bounds cache growth; production teams should choose the cutoff from observed scroll-depth and cold-read data. The raw ID payload is 800 * 8 bytes = 6.4 KB per user, but a Redis Sorted Set also stores scores, members, indexes, allocator overhead, keys, and replication. Treat 1.92 TB as a payload floor for 300 million users, then measure the actual representation before sizing the cluster.

Step 4: High-Level Architecture & Component Responsibilities

The system segregates tweet ingestion, asynchronous fanout processing, social graph queries, timeline caching, and feed hydration.

  1. 01Edge API Gateway: Terminates TLS, handles mobile auth tokens, and splits requests between Tweet Ingestion Service and Timeline Retrieval Service.
  2. 02Tweet Ingestion Service: Persists raw tweet payloads to sharded MySQL/Cassandra clusters, generates 64-bit Snowflake IDs, and publishes a TweetCreatedEvent to Apache Kafka.
  3. 03Social Graph Service (Meta TAO-style / Redis Graph): Stores bidirectional edge lists between followers and followees, caching graph associations in memory for fast neighbor lookups (get_followers(author_id)).
  4. 04Fanout Worker Fleet: Consumes TweetCreatedEvent from Kafka. Checks author follower count: if <25,000, writes tweet ID to Redis timeline:{follower_id} for all followers. If >=25,000, writes ONLY to the author's personal user_timeline:{author_id}.
  5. 05Timeline Service (Read Path): When a user loads their feed, the service fetches their cached Redis timeline, fetches recent tweets from celebrities the user follows, merges them in memory, and queries the Tweet Hydration Service.
  6. 06Tweet Hydration Service: Batches and resolves raw tweet content, author user profiles, and media metadata using multi-get queries against Redis and Memcached.
  7. 07ML Feed Ranker: Scores candidate tweets using feature extraction (recency, affinity, engagement probability) to generate the "For You" algorithmic timeline.

Decoupling Timeline Structure from Tweet Hydration

A critical design pattern is storing ONLY 64-bit tweet_id references inside Redis timeline lists—never full JSON tweet payloads. If a user edits or deletes a tweet, or changes their profile picture, storing full payloads would require mutating millions of follower timeline caches. Storing bare IDs keeps timelines compact and allows the Hydration Service to pull fresh, authoritative tweet data from cache in a single MGET call.

Step 5: Detailed Data Models & Storage Schema

Data modeling isolates immutable append-only tweet histories from mutable social graph relationships.

snippet.sqlsql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
-- PostgreSQL / CockroachDB Sharded Authoritative Tweet Storage
CREATE TABLE tweets (
    tweet_id BIGINT PRIMARY KEY,              -- 64-bit Snowflake ID (timestamp encoded)
    author_id BIGINT NOT NULL,                -- User ID of author
    content VARCHAR(280) NOT NULL,            -- UTF-8 text
    media_urls JSONB NULL,                    -- Array of S3 / CDN media asset links
    reply_to_tweet_id BIGINT NULL,            -- Parent tweet ID if thread
    retweet_count INT NOT NULL DEFAULT 0,
    like_count INT NOT NULL DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL
);

-- Sharded by author_id to colocate an author's tweets on a single storage node
CREATE INDEX idx_tweets_author_created ON tweets (author_id, created_at DESC);

-- Social Graph Relationship Table (TAO Edge Model / PostgreSQL)
CREATE TABLE user_follows (
    follower_id BIGINT NOT NULL,              -- The user who is following
    followee_id BIGINT NOT NULL,              -- The user being followed
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (followee_id, follower_id)    -- Composite PK optimized for "get_followers"
);

CREATE INDEX idx_user_follows_reverse ON user_follows (follower_id, followee_id);

Architectural Boundary · Do Not Confuse

Concept A

Fanout-on-Write (Push Model)

Concept B

Fanout-on-Read (Pull Model)

Push creates instant, zero-latency reads (O(1) Redis fetch) but burns massive CPU and queue capacity when high-follower accounts post. Pull generates zero write amplification (O(1) write) but forces the read path to execute hundreds of network queries across followed accounts, causing high p99 read latency.

Step 6: Core Algorithms & Step-by-Step Request Flows

The hybrid fanout algorithm dynamically routes posts based on the author's follower threshold and executes an in-memory k-way merge sort upon read.

snippet.typescripttypescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Production Hybrid Timeline Aggregator & K-Way Merge
export interface TweetSummary {
  tweetId: bigint;
  authorId: bigint;
  timestamp: number;
}

const CELEBRITY_FOLLOWER_THRESHOLD = 25000;

export class TimelineService {
  // FANOUT WORKER WRITE PATH
  async onTweetPublished(tweet: TweetSummary, followers: bigint[]): Promise<void> {
    // Always write to author's own profile timeline
    await redis.zadd(`user_timeline:${tweet.authorId}`, tweet.timestamp, tweet.tweetId.toString());

    if (followers.length >= CELEBRITY_FOLLOWER_THRESHOLD) {
      // CELEBRITY: Bypass push fanout! Zero follower updates written.
      console.log(`Celebrity post detected for user ${tweet.authorId}. Bypassing push fanout.`);
      return;
    }

    // NORMAL USER: Push tweet ID into every follower's home timeline ZSET in batches
    const pipeline = redis.pipeline();
    for (const followerId of followers) {
      const key = `home_timeline:${followerId}`;
      pipeline.zadd(key, tweet.timestamp, tweet.tweetId.toString());
      pipeline.zremrangebyrank(key, 0, -801); // Retain top 800 items
    }
    await pipeline.exec();
  }

  // TIMELINE READ PATH
  async getHomeTimeline(
    userId: bigint,
    followedCelebrities: bigint[],
    limit: number = 20,
    maxId?: bigint
  ): Promise<string[]> {
    // 1. Fetch normal pre-computed timeline from Redis ZSET
    const normalTweets = await redis.zrevrangebyscore(
      `home_timeline:${userId}`,
      maxId ? (maxId - 1n).toString() : '+inf',
      '-inf',
      'LIMIT', 0, limit
    );

    // 2. Concurrently fetch top tweets from all followed celebrities
    const celebrityPipelines = redis.pipeline();
    for (const celebId of followedCelebrities) {
      celebrityPipelines.zrevrangebyscore(
        `user_timeline:${celebId}`,
        maxId ? (maxId - 1n).toString() : '+inf',
        '-inf',
        'LIMIT', 0, limit
      );
    }
    const celebrityResults = await celebrityPipelines.exec();

    // 3. In-Memory K-Way Merge Sort across normal timeline and celebrity feeds
    const allCandidateIds: bigint[] = normalTweets.map((id) => BigInt(id));
    for (const [, tweetList] of celebrityResults ?? []) {
      if (Array.isArray(tweetList)) {
        for (const id of tweetList) allCandidateIds.push(BigInt(id));
      }
    }

    // Sort by the course's chosen cursor key. Snowflake IDs are roughly time ordered,
    // but cross-worker clock skew means they are not a perfect global chronology.
    allCandidateIds.sort((a, b) => (b > a ? 1 : b < a ? -1 : 0));

    // Return the top N requested tweet IDs for hydration
    return allCandidateIds.slice(0, limit).map((id) => id.toString());
  }
}
  1. 01Step 1 (Ingestion): User posts tweet. Tweet Ingestion Service writes to DB and emits Kafka event.
  2. 02Step 2 (Fanout Evaluation): Worker fetches author follower count from Social Graph Service. If <25k, batches ZADD commands to follower timelines. If >=25k, writes only to author profile.
  3. 03Step 3 (Timeline Read Request): Client calls GET /api/v1/timeline/home?limit=20. API Gateway routes to Timeline Service.
  4. 04Step 4 (Hybrid Merge): Timeline Service pulls cached follower timeline from Redis AND queries recent tweets from followed celebrities. Merges streams in memory in <3ms.
  5. 05Step 5 (Batch Hydration): Passes 20 tweet IDs to Hydration Service. Hydration Service performs a multi-key MGET against Memcached cluster, assembling tweet text, media, author details, and like counts.
  6. 06Step 6 (Response Delivery): Fully materialized JSON response returned to client in <80ms total p99 latency.

Step 7: Deep Dives into Critical Bottlenecks

The Offset Pagination Disaster on Live Feeds

Never use SQL OFFSET / LIMIT (e.g. OFFSET 20 LIMIT 20) for live timelines. As authors publish new tweets at the top of the feed, all existing tweets shift downward in index rank. By the time the user scrolls down and requests page 2, the top 5 tweets from page 1 have shifted into page 2, causing annoying duplicate tweets to render. Always implement Cursor-Based Pagination using the 64-bit Snowflake ID (WHERE tweet_id < max_id ORDER BY tweet_id DESC LIMIT 20), which is completely invariant to insertions at the head.

Inactive User Cache Eviction & Lazy Reconstruction

Fanning out tweets to users who haven't logged in for months wastes immense memory and write compute. Production systems set a 14-day TTL on Redis timeline keys. If an inactive user returns after 6 months, their cache key is empty. The Timeline Service catches the cache miss, queries the social graph for followed users, pulls their latest tweets, reconstructs the 800-tweet timeline in the background, and caches it in Redis.

Step 8: Real-World Production War Stories

Twitter: Timelines as Materialized Data

Twitter Engineering described home timelines as materialized collections of Tweet IDs stored for fast retrieval, followed by hydration of those IDs into complete posts. This reframes feed generation from a large read-time join into an asynchronous fanout and cache-maintenance problem. The reusable lesson is the separation between candidate-ID storage and object hydration—not an assumption that every product should copy one company's thresholds.

Failure Exercise: A Celebrity Fanout Storm

Suppose one post must be inserted into tens of millions of follower timelines. A pure push design creates that many cache mutations and can delay unrelated fanout work. Exempt very large accounts from push, merge their recent posts on read, partition queues by workload class, and measure queue age rather than only queue length. This is an illustrative stress scenario, not an attributed account of a specific event.

Step 9: Interviewer Deep-Dive Gauntlet & Active Recall

Deep-Dive Q1: Why use a unique cursor key instead of only a raw millisecond timestamp?

Model Answer: Multiple posts can share the same millisecond timestamp, so a timestamp alone is not a unique pagination boundary. A Snowflake-style ID combines time, worker identity, and a per-millisecond sequence to produce unique, roughly time-ordered IDs. Twitter describes Snowflake as k-sorted rather than a perfect global clock: clock skew and independent workers mean it must not be presented as absolute event chronology. If exact order is a product invariant, define a stable composite cursor such as (rank_time, unique_id) or use a scoped sequencer.

Deep-Dive Q2: When a user unfollows someone, how do you remove their historical tweets from the follower's timeline without an expensive scan?

Model Answer: Scanning an 800-entry Redis ZSET, checking the author of every single tweet against the unfollowed user ID, and calling ZREM introduces high latency and lock contention. Production systems use Lazy Tombstone Filtering: 1) The unfollow event is committed immediately to the Social Graph Service. 2) The Redis timeline is left completely untouched! 3) When the user fetches their timeline, the Hydration Service retrieves the 20 candidate tweet IDs and checks the author IDs against an in-memory set of the user's active followings/mutes/blocks. Any tweet authored by the unfollowed account is discarded during hydration, and replacement items are pulled seamlessly.

Deep-Dive Q3: How does the two-stage machine learning ranking pipeline (Light Ranker vs. Heavy Ranker) prevent timeline latency spikes?

Model Answer: Running a deep neural network (Heavy Ranker with hundreds of millions of parameters) over thousands of candidate tweets for 300 million users would require prohibitive GPU infrastructure and take over 1,000ms per request. The system splits ranking into two phases: 1) Candidate Retrieval & Light Ranker: Pulls 800 candidate tweets from Redis and applies lightweight linear models / gradient boosted trees (GBDT) evaluating simple signals (recency, author affinity) in <10ms, pruning the list to the top 50 candidates. 2) Heavy Ranker: The comprehensive deep learning model scores only those 50 candidates, evaluating complex multi-task engagement probabilities (p(Like), p(Retweet), p(Click)) in <30ms.

Deep-Dive Q4: How do you prevent cache stampedes when an inactive user with 2,000 followees suddenly opens the mobile app after 6 months?

Model Answer: For an inactive user whose Redis timeline has expired, querying 2,000 followed accounts synchronously during the initial HTTP request would blow past the 150ms SLA and risk database timeouts. Mitigations include: 1) Asynchronous Background Warming: When the user enters the mobile app splash screen or sends a push notification acknowledgment, a background worker initiates timeline reconstruction before the user views the feed. 2) Fast Fallback to Top-K Celebrities: If the timeline is cold, immediately serve the latest 20 tweets from the user's top 5 most engaged followed accounts in <20ms while an asynchronous task rebuilds the full 800-tweet timeline. 3) Singleflight Request Coalescing: Ensure only one worker reconstructs the timeline if the user refreshes repeatedly.

Active Recall Checkpoint

Calculate the write amplification factor when a user with 50 million followers publishes a tweet under a pure Fanout-on-Write (Push) architecture.

Hint: Consider how many Redis write operations must be executed for a single tweet.

Show answer & explanation

Under pure Fanout-on-Write, a single post triggers 50,000,000 individual timeline write operations to Redis. If a cluster sustains 50,000 writes/sec, that single post monopolizes cluster write capacity for 1,000 seconds (~16.6 minutes), proving why pure push fails for celebrity accounts.

Active Recall Checkpoint

Why does cursor-based pagination using Snowflake IDs eliminate duplicate posts during live timeline scrolling?

Hint: Compare against SQL LIMIT and OFFSET mechanics.

Show answer & explanation

SQL OFFSET relies on positional indexing; new incoming tweets push older tweets into higher offset ranks, causing page 2 to re-fetch items already seen on page 1. Cursor pagination filters by value (WHERE tweet_id < last_seen_id), ensuring deterministic reads independent of new items arriving at the top.

Hardware Bounds & Sizing Math

Topic sizing snapshot

The four numbers that materially affect this architecture. Use them as bounds, not as a generic calculator embedded in every lesson.

Peak QPS

70,000 Feed Read RPS / 12,000 Tweet Write RPS

5-Yr Storage

180 TB tweet metadata & text over 5 years

Bandwidth

15 Gbps feed egress bandwidth

Working Set RAM

400 GB Redis cluster caching 800-tweet timelines for 50M daily active users

Engineering Decision Matrix

Architectural Trade-Off Analysis

Compare latency, throughput, consistency, and operational complexity across core industry alternatives.

Architectural Trade-Off Matrix

Architecture Decision Matrix

Multi-axis engineering evaluation and FAANG interview rules of thumb.

Option A

SQL (Postgres / MySQL)

Relational ACID Store

Structured schema, relational joins, ACID transactions, and strict foreign keys.

Option B

NoSQL (Cassandra / DynamoDB)

Distributed Non-Relational Store

Horizontal partition keys, denormalized documents/wide-columns, and tunable consistency.

Evaluation AxisSQL (Postgres / MySQL)NoSQL (Cassandra / DynamoDB)Details
Latency
Moderate Strong
Throughput
Moderate Strong
Scalability
Moderate Strong
Consistency
Strong Moderate
Complexity
Strong Moderate
Cost
Moderate Strong
FAANG Interview Rule of Thumb

When to Choose in an Architecture Interview

Pick SQL (Postgres / MySQL) If:

Choose SQL when ACID guarantees are non-negotiable (financial ledgers, payment processing, inventory checkout) or when query access patterns are unpredictable and require ad-hoc analytical joins.

Pick NoSQL (Cassandra / DynamoDB) If:

Choose NoSQL when write volume exceeds single-node capacity (>20K writes/sec), data is unstructured/hierarchical (logs, telemetry, user feeds), or multi-region active-active replication is mandatory.

Examiner Trap to Avoid:

Never say "NoSQL is faster than SQL" without qualification. SQL with proper B-Tree indexes on indexed primary keys is lightning fast. NoSQL wins on horizontal write scaling, not inherent single-row read speed.

Production Postmortem & Verification

Production Incident Postmortem

  1. Trigger / Setup: A platform uses pure Fanout-on-Write; a soccer star with 90M followers posts a goal celebration.
  2. Production Symptom: Message queues back up with 90 million write tasks; message delivery for all other users is delayed by 45 minutes.
  3. Root Cause & Fix: Use a hybrid fanout model; do not fan out celebrity posts to follower timelines. Merge celebrity posts dynamically at read time.

Acceptance Criteria & Outcomes

  • Quantify write amplification math for push vs pull across normal and celebrity follower distributions.
  • Design Redis timeline data structures (ZSET with timestamp as score, capped at 800 items).
  • Implement cursor-based pagination to eliminate duplicate items across shifting feed timelines.

End-of-Chapter Synthesis & Key Takeaway

Social Timeline & Newsfeed (Twitter/X & Meta Feed) is built around one fundamental rule: Establish clear responsibility and explicit trade-offs.. Before adding components, establish explicit quantitative SLAs for latency, throughput, and consistency. Choose the simplest architecture that meets stated constraints.

Architectural & Technical Interview Review

Core FAANG Interview Questions

3 Questions
Q01
How do you justify introducing Social Timeline & Newsfeed (Twitter/X & Meta Feed) into a high-scale production architecture?
Click to reveal model answer →Hide answer ↑Requirements & Design Brief

Introduce Social Timeline & Newsfeed (Twitter/X & Meta Feed) only when measured scale, data size, or failure boundaries exceed single-node capacity. State the exact bottleneck, evaluate operational overhead, and verify that the trade-offs justify the added moving parts.

Source section: Requirements & Design Brief
Q02
What is the primary trade-off and hidden operational cost of Social Timeline & Newsfeed (Twitter/X & Meta Feed)?
Click to reveal model answer →Hide answer ↑Architecture Trade-offs

It improves scalability and availability, but introduces network hops, serialization overhead, and eventual consistency or coordination complexity.

Source section: Architecture Trade-offs
Q03
How do you handle catastrophic failure or dependency degradation in Social Timeline & Newsfeed (Twitter/X & Meta Feed)?
Click to reveal model answer →Hide answer ↑Failure Review & Recovery

Implement connect/read timeouts, exponential backoff with jitter, and fallback defaults so downstream degradations do not cause cascading outages.

Source section: Failure Review & Recovery

Production Pitfalls & Anti-Patterns

Critical Failure Anti-Patterns

!

Premature Distributed Complexity

Scattering distributed components before identifying concrete write, read, or storage limits creates accidental points of failure and operational debt.

Production Mitigation: Start with the simplest modular design that satisfies requirements, evolving it only as measured constraints dictate.

!

Unbounded Retries and Cascading Storms

When a dependency degrades, immediate synchronized retries multiply downstream traffic, turning a minor slowdown into a total fleet outage.

Production Mitigation: Enforce strict retry budgets, exponential backoff, and full randomized jitter on all client calls.

!

Neglecting Observability and Metrics

Deploying architecture without distributed tracing or p99 tail latency alerts leaves engineers blind when partial partitions occur.

Production Mitigation: Export metrics for request rate, error rate, p95/p99 duration, and saturation at every service boundary.

Primary Documentation & Specifications

Timelines at Scale (Twitter Engineering)Twitter Engineering: Announcing Snowflake
Previous LessonPastebin & Ephemeral Blob StorageHigh-Level Design (HLD)Next LessonGlobal Real-Time Chat & Messaging (Discord & WhatsApp)High-Level Design (HLD)

In this chapter

01Architectural Question02Step 1: Problem Statement & Operational Context03Step 2: Requirements (Functional & Non-Functional)04Step 3: Detailed Back-of-the-Envelope Capacity Estimations05Step 4: High-Level Architecture & Component Responsibilities06Step 5: Detailed Data Models & Storage Schema07Step 6: Core Algorithms & Step-by-Step Request Flows08Step 7: Deep Dives into Critical Bottlenecks09Step 8: Real-World Production War Stories10Step 9: Interviewer Deep-Dive Gauntlet & Active Recall11Sizing Snapshot12Trade-Off Analysis13Production Verification14Synthesis & Review15Primary References

Chapter promise

Fanout-on-Write (Push model): fast reads, but high write amplification for celebrity accounts