Skip to main content

Scenario: Meta News Feed Design

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"Design a news feed for 200M DAU. Users follow up to 5K accounts. p99 feed load < 500ms."

2. Real-World Context​

DimensionDetail
Company / systemMeta (Facebook) — canonical fan-out problem at planetary scale
Scale200M DAU; 500M posts/day; celebrity accounts with 50M+ followers (hot keys)
Why architects careFan-out on write vs read is the central tradeoff; hybrid model required
Public referencesClassic system design problem; Meta research on feed ranking and TAO graph store

AWS deployment context​

Typical Meta-scale news feed on AWS: ECS Fargate post + feed services; Amazon DynamoDB for posts and social graph; Amazon ElastiCache Redis for precomputed feed timelines (sorted sets); Amazon MSK for async fan-out events; Amazon OpenSearch for ranking feature store; CloudFront for media CDN; Amazon Personalize or custom ML ranker on SageMaker; CloudWatch for feed latency SLOs.

Step-by-step flow:

StepActionExplanation
1Create postUser publishes text/image/video.
2PersistPost stored in DynamoDB with post_id, author_id, timestamp.
3Publish eventpost_created event to MSK for async fan-out.
4Fan-outWorker pushes post_id to followers' Redis sorted sets.
5ZADD feed cacheZADD user:{follower_id}:feed {score} {post_id}.
6Load feedUser opens app; requests home feed.
7ZRANGE timelineFetch top 200 post_ids from Redis — sub-ms.
8Merge celebritiesPull recent posts from celebrity accounts (fan-out on read).
9Re-rank top 200ML ranker scores and reorders candidates.

3. Step-by-Step Interview Answer​

Step 1 — Clarify requirements​

RequirementTarget
DAU200M
Posts/day500M (~5.8K/sec avg; 50K/sec peak)
Feed reads~10 reads/user/day → 2B reads/day (~23K/sec avg)
Follow limit5K accounts per user
Feed load p99< 500ms
FreshnessNew posts visible within 5–30 seconds
CelebrityAccounts with > 1M followers use pull merge

Step 2 — Capacity math​

MetricCalculationResult
Avg follow countPower-law distribution~200 median; 5K max
Fan-out writes/postAvg 200 followers × 5.8K posts/sec~1.16M Redis ZADD/sec
Feed cache size200M users × 500 post_ids × 16B~1.6 TB (trim to 200/post)
Celebrity thresholdFan-out > 1M ZADDs/postSwitch to pull at 1M followers
Read QPS2B reads/day~23K/sec (peak 100K+)

Step 3 — Hybrid fan-out architecture​

Step-by-step flow:

StepActionExplanation
1Post createdAuthor publishes; event emitted to MSK.
2Check follower countFan-out worker reads author metadata from DynamoDB.
3aNormal fan-outFor users with < 1M followers: ZADD to each follower's Redis feed.
3bCelebrity skipFor celebrities: store post only; no fan-out (avoids 50M writes/post).
4ZRANGE feed cacheRead path fetches precomputed timeline from Redis sorted set.
5Fetch celebrity postsPull recent posts from followed celebrities at read time.
6Merge + dedupeUnion push + pull candidates; remove duplicates by post_id.
7Rank top 200ML ranker scores engagement, recency, affinity.
8Hydrate post bodiesBatch-fetch post content from DynamoDB by post_id.

Step 4 — Write path sequence​

Step-by-step flow:

StepActionExplanation
1POST /postsClient submits new post.
2PutItem postPersist post with post_id, author_id, created_at, content ref.
3Publish post_createdAsync fan-out via MSK — API returns fast.
4201 CreatedUser sees confirmation; feed update is eventual.
5Consume eventFan-out worker picks up from post-created topic.
6Get follower listQuery social graph: followers:{author_id} from DynamoDB.
7ZADD each followerPush post_id with score = created_at epoch to each feed.
8Skip fan-outCelebrity: post stored but not pushed to 50M feeds.
9ZADD author own feedAuthor always sees own post immediately (read-your-writes).

Step 5 — Read path sequence​

Step-by-step flow:

StepActionExplanation
1GET /feedUser requests home timeline with pagination cursor.
2ZREVRANGEFetch top 200 post_ids from precomputed Redis feed.
3Get celebritiesLoad list of followed accounts with > 1M followers.
4Query celebrity postsPull last N posts per celebrity from DynamoDB GSI.
5Merge + dedupeUnion push and pull candidates; dedupe by post_id.
6Score top 200Ranker applies ML features: engagement, affinity, recency.
7Ranked post_idsOrdered list returned to Feed API.
8BatchGet post bodiesHydrate full post objects from DynamoDB.
9Feed JSONReturn ranked feed with next_cursor for infinite scroll.

Step 6 — Celebrity hot path​

Step-by-step flow:

StepActionExplanation
1Post createdCelebrity publishes — would cause 50M Redis writes if fan-out.
2Skip fan-outWorker detects follower_count ≥ 1M; no ZADD storm.
3Store in author timelinePost indexed on author_id GSI for pull queries.
4Open feedFollower loads home feed.
5ZRANGE own cachePrecomputed posts from normal followees.
6Pull celebrity GSIQuery posts_by_author for each followed celebrity.
7Merge at rank timeCelebrity posts enter candidate pool before ranking.

4. Whiteboard Guide​

Draw three boxes left-to-right: Write Path → Feed Cache → Read Path. Emphasize the celebrity fork: fan-out stops at 1M followers.

Step-by-step flow:

StepComponentRole
1ALBTerminates TLS; routes /feed and /posts.
2Post ServiceSynchronous write; publishes to MSK.
3MSKDecouples fan-out from API latency.
4Fan-out WorkersHorizontally scaled; partition by author_id.
5ElastiCache RedisSorted-set timelines; cluster mode for sharding.
6DynamoDBPosts table + social graph; GSI for celebrity pull.
7Ranking ServiceTwo-phase: candidate gen → ML scoring.
8OpenSearchFeature store for engagement signals.
9CloudWatchFeed p99, fan-out lag, Redis memory alarms.

5. Principal-Level Signals​

SignalWhat strong candidates say
Hybrid fan-out"Push for normal users; pull merge for celebrities above 1M followers."
Write amplification math"50M ZADDs per celebrity post is unacceptable — that's the fork point."
Read-your-writes"Author's own feed always gets ZADD even when fan-out is skipped."
Ranking as separate phase"Fetch 200 candidates cheaply; rank only the merged pool."
Cache trimming"Cap feed at 200–500 post_ids; evict oldest on ZADD."
Eventual consistency"5–30s fan-out lag is acceptable; not linearizable."

6. Red Flags​

Red flagWhy it fails
Pure fan-out on writeCelebrity post melts Redis — 50M writes in seconds.
Pure fan-out on readEvery feed load queries 5K followees — 5K DynamoDB reads/request.
No feed cacheCannot hit 500ms p99 at 23K read QPS.
Synchronous fan-out in APIPost API blocks on follower iteration — timeout at scale.
Single Redis instanceHot keys and memory ceiling; need cluster mode.
Ranking entire graphMust limit candidates to ~200 before ML scoring.

7. Follow-Up Questions​

QuestionStrong answer
How do you handle a user unfollowing someone?Lazy removal: don't purge history; filter at read time. Or async purge job on unfollow event.
How do ads fit in?Slot-based injection in ranker output — positions 3, 7, 12 reserved for ads.
Real-time feed updates?WebSocket push for new posts after initial load; polling fallback.
Feed for new user with no follows?Cold-start: popular/trending posts from ranking service.
How to shard Redis?Hash slot per user_id; cluster mode with 16384 slots.
Duplicate posts after merge?Dedupe by post_id in merge step before ranking.

8. Practice Drill (10 min)​

  1. 2 min — State hybrid fan-out and celebrity threshold.
  2. 3 min — Draw write path: Post → MSK → Fan-out → Redis.
  3. 3 min — Draw read path: Redis ZRANGE + celebrity pull + rank.
  4. 2 min — Capacity: 200 followers × 5.8K posts/sec = fan-out QPS.

9. Key Takeaways​

  1. Hybrid fan-out is non-negotiable at Meta scale — pure push or pull both fail.
  2. Redis sorted sets are the production timeline cache — ZADD/ZREVRANGE with score = timestamp.
  3. Async fan-out via MSK keeps post API fast; lag is acceptable.
  4. Two-phase ranking: cheap candidate fetch → expensive ML on top 200.
  5. Read-your-writes for author's own posts bypasses celebrity skip logic.

10. Production HLD​

10.1 C4 Context​

Step-by-step flow:

StepInteractionExplanation
1User ↔ Feed SystemCreate posts and load personalized home feed.
2Post StoreDynamoDB — source of truth for post content.
3Graph StoreFollow/follower relationships; follower counts.
4Feed CacheElastiCache Redis — precomputed timelines per user.
5RankerML scoring on merged candidate pool.
6Media CDNCloudFront serves images/video referenced by posts.

10.2 Full production stack​

LayerAWS ServicePurpose
EdgeCloudFront + ALBTLS, media CDN, API routing
ComputeECS FargatePost, Feed, Fan-out, Ranking services
MessagingAmazon MSKpost-created, unfollow events
Timeline cacheElastiCache Redis (cluster)Sorted-set feeds per user
PostsDynamoDBPosts table; GSI author_id-created_at
Social graphDynamoDBfollows adjacency; follower_count on user
Ranking featuresOpenSearchEngagement signals, affinity scores
MLSageMakerFeed ranking model inference
ObservabilityCloudWatch + X-RayLatency, fan-out lag, cache hit rate

10.3 Architecture index​

#DiagramSection
1AWS deployment context§2
2Hybrid fan-out flowchart§3 Step 3
3Write path sequence§3 Step 4
4Read path sequence§3 Step 5
5Celebrity hot path§3 Step 6
6Whiteboard AWS layout§4
7C4 context§10.1
8Fan-out worker internals§11.2
9Ranking pipeline§11.4
10HA / multi-AZ§12

11. Production LLD​

11.1 Data schemas​

Posts table (DynamoDB)

AttributeTypeKeyDescription
post_idStringPKUUID
author_idStringGSI PKAuthor user ID
created_atNumberGSI SKEpoch ms — sort key
content_typeString—text, image, video
content_refString—S3 key or text body
like_countNumber—Eventually consistent counter

Social graph table (DynamoDB)

AttributeTypeKeyDescription
user_idStringPKFollower
followee_idStringSKFollowed account
created_atNumber—Follow timestamp

User metadata (DynamoDB)

AttributeTypeDescription
user_idString PKUser identifier
follower_countNumberUsed for celebrity threshold
is_celebrityBooleanCached flag when count ≥ 1M

Feed cache (Redis sorted set)

Key: feed:{user_id}
Score: created_at epoch ms
Member: post_id
Max: 500 members (ZREMRANGEBYRANK trim)

11.2 Fan-out worker pseudocode​

def handle_post_created(event):
post = event.post
author = get_user(post.author_id)

# Always push to author's own feed (read-your-writes)
redis.zadd(f"feed:{post.author_id}", {post.post_id: post.created_at})
trim_feed(post.author_id, max_size=500)

if author.follower_count >= CELEBRITY_THRESHOLD:
log.info("celebrity skip", author_id=post.author_id)
return

followers = get_followers(post.author_id) # paginated scan
for batch in chunks(followers, 1000):
pipe = redis.pipeline()
for follower_id in batch:
pipe.zadd(f"feed:{follower_id}", {post.post_id: post.created_at})
pipe.zremrangebyrank(f"feed:{follower_id}", 0, -501)
pipe.execute()

11.3 API contracts​

POST /v1/posts

// Request
{ "content_type": "text", "body": "Hello world" }

// Response 201
{ "post_id": "p_abc123", "created_at": 1722123456789 }

GET /v1/feed?limit=20&cursor=eyJ...

// Response 200
{
"posts": [
{ "post_id": "p_abc", "author_id": "u_1", "body": "...", "like_count": 42 }
],
"next_cursor": "eyJ..."
}

11.4 Ranking pipeline​

Step-by-step flow:

StepActionExplanation
1Redis ZREVRANGE 200Cheap precomputed candidates from push fan-out.
2Celebrity GSI pullRecent posts from followed celebrities.
3Merge + dedupeUnion pools; unique by post_id.
4Feature lookupEngagement, affinity, recency from OpenSearch.
5Model inferenceSageMaker endpoint scores each candidate.
6Reorder top 200Sort by score; take top limit for response.
7Inject ad slotsInsert sponsored content at fixed positions.

11.5 Feed read handler pseudocode​

def get_feed(user_id: str, cursor: str | None, limit: int = 20):
# Phase 1: candidates
cached_ids = redis.zrevrange(f"feed:{user_id}", 0, 199, withscores=True)
celebrities = get_followed_celebrities(user_id)
celebrity_posts = []
for celeb_id in celebrities:
celebrity_posts.extend(query_recent_posts(celeb_id, limit=10))
candidates = dedupe_by_post_id(cached_ids + celebrity_posts)

# Phase 2: rank
ranked_ids = ranker.score_and_sort(user_id, candidates)[:200]

# Phase 3: hydrate + paginate
posts = batch_get_posts(ranked_ids)
page, next_cursor = paginate(posts, cursor, limit)
return {"posts": page, "next_cursor": next_cursor}

12. HA, DR, and Multi-AZ​

ConcernStrategy
Feed API HAECS service across 3 AZs; ALB health checks
Redis HAElastiCache cluster mode; replica per shard; automatic failover
DynamoDBOn-demand capacity; multi-AZ by default
MSK3-broker cluster; replication factor 3
Fan-out lagMonitor consumer lag; auto-scale workers on backlog
DRCross-region DynamoDB Global Tables for posts; Redis rebuilt from fan-out replay

13. Observability​

MetricTargetAlarm
feed.load.p99< 500ms> 800ms for 5 min
fanout.lag.seconds< 30s> 60s
redis.memory.used_pct< 80%> 85%
fanout.zadd.ratebaseline3× spike
ranker.inference.p99< 100ms> 200ms
post.create.p99< 200ms> 500ms

Dashboards: Feed load latency breakdown (Redis / DDB / Ranker); fan-out throughput per worker; celebrity skip rate; cache hit ratio.

14. Evolution Roadmap​

PhaseCapabilityTrigger
V1Push fan-out only< 10M DAU; no celebrities
V2Hybrid + celebrity pullHot user incidents
V3Two-phase rankingEngagement optimization
V4Real-time WebSocket pushProduct freshness requirement
V5Graph-aware fan-outClose friends get priority ZADD

15. Testing Strategy​

Test typeScenarioPass criteria
UnitCelebrity threshold logicSkip fan-out at ≥ 1M followers
IntegrationPost → MSK → RedisFollower feed contains post within 30s
Load50K posts/sec fan-outWorker lag < 30s
ChaosRedis shard failoverFeed load p99 < 1s during failover
CorrectnessAuthor read-your-writesOwn post visible before fan-out completes
MergeCelebrity + normal followeeNo duplicate post_ids in feed

16. Production Checklist​

  • Celebrity threshold configured (default 1M followers)
  • Redis cluster mode with ≥ 3 shards per region
  • Feed cache trimmed to 500 post_ids max
  • Fan-out workers partitioned by author_id on MSK
  • Author own-feed ZADD on every post (read-your-writes)
  • Ranking limited to 200 candidates before ML inference
  • CloudWatch alarms on fan-out lag and feed p99
  • DynamoDB GSI author_id-created_at for celebrity pull
  • Cursor-based pagination (not offset)
  • Idempotent fan-out (dedupe by post_id on ZADD)