System Design Problem

Design a News Feed System (Facebook / Instagram)

Commonly Asked By:MetaTwitterLinkedInByteDance

Interview Setup

Interview Prompt

Design a scalable news feed system similar to Facebook or Instagram. Users follow other accounts, create multimedia posts, and view a personalized home feed populated with recent and relevant content from followed creators. The system must support high read-to-write ratios, infinite scroll pagination, ranking layers, and high-follower celebrity accounts.

Clarifying Questions (ask before designing)

QuestionWhy it matters
Should the feed be strictly reverse-chronological or ranked by engagement relevance?Reverse-chronological feeds execute fast sorted set merges, whereas ranked feeds require a two-stage candidate retrieval and scoring pipeline.
What does the follower distribution look like across the user base?High-follower celebrity accounts with millions of followers create massive write amplification under naive push models, necessitating a hybrid fan-out architecture.
What is the expected read-to-write ratio and acceptable feed staleness window?A typical 100:1 read-to-write ratio with a 5-second staleness tolerance allows asynchronous queue decoupling and precomputed timeline caching.
What content types are supported: plain text only or rich media attachments?Media attachments require separate object storage uploads and CDN edge caching, storing only lightweight pointer references in feed caches.

Scope

In scope

  • Post creation and reliable asynchronous fan-out to follower timelines using a transactional outbox
  • Home timeline feed retrieval API with opaque cursor pagination supporting both chronological and ranked modes
  • Celebrity high-fanout isolation using adaptive hybrid push and pull strategies
  • Two-phase ranking layer integration with bounded candidate generation and ML scoring
  • Social graph relationship storage with low-latency caching and authoritative persistence

Out of scope (state explicitly)

  • Offline ML ranking model training pipelines
  • Ephemeral stories and short-form video streaming infrastructure
  • Nested comment thread tree generation

Functional Requirements

Core architecture patterns for social timeline generation. For tweet-length variations with retweet mechanics and list feeds, review Design Twitter Timeline and Search.

  • Users can create multimedia posts containing text, images, videos, and external hyperlinks.
  • Users can follow or unfollow other accounts to curate their personal social graph.
  • The system generates a personalized home feed showing recent, relevant posts from followed accounts.
  • Feeds support infinite scroll navigation powered by cursor-based pagination across chronological and ranked views.
  • Newly published posts appear in follower feeds in near real time (within 5 seconds).
  • Users can interact with posts through likes, comments, and re-sharing workflows.

Non-Functional Requirements

Feed systems are overwhelmingly read-heavy, demanding sub-200 ms latency and high availability even during viral surges.

  • Low Latency: Serve home feed read requests in under 200 ms at p99, and under 100 ms for reverse-chronological feeds.
  • High Availability: Maintain 99.99% service availability with graceful degradation during downstream component failures.
  • Massive Scalability: Support 500 million daily active users generating over 5 billion daily feed requests.
  • Eventual Consistency: Tolerate slight propagation delays (up to a few seconds) for new posts to materialize across follower feeds.
  • Read-Heavy Optimization: Optimize for a 100:1 read-to-write ratio where timeline reads dominate system resource utilization.
  • Relevance Ranking: Support personalized relevance scoring to maximize user engagement over purely chronological ordering.

Capacity Estimations

Evaluating write amplification across follower graphs determines whether push, pull, or hybrid fan-out architectures are required.

MetricCalculationValue
Daily active users (DAU)Given product assumption500M
New posts created daily500M DAU x 0.2 posts per user100M (~1,157 posts / sec avg)
Daily feed views500M DAU x 10 views per user5B (~57,870 reads / sec avg, peak 3x: ~175K / sec)
Average followers per userProduct distribution assumption200 followers
Average post metadata sizeText, media links, and author pointers1 KB
Timeline cache size per user500 post pointers x 16 bytes8 KB per active user
Daily fan-out writes (pure push model)100M posts x 200 followers20B writes per day
Average fan-out write throughput20B writes ÷ 86,400 seconds~231,481 writes / sec

Throughput and Storage Sizing Details

  • Post Creation Throughput: 100 million daily posts average roughly 1,157 posts per second, peaking at approximately 3,500 posts per second during major events.
  • Feed Read Throughput: 5 billion daily feed requests average roughly 57,870 reads per second, with peak traffic exceeding 175,000 requests per second.
  • Fan-Out Write Amplification: Under a naive push model, 100 million posts with 200 followers produce 20 billion timeline writes daily (~231,481 writes/sec). A single celebrity with 50 million followers would trigger 50 million writes for a single post, demonstrating why an adaptive hybrid approach is mandatory.
  • Feed Cache Storage: Caching 500 post pointers (8 bytes each) plus metadata (8 bytes) consumes roughly 8 KB per user. For 300 million active users, timeline caches require approximately 2.4 TB of RAM in Redis.

Architecture Diagram

Interview strategy: Frame the fan-out trade-off before drawing service boxes. Explain how an adaptive hybrid model isolates high-follower accounts from standard creator pipelines to eliminate write amplification storms while maintaining fast feed generation.

The architecture separates the synchronous write ingestion path from the asynchronous fan-out engine and read aggregation pipeline. When a user creates a post, the Post Service persists the post record and an outbox event atomically in MySQL in a single database transaction.

An asynchronous Outbox Publisher relays events to Kafka with at-least-once delivery guarantees. Fan-out workers evaluate the creator's follower count against an adaptive threshold. For standard creators (typically under 10,000 followers), workers push post ID pointers into follower Redis sorted sets. For high-follower celebrity accounts, fan-out on write is bypassed, and the Feed Service instead pulls a bounded candidate window of celebrity posts dynamically at read time to merge with the precomputed feed before ranking.

Loading...

Core Fan-Out Architectural Strategies

1. Fan-Out on Write (Push Model)

  • Mechanism: When a post is published, workers immediately insert the post ID into every follower's Redis feed cache.
  • Advantages: Precomputes feed candidates so the Feed Service avoids querying and merging hundreds of normal creator timelines at request time.
  • Disadvantages: Massive write amplification for celebrity accounts and wasted storage for inactive followers who never open the app.
  • Target Use Case: Standard accounts with typical follower counts.

2. Fan-Out on Read (Pull Model)

  • Mechanism: Posts are stored only in the author's timeline. When a user requests their feed, the system queries all followed accounts and merges their recent posts at runtime.
  • Advantages: Zero write amplification and zero wasted storage for inactive users.
  • Disadvantages: Higher read latency and database CPU overhead caused by querying many timelines simultaneously.
  • Target Use Case: Celebrity accounts with millions of followers and users who follow very few accounts.

3. Hybrid Fan-Out Architecture ⭐ (Industry Standard)

  • Standard Accounts: Use fan-out on write to precompute follower timelines.
  • Celebrity Accounts: Use fan-out on read, fetching a bounded set of recent celebrity posts on demand at feed read time.
  • Adaptive Classification Engine: Evaluates follower count, posting frequency, audience activity, and worker queue lag to dynamically classify creators.

Component Deep Dives

Detailed analysis of post ingestion with transactional outbox reliability, asynchronous fan-out processing, social graph adjacency lookups, timeline caching, and machine learning ranking pipelines.

Post Ingestion Service and Transactional Outbox

The Post Service handles post creation, schema validation, media asset references, and privacy configurations before persisting records to the database.

  • Atomic Ingestion: Persists the post record into MySQL sharded by user_id and simultaneously inserts an event record into a local post_outbox_events table within the same database transaction. This prevents the failure window where a database write succeeds but the service crashes before publishing to Kafka.
  • Reliable Dispatch: An asynchronous Outbox Publisher or change data capture (CDC) process reads pending outbox events, dispatches them to Kafka with at-least-once delivery guarantees, and marks them as published upon broker acknowledgment.
  • Media Processing: Validates image and video upload receipts stored in Amazon S3, attaching CDN delivery URLs to the post metadata.

Fan-Out Service and Worker Fleet

The Fan-Out Service consumes events from Kafka and coordinates the distribution of post pointers into follower timeline caches.

  • Follower List Resolution: Queries the Social Graph Service to retrieve follower lists in paginated chunks, avoiding loading millions of graph edges into worker memory simultaneously.
  • Adaptive Routing: For creators below the adaptive celebrity threshold (such as 10,000 followers), workers pipeline Redis ZADD commands to follower sorted sets. For high-follower creators, the write-time push step is bypassed.
  • Idempotent Processing: Because Kafka can deliver events more than once, workers rely on the unique member property of Redis sorted sets (post_id) to ensure re-delivered events update scores rather than creating duplicates. Offsets are committed only after successful Redis pipeline execution.
  • Inactive User Optimization: When fan-out queue lag rises, workers can defer or shed write-time materialization for accounts that have been inactive for over 30 days. When an inactive user returns, their timeline is dynamically backfilled at read time.

Social Graph Service

The Social Graph Service manages bidirectional follow relationships and provides low-latency adjacency list queries.

  • In-Memory Caching: Redis sets store following:{user_id} and followers:{user_id} for microsecond lookups of active social graphs.
  • Durable Source of Truth: Cassandra and relational tables persist follow relationships partitioned by user_id, guaranteeing durable relationship storage and supporting paginated retrieval for large follower graphs.

Feed Assembly and Candidate Generation Service

The Feed Service coordinates feed retrieval requests, combining precomputed timelines with dynamic celebrity candidate pools.

  • Precomputed Timeline Fetch: Retrieves top candidate post IDs from the user's Redis sorted set.
  • Bounded Celebrity Pull: Queries the Social Graph Service for followed high-follower accounts and retrieves a strictly bounded set of recent posts (for example, the top 10 recent posts per celebrity within a 24-hour window) from edge caches or author timelines.
  • Merge and Deduplication: Merges precomputed and pulled post IDs, deduplicating any overlapping entries.
  • Visibility and Validity Filtering: Enforces the core rule that timeline membership is not final authorization to view a post. It filters out deleted posts, moderated content, private posts no longer accessible, and posts from blocked or muted accounts before ranking.
  • Hydration and Response: Passes filtered candidates to the Ranking Service, hydrates full post metadata from cache or database for the top selected items, and returns the response with a pagination cursor.

Machine Learning Ranking Service

The Ranking Service scores candidate posts to personalize feed ordering based on predicted engagement probability.

  • Candidate Pool: Accepts a bounded candidate pool of approximately 500 post IDs from the Feed Service.
  • Feature Extraction: Retrieves user affinity scores, post age decay, content modality preferences, and engagement velocity from an in-memory feature store.
  • Inference Engine: Executes lightweight scoring models (such as logistic regression or gradient boosted decision trees) to rank candidates.
  • Resilience Fallback: If the ranking model exceeds a 50 ms timeout or fails, the pipeline automatically falls back to reverse-chronological sorting.

Redis Feed Cache Architecture

Redis sorted sets maintain lightweight chronological timelines for active users.

  • Data Structure: Stored under feed:{user_id} where score represents the post timestamp or Snowflake ID and member represents the post_id string.
  • Capacity Cap: Capped at 500 entries per user using ZREMRANGEBYRANK to keep the memory footprint around 8 KB per user.
  • Idempotency and Trimming: Writing an existing post ID updates its score rather than creating a duplicate member, ensuring safe worker retries.

Kafka Event Bus Configuration

The event streaming topology structures message distribution, partition keys, and dead letter handling:

Topic: new-posts
  Partitions: 128
  Partition key: author_user_id (preserves chronological order per author)
  Retention: 7 days
  Replication factor: 3, min.insync.replicas: 2

Producer: Transactional Outbox Relay / CDC Worker
  Guarantees: At-least-once delivery from MySQL post_outbox_events table
  Event Schema: { event_id, post_id, author_user_id, created_at, is_celebrity, follower_count, content_preview }

Consumer Groups:
  1. fan-out-workers: Writes post_id pointers into follower Redis sorted set timelines (bypassed for high-follower celebrity accounts)
  2. notification-workers: Emits push notifications to close friends and high-affinity contacts
  3. search-indexer: Streams post content into Elasticsearch for full-text discovery
  Dead Letter Queue: new-posts-dlq after 3 retries, with lag alerts configured for delays above 30 seconds

Synchronous Ingress Path:
  Validate payload -> Persist post record and outbox event in MySQL in a single atomic transaction -> Return 201 Created

Asynchronous Outbox and Fan-Out Path:
  Outbox Publisher polls or tails transaction log -> Publishes event to Kafka -> Fan-out workers query follower graph -> Pipeline idempotent ZADD operations into follower Redis timelines -> Commit Kafka consumer offsets

API Design

RESTful API contracts for post creation, home feed retrieval with opaque cursors, and social graph relationship management.

Client API Type Definitions

TypeScript domain interfaces defining post creation models, feed items, and pagination structures:

TYPESCRIPT
export type PrivacyLevel = "public" | "friends" | "private";
export type MediaType = "image" | "video" | "link";

export interface CreatePostRequest {
  content: string;
  mediaIds?: string[];
  privacy: PrivacyLevel;
}

export interface PostAuthor {
  userId: string;
  name: string;
  avatarUrl: string;
}

export interface PostMediaItem {
  url: string;
  type: MediaType;
  thumbnailUrl?: string;
}

export interface FeedPost {
  postId: string;
  author: PostAuthor;
  content: string;
  media: PostMediaItem[];
  reactionsCount: number;
  commentsCount: number;
  createdAt: string;
}

export interface GetFeedResponse {
  posts: FeedPost[];
  nextCursor: string | null;
  hasMore: boolean;
}

export interface FeedServiceClient {
  createPost(request: CreatePostRequest): Promise<{ postId: string; createdAt: string }>;
  getHomeFeed(pageSize: number, cursor?: string): Promise<GetFeedResponse>;
  followUser(targetUserId: string): Promise<{ success: boolean }>;
  unfollowUser(targetUserId: string): Promise<{ success: boolean }>;
}

Create Post Endpoint

Dispatches post content, media attachment references, and privacy settings:

HTTP
POST /api/v1/posts
Authorization: Bearer <user_token>
Content-Type: application/json

{
  "content": "Exploring distributed feed architectures with hybrid fan-out strategies.",
  "media_ids": ["img_9f8b4c2e-6d1a-4f5e"],
  "privacy": "public"
}

HTTP/1.1 201 Created
Content-Type: application/json

{
  "post_id": "1541815603606036480",
  "author_id": "usr_82910482",
  "created_at": "2026-03-13T10:00:00.000Z",
  "status": "published"
}

Get Home News Feed Endpoint

Retrieves a paginated list of enriched post objects using an opaque cursor:

HTTP
GET /api/v1/feed?page_size=20&cursor=eyJ2IjoxLCJzbmFwc2hvdF9pZCI6IjY5YWYwMSIsInBvc2l0aW9uIjoyMH0
Authorization: Bearer <user_token>

HTTP/1.1 200 OK
Content-Type: application/json

{
  "posts": [
    {
      "post_id": "1541815603606036480",
      "author": {
        "user_id": "usr_82910482",
        "name": "Sarah Connor",
        "avatar_url": "https://cdn.example.com/avatars/usr_82910482.jpg"
      },
      "content": "Exploring distributed feed architectures with hybrid fan-out strategies.",
      "media": [
        {
          "url": "https://cdn.example.com/media/img_9f8b4c2e.jpg",
          "type": "image"
        }
      ],
      "reactions_count": 142,
      "comments_count": 18,
      "created_at": "2026-03-13T10:00:00.000Z"
    }
  ],
  "next_cursor": "eyJ2IjoxLCJzbmFwc2hvdF9pZCI6IjY5YWYwMSIsInBvc2l0aW9uIjo0MH0",
  "has_more": true
}

Follow and Unfollow Endpoints

Manages social graph follow relationships:

HTTP
POST /api/v1/users/usr_82910482/follow
Authorization: Bearer <user_token>

HTTP/1.1 200 OK
Content-Type: application/json

{ "success": true, "followed_at": "2026-03-13T10:02:00Z" }

DELETE /api/v1/users/usr_82910482/follow
Authorization: Bearer <user_token>

HTTP/1.1 200 OK
Content-Type: application/json

{ "success": true, "unfollowed_at": "2026-03-13T10:05:00Z" }

Common Error Responses

400 Bad Request: invalid input, missing required fields, or malformed JSON payload
401 Unauthorized: missing or invalid authentication token or API key
403 Forbidden: authenticated caller lacks required permissions for this resource
404 Not Found: requested resource ID does not exist
409 Conflict: duplicate write or version conflict, retry with a unique idempotency key
422 Unprocessable Entity: syntactically valid request failed semantic business validation
429 Too Many Requests: rate limit quota exceeded, client should honor Retry-After header
500 Internal Error: unexpected server failure, retry safely with an idempotency key
503 Service Unavailable: downstream dependency is unavailable or overloaded, retry with exponential backoff
202 Accepted: asynchronous job queued successfully, poll GET /jobs/{id} for completion status
408 Request Timeout: background job is still executing, continue polling status endpoint

Data Model

Polyglot storage architecture combines relational consistency and transactional outbox reliability with write-optimized NoSQL stores for timelines and in-memory caches for social graphs.

MySQL (Sharded by user_id): Posts and Outbox Tables

Stores authoritative post content and local outbox events committed in the same database transaction:

SQL
CREATE TABLE posts (
    post_id     BIGINT PRIMARY KEY, -- 64-bit Snowflake identifier
    user_id     BIGINT NOT NULL,
    content     TEXT,
    media_urls  JSON,
    privacy     VARCHAR(16) DEFAULT 'public', -- 'public', 'friends', 'private'
    is_deleted  BOOLEAN DEFAULT FALSE,
    created_at  TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_created (user_id, created_at DESC)
);

CREATE TABLE post_outbox_events (
    event_id    BIGINT PRIMARY KEY AUTO_INCREMENT,
    post_id     BIGINT NOT NULL,
    payload     JSON NOT NULL,
    status      VARCHAR(16) DEFAULT 'PENDING', -- 'PENDING', 'PUBLISHED', 'FAILED'
    created_at  TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_status_created (status, created_at)
);

Cassandra: User Timelines

Maintains chronological history of posts published by a specific author:

SQL
CREATE TABLE user_timeline (
    user_id     UUID,
    post_id     BIGINT,
    created_at  TIMESTAMP,
    PRIMARY KEY (user_id, created_at)
) WITH CLUSTERING ORDER BY (created_at DESC);

Redis Sorted Sets: Precomputed Home Feed

Maintains precomputed post pointer IDs ordered by creation timestamp score:

Key:     feed:{user_id}
Type:    Sorted Set (ZSET)
Members: post_id (64-bit integer string, e.g., "1541815603606036480")
Scores:  timestamp_ms (epoch milliseconds, e.g., 1710320400000)
Max Cap: 500 entries per user (trimmed via ZREMRANGEBYRANK)

Social Graph Data Storage

Dual-layer storage with Redis sets for fast fan-out queries and Cassandra for durable persistence:

Redis Cache Layer:
  Key: following:{user_id} -> SET of followed user_id strings
  Key: followers:{user_id} -> SET of follower user_id strings
SQL
CREATE TABLE followers (
    user_id      UUID,
    follower_id  UUID,
    followed_at  TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id, follower_id)
);

Kafka Event Message Schema

Schema for the new-posts topic consumed by fan-out and indexing workers:

JSON
{
  "event_id": "evt_9831048201",
  "post_id": "1541815603606036480",
  "author_user_id": "usr_82910482",
  "content_preview": "Exploring distributed feed architectures...",
  "created_at": "2026-03-13T10:00:00.000Z",
  "is_celebrity": false,
  "follower_count": 200
}

Fault Tolerance

Resilience patterns for transactional publication, viral traffic spikes, cache evictions, moderation changes, and downstream service failures.

Fault Tolerance Strategies

Failure DomainResilience Mechanism
Transactional Outbox PublicationAtomic database transactions guarantee post creation and event generation succeed or fail together, eliminating event loss on service crashes.
Kafka Broker DurabilityReplication factor of 3 with min.insync.replicas=2 ensures published events survive broker outages without loss.
Redis Persistence and ClusteringRDB snapshots and AOF persistence combined with Redis Cluster replication provide high availability for feed caches.
Database Read ReplicasSharded MySQL replicas distribute read queries for post hydration during peak traffic.
Bounded Degradation on Redis FailureIf Redis clusters degrade, the system serves stale cached snapshots or queries a strictly bounded pool of top followed accounts, avoiding catastrophic database read storms.

Problem-Specific Failure Handling

1. Celebrity Fan-Out Storms

  • High-follower accounts automatically bypass fan-out on write, preventing millions of concurrent Redis write operations.
  • Celebrity posts are stored in dedicated author timelines and merged dynamically in bounded candidate windows at read time.

2. Feed Cache Misses and Inactive User Cold Starts

  • Users who have been inactive for extended periods have their Redis timelines evicted or skipped during fan-out writes.
  • When the user logs in, the Feed Service falls back to bounded fan-out on read: it queries recent posts from followed creators, merges active items, applies ranking, and repopulates the Redis sorted set.

3. Comprehensive Lazy Invalidation (Deletions, Moderation, and Privacy)

  • Synchronously purging millions of follower caches on every post deletion, content moderation action, account block, or privacy update creates unmanageable write amplification.
  • The architecture establishes the fundamental invariant that timeline membership is not final authorization to display content.
  • During feed read hydration, the system checks whether each candidate post is active, approved by moderation classifiers, and permitted under current relationship and privacy rules. Stale references are filtered immediately and purged asynchronously.

4. Ranking Service Outages

  • If the Machine Learning Ranking Service encounters timeouts or crashes, automated circuit breakers trip within 50 ms.
  • The Feed Service gracefully degrades by serving reverse-chronological feeds directly from Redis sorted sets without blocking user requests.

Additional Considerations

Advanced topics covering pagination mechanics across chronological and ranked feeds, content moderation pipelines, push notification triggers, and real-time freshness.

Pagination Mechanics for Chronological vs Ranked Feeds

Pagination requirements differ fundamentally depending on whether the feed is ordered deterministically by timestamp or dynamically by a machine learning model.

  • Reverse-Chronological Feeds: Use composite cursors formatted as timestamp_postId. The query ZREVRANGEBYSCORE feed:{user_id} (cursor_score -inf LIMIT 0 20 retrieves the next slice in O(log N + M) time with deterministic deduplication on identical timestamps.
  • Dynamically Ranked Feeds: Because ranking scores fluctuate dynamically between page requests, simple timestamp cursors cause duplicated or skipped posts. Ranked feeds use opaque snapshot cursors containing a feed generation ID, candidate window position, and ranking model version to preserve session consistency across infinite scroll requests.

Asynchronous Content Moderation

Posts are persisted to the database and published to author timelines while an asynchronous Kafka consumer routes text and images to machine learning moderation classifiers. If a post violates safety policies, the system marks is_deleted = true in MySQL and emits a cache invalidation event, ensuring read hydration filters it out immediately.

Push Notification Heuristics

To avoid notification fatigue, the system calculates an affinity score between author and follower before dispatching push notifications, alerting only close friends and high-interaction contacts.

Feed Freshness Indicators

When followed creators publish new content, a lightweight WebSocket or Server-Sent Events (SSE) signal notifies active client apps to display a "New Posts Available" banner, allowing users to pull refreshed content on demand without polling.

Related Problems and Concepts

Feed generation patterns overlap with Design Twitter Timeline and Search for tweet-length variations, retweet deduplication, and list feeds. Deepen your understanding of underlying caching and data distribution mechanisms in Caching Patterns and Invalidation, Sharding and Partitioning, Scaling 0 to 1M Users, and System Design Interview Patterns.

Interview Walkthrough

  • 25-Minute Interview Strategy

    Focus on the fan-out trade-offs and adaptive hybrid threshold before detailing transactional outbox reliability, Redis timeline data models, and the two-stage ranking pipeline.

    • Requirements and Read/Write Scope Definition (5 min)
    • Fan-Out Strategy: Push vs Pull vs Adaptive Hybrid (6 min)
    • High-Level Architecture and Transactional Outbox Flow (5 min)
    • Redis Sorted Set Timeline Model and Opaque Cursor Pagination (5 min)
    • Ranking Pipeline, Cold Start, and Fault Tolerance (4 min)
  • Lead with the fan-out decision (push on write vs pull on read) as it forms the foundational architectural fork for all downstream components.
  • Introduce the hybrid architecture early, explaining how an adaptive threshold prevents celebrity posting storms from overwhelming worker queues while keeping normal user feed retrieval fast.
  • Highlight the transactional outbox pattern to prove that post persistence and event publication cannot experience silent event loss during service crashes.
  • Detail how Redis sorted sets store lightweight 64-bit post pointers scored by timestamp, explaining member uniqueness for idempotent fan-out retries.
  • Distinguish deterministic timestamp cursors for chronological feeds from opaque snapshot cursors for dynamically ranked feeds.
  • Walk through the two-stage ranking flow (bounded candidate generation followed by ML feature scoring) and describe the graceful degradation fallback to chronological sorting.
  • Explain lazy invalidation across deletions, moderation, privacy changes, and blocks, demonstrating that timeline membership is not final authorization to view content.

Engineering Trade-offs

Architectural trade-offs across fan-out paradigms, in-memory data structures, database tiering, ranking pipelines, and deletion propagation models.

The Fan-Out Architectural Decision

Comparing write-time fan-out, read-time aggregation, and hybrid distribution models across latency and resource dimensions.

Fan-Out StrategyOperational MechanismAdvantagesDisadvantages
Fan-Out on Write (Push)Post creation event immediately writes post IDs into every follower's Redis feed cacheAvoids read-time aggregation across followed normal accounts by precomputing candidate timelinesSevere write amplification for high-follower accounts and wasted storage for inactive users
Fan-Out on Read (Pull)
  • Posts are stored only in author timelines
  • feeds query all followed creators and merge posts at read time
Zero write amplification and zero wasted storage for inactive usersHigher read latency caused by querying hundreds of creator timelines simultaneously
Adaptive Hybrid Model ⭐Push model for standard creators and bounded pull model for high-follower celebrity accountsCombines precomputed speed for normal feeds with protection against celebrity write stormsRequires read-time merging logic and dynamic follower threshold tracking

Redis Sorted Sets vs Redis Lists for Feed Caches

Evaluating in-memory data structures for timeline storage, duplicate prevention, and pagination efficiency.

Data StructureOperational CharacteristicsTrade-off Assessment
Redis List (LPUSH / LRANGE)Simple sequential list appending post IDs to headLacks native deduplication during worker retries, cannot efficiently remove specific deleted posts, and cannot support ranked scoring.
Redis Sorted Set (ZSET) ⭐Skip list and hash table ordering members by timestamp or scoreEnforces unique post_id members for idempotent retries, enables efficient trimming via ZREMRANGEBYRANK, and supports O(log N + M) range queries.

Polyglot Persistence Layering

Aligning distinct data access patterns with purpose-built database technologies across the feed lifecycle.

Data DomainAccess PatternStorage EngineArchitectural Rationale
Post Content and Outbox EventsAtomic write for post + outbox event, read by IDMySQL (sharded by user_id)Relational integrity, ACID transaction boundaries for reliable outbox publishing, and predictable sharded indexing.
Author TimelineAppend-only, queried by user_id ordered by timeCassandraHigh write throughput, native clustering order by timestamp, and scalable time-series partitioning.
Precomputed Home FeedHigh-frequency writes (fan-out) and low-latency readsRedis Sorted SetsSub-millisecond in-memory read latency, score-based range queries, and automatic eviction support.
Social Follow GraphRead-heavy set operations and follower lookupsRedis + CassandraRedis sets provide microsecond fan-out lookups, while Cassandra guarantees durable relationship storage.

Feed Ordering: Reverse-Chronological vs Machine Learning Ranked

Balancing computational complexity and user experience between deterministic ordering and engagement-driven ranking.

Ordering ModelInference MechanismTrade-off Profile
Reverse-ChronologicalFeeds sorted purely by post creation timestampDeterministic and computationally lightweight, but high-volume posters dominate feeds and bury relevant content from close contacts.
ML-Ranked Scoring ⭐Two-phase candidate generation followed by ML scoringMaximizes user engagement by prioritizing high-affinity content, but introduces 50 to 100 ms of inference latency and requires feature stores.

Post Invalidation and Deletion: Eager Purge vs Lazy Filtering

Managing cache consistency when posts are deleted, moderated, or have privacy rules changed across millions of follower timelines.

Invalidation StrategyExecution FlowTrade-off Assessment
Eager DeletionSynchronously removes post ID from all follower Redis sorted setsRequires up to millions of Redis ZREM operations per action, causing worker backlog and cluster saturation during viral post deletions.
Lazy Filtering with Async Cleanup ⭐Marks post state in MySQL and filters invalid IDs during feed hydrationO(1) instant write-time update with minimal read hydration overhead, while background workers asynchronously purge stale pointers.

💬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...