Designing a Ranked Personal Content Feed at Scale
System DesignModel answerLast updated
Architect a scalable, personalized news feed system that handles hybrid fanout, multi-stage recommendation pipelines, stable cursor pagination, and instant post soft-deletions.
Problem Overview
Design the architecture for an interactive, personalized home feed service (similar to LinkedIn or X). Users publish text/media updates, follow other entities, and consume an infinite-scrolling feed of ranked posts combining content from connections/followees with recommended out-of-network content.
System Requirements
Functional Requirements
- Publish & Delete Content: Users can publish new items and instantly delete existing ones.
- Social Graph Management: Support direct follow/unfollow functionality.
- Personalized Ranked Feed: Deliver a single stream blending in-network posts and out-of-network discoveries, sorted dynamically by predicted user engagement.
- Stable Pagination: Provide consistent cursor-based pagination that prevents duplicate items or skipped content as fresh posts land continuously.
Non-Functional Requirements & Metrics
- Scale: 100 Million Daily Active Users (DAU).
- Read/Write Ratio: Heavily read-skewed (~20:1). Average 10 feed refreshes/page requests per DAU per day (~1B total read requests/day). Approximately 50 Million new posts created per day (~580 writes/sec average, peaking at ~2,000 writes/sec).
- Latency: p99 response time for feed generation under 200 milliseconds.
- Data Freshness & Availability: High availability for feed reads; eventual consistency (within a few seconds) for content delivery to followee feeds.
What Your Design Should Cover
- High-Level Architecture & Data Stores: Detail the write ingestion path, read generation pipeline, and database selections (post storage, graph engines, and cache topologies).
- Hybrid Fanout Strategy: Address how to scale content distribution efficiently, taking into account normal vs. high-follower ("celebrity/influencer") accounts.
- ML Retrieval & Heavy Ranking Pipeline: Map out candidate generation (in-network inbox + vector ANN search), filtering (blocks, seen items, tombstones), real-time feature hydration, multi-stage model scoring, and payload hydration.
- Pagination & Consistency Guarantees: Define a robust cursor strategy that maintains pagination stability during active sessions, along with fast-path soft deletion/privacy enforcement.
Hints
Hint 1
Consider how write amplification changes when an account has 50 followers versus 50 million followers. Avoid blindly pushing writes to massive follower lists.
Hint 2
Decouple candidate ranking from payload hydration: scoring thousands of post IDs is cheap, but fetching rich user profiles and high-res media metadata for 2,000 items on every request will blow through your 200 ms latency budget.
Hint 3
Using simple numeric offsets for an infinitely updating feed causes items to shift positions between page requests. Think about session-based snapshots or cursor tie-breakers.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirement Clarifications & Traffic Estimates
Back-of-the-Envelope Math
- Read Load: 100M DAU × 10 requests = 1 Billion feed requests/day.
- Average Read QPS = $1\text{B} / 86,400 \approx \mathbf{11,600\text{ QPS}}$
- Peak Read QPS (3× factor) $\approx \mathbf{35,000\text{ QPS}}$
- Write Load: 50M posts/day.
- Average Write QPS = $50\text{M} / 86,400 \approx \mathbf{580\text{ QPS}}$
- Peak Write QPS $\approx \mathbf{2,000\text{ QPS}}$
- Fanout Write Amplification:
- If average followers/user = 200: $580\text{ post writes/sec} \times 200 = \mathbf{116,000\text{ inbox inserts/sec}}$.
- Tail risk: A user with 40M followers would require 40M immediate database/cache writes on a single post creation if using standard push fanout.
- Storage Footprint:
- 50M posts/day × ~1 KB text/metadata = 50 GB/day (excluding binary media assets, which go directly to Blob Storage / CDN).
- Inbox Caches: 100M active users × 500 post IDs × 16 bytes/entry $\approx \mathbf{800\text{ GB}}$ in distributed cache (e.g., Redis).
2. API Design & Data Contracts
POST /v1/posts
Header: Authorization: Bearer <token>
Content-Type: application/json
{
"text": "Hello world",
"media_ids": ["med_991823"]
}
--> 201 Created { "post_id": "p_109283749210" }
DELETE /v1/posts/{post_id}
--> 204 No Content
POST /v1/users/{user_id}/follow
--> 200 OK
GET /v1/feed?cursor=eyJzZXNzaW9uX2lkIjoiMTIzNCIsInBvcyI6MjB9&limit=20
--> 200 OK
{
"items": [
{
"post_id": "p_109283749210",
"author": { "user_id": "u_55", "name": "Jane", "avatar_url": "..." },
"text": "...",
"media": [...],
"metrics": { "likes": 142, "replies": 12 },
"created_at": 1711928300
}
],
"next_cursor": "eyJzZXNzaW9uX2lkIjoiMTIzNCIsInBvcyI6NDB9"
}
3. Storage Layer Architecture
- Posts Database: Distributed NoSQL wide-column store (e.g., ScyllaDB/Cassandra) or sharded relational database (MySQL/PostgreSQL) partitioned by
post_id(using Snowflake/Time-sortable IDs).- Schema:
post_id (PK),author_id,text,media_json,created_at,status (active/deleted). - Secondary lookup mapping:
author_id -> list of post_ids(sorted by timestamp descending) to support read-time pull fetching.
- Schema:
- Social Graph Store: Distributed graph database or key-value engine (e.g., RocksDB-backed custom graph store or Redis graph tables).
- Dual adjacency structure:
following:{user_id}andfollowers:{user_id}.
- Dual adjacency structure:
- In-Network Inbox Cache: Sharded Redis deployment containing sorted sets (
ZSET) keyed asinbox:{user_id}storing(post_id, timestamp). Truncated to a max length of 500 entries per user. - Counters Service: Dedicated Redis or Cassandra counters for volatile state (
likes,retweets/reshares,comments). Avoids atomic write amplification on the main Post record.
4. End-to-End System Architecture
[ POST WRITE PATH ]
Client ──> API Gateway ──> Post Service ──> Write to Posts DB (ScyllaDB)
│
└──> Event Bus (Kafka)
├──> Fanout Engine ──> Filter Active Users ──> ZADD to Redis Inboxes
├──> Vector Ingestion ──> Embedding Model ──> HNSW Vector Index (ANN)
└──> Real-time Analytics (Flink) ──> Online Feature Store
[ FEED READ PATH ]
Client ──> API Gateway ──> Feed Assembly API
│
┌──────────────────────┼──────────────────────┐
▼ ▼ ▼
Inbox Fetcher Celebrity Puller Discovery Service
(Redis Inboxes) (Followee High-Degree) (ANN Vector Search)
[~500 IDs] [~300 IDs] [~400 IDs]
└──────────────────────┬──────────────────────┘
│ (~1,200 Candidate IDs)
▼
Filter Pipeline
(Blocks, Seen Set, Tombstones)
│ (~1,000 Clean Candidates)
▼
Lightweight Ranker (GBDT / Small DNN)
│ (~300 Candidates)
▼
Feature Store Hydration
(User Profile + Post Engagement Velocity)
│
▼
Heavy DNN Ranker
(Multi-task: p(click), p(like), p(dwell))
│ (~20 Top Candidates)
▼
Payload Hydration
(Fetch Author Info & Counters for Top 20)
│
▼
Client Response + Cursor
5. Fanout Strategy: Hybrid Push/Pull Model
A pure push model (fanout-on-write) fails for celebrity accounts with millions of followers due to memory write storms and high tail latency. A pure pull model (fanout-on-read) incurs excessive read-time DB fanout overhead across hundreds of followees for every request.
We apply a hybrid push/pull strategy:
Follower Count Threshold (T) = 10,000 Followers
- Standard Accounts (< 10k Followers) → Push Strategy:
- When User A posts, an asynchronous Kafka worker fetches User A's follower list.
- For all followers who have been active in the past 30 days, append
post_idto their Redis sorted setinbox:{follower_id}viaZADD.
- High-Follower / Celebrity Accounts (≥ 10k Followers) → Pull Strategy:
- When a high-follower user posts, skip inbox fanout entirely. Save the post to their individual timeline store
timeline:{author_id}. - When a follower loads their feed, the Feed Assembly Service reads from their
inbox:{user_id}and queries the recent posts of the specific high-follower accounts the user follows (retrieved from memory/local cache).
- When a high-follower user posts, skip inbox fanout entirely. Save the post to their individual timeline store
- Inactive User Optimization: If a user has not logged in for over 30 days, prune their
inbox:{user_id}cache. When they eventually return, trigger an asynchronous inbox backfill via pull fanout.
6. Candidate Retrieval & ML Recommendation Pipeline
To deliver a ranked feed under 200 ms, candidate scoring operates in multi-stage pipelines:
Stage 1: Parallel Retrieval (Candidate Generation) — Target: ~30 ms
Gather ~1,200 total candidate post IDs across three sources:
- In-Network Push Inbox: Read up to 500 recent post IDs from Redis sorted set.
- In-Network Celebrity Pull: Read 20 recent post IDs from each followed account exceeding the 10k follower threshold (~300 posts total).
- Out-of-Network Discovery (ANN Search): Generate candidate post IDs using a Two-Tower Embedding Network. A user embedding vector queries an Approximate Nearest Neighbor (ANN) vector store (e.g., Milvus or HNSWLib indexing the last 48 hours of published content) to yield ~400 relevant out-of-network candidate IDs.
Stage 2: Fast Filtering — Target: ~10 ms
Execute fast operations to filter candidates down to ~1,000:
- Tombstone/Deletion Check: Remove IDs present in the global post-deletion Bloom filter / short-term Redis invalidation set.
- Block/Mute Filters: Remove posts from authors muted or blocked by the requesting user.
- Seen-State Filtering: Exclude post IDs that match the user’s recent impression log stored in a per-user Redis Bloom Filter.
Stage 3: Lightweight Scoring (Scoring Reduction) — Target: ~20 ms
Run a fast, lightweight ranker (e.g., Gradient Boosted Decision Trees or a small Logistic Regression model) using basic features (post age, author affinity score, media type match) to downselect from ~1,000 candidates to 300 high-potential candidates.
Stage 4: Feature Hydration & Heavy Multi-Task Ranking — Target: ~70 ms
- Online Feature Store Retrieval: Fetch real-time context from Redis/Feast:
- User context: Current session category affinity, user age, location, device.
- Author context: Historic engagement score, post frequency.
- Post/Real-Time context: Current engagement velocity (likes/min in the last 15 minutes processed by Apache Flink).
- Heavy Multi-Task Deep Neural Network (DNN): Predict engagement probabilities: $$\text{Score} = w_1 \cdot P(\text{click}) + w_2 \cdot P(\text{like}) + w_3 \cdot P(\text{reply}) + w_4 \cdot P(\text{dwell} > 10\text{s}) - w_5 \cdot P(\text{negative_feedback})$$
- Rank the top candidates and apply policy rules (diversity constraints to prevent 3 consecutive posts from the same author, business logic quotas for discovery items vs. in-network items). Select the top 20 post IDs.
Stage 5: Final Hydration — Target: ~20 ms
Only after the final 20 post IDs are determined, execute a batched multi-get (MGET) to fetch full post text, author profile metadata, asset URLs, and current counts (likes/comments) from distributed memory caches.
Latency Budget Allocation (Total p99 Goal: < 200 ms)
| Step | Budget |
|---|---|
| Transport / API Gateway Overhead | 15 ms |
| Parallel Candidate Retrieval | 30 ms |
| Fast Filtering & Deduplication | 10 ms |
| Light Ranking (1000 -> 300) | 20 ms |
| Feature Store Multi-Get | 25 ms |
| Heavy Ranker Model Inference (GPU/Triton) | 60 ms |
| Top-20 Data Hydration | 20 ms |
| Total Target | 180 ms |
7. Pagination Strategy
Traditional offset pagination (LIMIT 20 OFFSET 40) fails in dynamic feeds because real-time arrivals cause items to shift, leading to missing content or duplicate rendering across pages.
Session-Based Ranked Snapshots
- Initial Page Request (
GET /v1/feed):- The pipeline generates a list of 100–200 top-ranked post IDs.
- This ranked ID array is cached in Redis under a short-lived key:
feed_session:{user_id}:{session_id}, with a time-to-live (TTL) of 30 minutes. - Return the first page of 20 items to the client alongside an opaque cursor:
cursor = Base64({"session_id": "s_8812", "offset": 20})
- Subsequent Page Requests (
GET /v1/feed?cursor=...):- Decrypt/parse the cursor to find
session_idandoffset. - Directly slice items
[offset : offset + limit]from the stored session array in Redis. - Run real-time hydration and filter checks (in case a post was deleted after session snapshot creation).
- Decrypt/parse the cursor to find
- Session Expiry & Pull-To-Refresh:
- When the client reaches the end of the snapshot or explicitly pulls to refresh, a new
session_idis generated, causing the retrieval pipeline to execute fresh candidate generation. - New incoming posts land at the top of the next generated session, completely avoiding UI jitter or item shifts during scroll.
- When the client reaches the end of the snapshot or explicitly pulls to refresh, a new
8. Handling Deletions & Edge Cases
- Instant Soft Deletions:
- When a user clicks delete, update the database record to
status = DELETEDand emit apost_deletedevent to Kafka. - Append the
post_idto an in-memory Tombstone Cache (a high-performance Redis set / fast local filter). - During Feed Read Assembly, candidate IDs hitting the Tombstone set are instantly discarded during Stage 2 filtering. This ensures deleted posts disappear within milliseconds globally, even if background cleanups of pre-materialized Redis inboxes take longer.
- When a user clicks delete, update the database record to
- Fallback & Degradation Strategy:
- If the Heavy Ranker service times out (>60 ms), fail over gracefully by serving candidates ordered by the Light Ranker or fall back to reverse-chronological order directly from the Redis Inbox.