logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramlinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Design a Social-Media News Feed
API GatewayAPIBatchingCacheCAPConsistent HashingCounting At ScaleCQRSCRDTDatabase ScalingDatabase Selection StrategyDeployment StrategyDNSEvent SourcingHandling FailureVertical vs Horizontal ScalingHTTPId GenerationIndexesKafkaKubernetesLarge FilesLoad BalancingPaginationProxyReal Time PushRedisScaling ReadsStateless vs Stateful SystemsScaling Writes
System Design/problems

Design a Social-Media News Feed

16 min read
On this page1. Problem framing
1. Problem framingScope2. RequirementsFunctional requirementsNon-functional requirementsClarifying questions to ask first3. Back-of-the-envelope sizing4. Core APIs5. Data modelCritical principle6. High-level architecture7. Publish pathFlowTransactional outbox patternIdempotency8. Feed retrieval pathStepsCursor pagination9. Fanout strategiesFanout on writeFanout on readRecommended hybrid design10. RankingTwo-stage rankingPolicy and diversity rulesRanking tradeoff11. CachingCache-stampede protectionCache principle12. Storage and shardingPostsFeed timelineSocial graphCounters13. Media and CDNUpload flowImportant details14. Interactions and notificationsLikes/reactionsCommentsNotifications15. Privacy, deletes, and moderationDouble privacy checkTombstone deletion patternModeration16. Consistency modelOrdering17. Failure modes and ideal interview answers“What if the queue is down?”“What if fanout workers lag?”“What if Redis/feed cache is flushed?”“What if a celebrity posts?”“What if ranking is unavailable?”“What if a user is blocked after feed entries were written?”“What if a post event is delivered twice?”18. Reliability and observabilityReliability patternsMetrics19. Multi-region design20. Design invariants21. Tradeoffs22. Two-minute interview answer23. Suggested 40-minute walkthroughFinal memorable statement

# 1. Problem framing

A home/news feed is a personalized, continuously updated list of posts from accounts, pages, or groups a user follows.

The hard problem is asymmetry:

  • Reads are extremely frequent and must be fast.
  • A single post can create millions of downstream feed updates.
  • Feed ranking, privacy, deletion, media, and interactions make the result more than a chronological list.

# Scope

Support:

  • Create text, image, and video posts.
  • Follow, unfollow, block, and mute users.
  • Fetch a personalized feed with infinite scroll.
  • Like, comment, share, save, hide, and report.
  • Near-real-time new-content indication.
  • Privacy controls and deletion.

Out of scope unless asked:

  • Ads, stories, live video, direct messaging, search, recommendation-only feed, and content-moderation model internals.

# 2. Requirements

# Functional requirements

  • Users create posts with text and optional media.
  • Users follow accounts/pages/groups.
  • Users see a personalized feed.
  • Feed supports pagination/infinite scroll.
  • New content appears within a few seconds.
  • Users can interact with posts.
  • Audience restrictions, blocks, mutes, and deletes are respected.

# Non-functional requirements

RequirementTarget example
Feed first-page latencyp95 < 300 ms
Feed availability99.99%
Post creation acknowledgment< 500 ms after durable write
New-post propagationseconds for normal authors
Consistencyeventual for feed/rank/counters; stronger for privacy/deletes
Scalehundreds of millions of DAU
Durabilityaccepted post must not be lost

# Clarifying questions to ask first

  1. Is the feed chronological or ranked?
  2. Are relationships follows, friends, pages, groups, or all of them?
  3. What is the freshness requirement?
  4. Are media, likes, comments, and notifications in scope?
  5. How many DAU, feed opens/day, posts/day, follows/user, and max followers?
  6. Is eventual consistency acceptable?
  7. Do privacy, blocks, deletes, and moderation need immediate behavior?

# 3. Back-of-the-envelope sizing

Example assumptions:

ItemAssumptionResult
DAU100 M—
Feed opens/user/day101 B feed reads/day
Average read rate1 B / 86,400~11.6 K RPS
Peak multiplier10x~116 K RPS
Posts/user/day0.220 M posts/day
Average post rate20 M / 86,400~230 posts/s
Average followers300~6 B potential fanout writes/day
Cached feed window500 post IDs/user50 B feed entries

Important insight:

Post creation may be modest, but fanout can turn one post into millions of writes. The celebrity tail determines the architecture.


# 4. Core APIs

POST /v1/posts
Authorization: Bearer <token>
Idempotency-Key: <client-generated-uuid>
 
{
  "text": "Hello",
  "mediaIds": ["media_123"],
  "audience": "followers"
}
GET /v1/feed?cursor=<opaque-cursor>&limit=25
Authorization: Bearer <token>
{
  "items": [
    {
      "postId": "p_123",
      "author": {"id": "u_9", "name": "Asha"},
      "text": "Hello",
      "media": [{"url": "https://cdn.example/media/abc"}],
      "viewerState": {"liked": false, "saved": false},
      "counts": {"likes": 42, "comments": 5}
    }
  ],
  "nextCursor": "signed-opaque-cursor"
}
POST   /v1/users/{id}/follow
DELETE /v1/users/{id}/follow
 
POST   /v1/posts/{id}/reactions
DELETE /v1/posts/{id}/reactions/{type}
 
POST   /v1/posts/{id}/comments
DELETE /v1/posts/{id}
 
POST   /v1/posts/{id}/hide
POST   /v1/posts/{id}/report

Use:

  • Authentication from the session/token, never client-supplied user IDs.
  • Idempotency keys for post/reaction/comment mutations.
  • Opaque cursor pagination, not offset pagination.

# 5. Data model

EntityImportant fieldsStorage approach
Useruser_id, profile, settingsrelational/KV
Follow edgefollower_id, followee_idgraph or adjacency-list KV store
Postpost_id, author_id, body, media, visibility, status, created_atdistributed post store
Mediamedia_id, object key, variants, statusobject storage + metadata DB
Feed entryviewer_id, post_id, sort key, source, scorefeed store/cache
Reactionpost_id, user_id, typeinteraction store
Commentcomment_id, post_id, author_id, bodypartitioned comment store
Counterpost_id, count typesharded counter store
Eventevent_id, type, payload/versiondurable event log

# Critical principle

Feed timelines store post IDs and small metadata, not copied post bodies or media.

Why:

  • Less memory and storage.
  • Post edits/deletes do not require rewriting every follower’s copy.
  • Full post/profile data can be hydrated from caches.

# 6. High-level architecture

There are two independent paths:

  1. Write/publish path: create a post, durably emit an event, asynchronously distribute it.
  2. Read/retrieval path: obtain candidates quickly, enforce policy, hydrate, rank, and return a page.

# 7. Publish path

# Flow

# Transactional outbox pattern

This is one of the most useful advanced patterns.

Problem:

  • The service writes the post to a database.
  • It then publishes an event to a queue.
  • If the process crashes between the two steps, the post exists but followers may never receive it.

Solution:

  • Write the post and an outbox row in the same database transaction.
  • A background publisher reliably publishes outbox records to the event log.
  • Mark the outbox row delivered only after publication succeeds.

Invariant:

A successfully accepted post is either already published to the event stream or can be published after recovery.

# Idempotency

Queues are commonly at-least-once delivery systems. A fanout event may be received more than once.

Prevent duplicate timeline entries with:

unique(viewer_id, post_id)

Or use a deterministic event ID:

fanout_event_id = hash(post_id, viewer_id)

# 8. Feed retrieval path

# Steps

  1. Authenticate the viewer.
  2. Load cached block, mute, follow, and audience-policy information.
  3. Read materialized candidate IDs from the viewer’s feed timeline.
  4. Merge pull-on-read candidates, such as celebrity posts.
  5. Filter:
    • deleted posts;
    • blocked/muted authors;
    • invalid audience;
    • hidden/reported content;
    • expired or moderated content;
    • duplicates.
  6. Hydrate post bodies, author profiles, media URLs, counters, and viewer state.
  7. Rank a bounded candidate set.
  8. Return the page and a cursor.

# Cursor pagination

Use keyset/cursor pagination:

cursor = signed(
  feed_version,
  last_score,
  last_publish_time,
  last_post_id,
  filter_snapshot_version
)

Avoid OFFSET because it:

  • Gets slower for later pages.
  • Produces unstable results when posts are inserted/deleted.
  • Is expensive across distributed partitions.

A cursor does not create perfect snapshot isolation. Instead:

  • Deduplicate by post_id.
  • Keep a small seen-ID set in the client session.
  • Surface fresh posts after refresh or through a “new posts” indicator.

# 9. Fanout strategies

StrategyHow it worksBenefitMain cost
Fanout on writePush post ID to every follower feed after publishVery fast readsHuge write amplification
Fanout on readRead recent posts from all followed authors, merge and rank on requestCheap writesSlow/read-heavy
HybridPush normal authors; pull celebrities and cold usersBest balance at scaleMore complex merge logic

# Fanout on write

author posts
  -> retrieve followers
  -> append post ID to each follower timeline

Best for:

  • Normal authors.
  • Active followers.
  • Read-heavy systems.

Problems:

  • A celebrity with 10 M followers creates 10 M feed writes.
  • Inactive followers receive updates they may never read.
  • Can overload graph, queue, cache, and feed-store shards.

# Fanout on read

viewer opens feed
  -> retrieve followed authors
  -> retrieve their recent posts
  -> merge, filter, sort, rank

Best for:

  • Small systems.
  • Inactive users.
  • Very high-follower authors.
  • A source with low posting volume.

Problems:

  • One request can trigger hundreds of author/timeline reads.
  • Higher p99 latency.
  • Ranking and merging happen on the user-facing path.

# Recommended hybrid design

  • Push ordinary-author posts to active followers.
  • Pull celebrity/influencer posts on feed read.
  • Pull content for inactive users rather than precomputing their feeds.
  • Merge both candidate sources before ranking.
  • Make the threshold adaptive using:
    • follower count;
    • author post frequency;
    • queue lag;
    • current system load;
    • projected fanout writes.

Do not say “all celebrities use pull” without explaining the tradeoff.


# 10. Ranking

# Two-stage ranking

Stage 1: candidate generation

Retrieve a bounded set from:

  • materialized follower timeline;
  • celebrity pull candidates;
  • recommendations;
  • recently engaged-with authors;
  • optionally ads.

Stage 2: ranking

Apply a more expensive personalized model only to those candidates.

score =
  author_affinity
  + predicted_engagement
  + freshness_decay
  + content_quality
  + format/context signals
  - repetition_penalty
  - negative_feedback_penalty

# Policy and diversity rules

Ranking must never override hard eligibility:

  • audience/privacy;
  • blocks/mutes;
  • age/geography/legal restrictions;
  • deletion;
  • moderation/takedown state.

Add constraints such as:

  • maximum posts from one author in a page;
  • topic/media diversity;
  • no duplicate reshares;
  • reserve a small portion for fresh content;
  • negative feedback suppression.

# Ranking tradeoff

  • More personalization improves relevance.
  • More model work increases latency and cost.
  • Excessive personalization can create repetition and filter bubbles.

Fallback if ranker is unhealthy:

Return a filtered reverse-chronological feed rather than failing the home page.


# 11. Caching

CacheStoresKeyImportant behavior
CDNimages, video segments, thumbnailsversioned media URLimmutable/versioned objects
Feed cachecandidate IDs/ranked windowviewer_idbounded and rebuildable
Post cachepost body/statuspost_idinvalidate/update on edit/delete
Profile cachedisplay-safe author datauser_idTTL/versioned
Graph/privacy cachefollow/block/mute/audience stateviewer-author pairshort TTL + event invalidation
Counter cachelikes/comments/sharespost_idapproximate/eventual

# Cache-stampede protection

When a popular item expires, many requests can miss together and overload storage.

Use:

  • request coalescing/single-flight;
  • TTL jitter;
  • stale-while-revalidate;
  • bounded fallback;
  • rate limits;
  • cache warming for known hot keys.

# Cache principle

Caches improve latency; they must not be the sole source of truth.

A wiped feed cache must be rebuildable from durable posts, follow graph, and event history.


# 12. Storage and sharding

# Posts

Partition by author_id or post_id.

Useful index:

(author_id, created_at DESC)

This supports retrieving recent posts from an author in pull-on-read mode.

# Feed timeline

Partition by viewer_id.

Store a sorted/bounded collection:

viewer_id -> [(sort_key, post_id, source, preliminary_score)]

Keep only a configurable recent window, for example 500–2,000 candidates.

# Social graph

Maintain both views:

following(viewer_id) -> followee_ids
followers(author_id) -> follower_ids

Why both:

  • Feed retrieval needs whom a viewer follows.
  • Fanout needs who follows an author.

For very large accounts:

  • Split follower lists into shards/buckets.
  • Scan in pages.
  • Batch fanout writes.
  • Cache stable portions carefully.

# Counters

Viral posts create hot keys.

Do not continuously increment one global row for every like.

Use striped counters:

counter_shard = hash(user_id) mod N
(post_id, counter_shard) -> partial_count

Aggregate asynchronously for display.


# 13. Media and CDN

# Upload flow

  1. Client requests short-lived upload authorization.
  2. Client uploads directly to object storage.
  3. Media pipeline scans, validates, transcodes, and creates thumbnails.
  4. Post references the approved media ID.
  5. Feed returns CDN URLs or signed access tokens.

# Important details

  • Do not proxy large media through feed servers.
  • Use adaptive video renditions.
  • Use immutable/versioned object keys.
  • Use signed URLs/cookies for private media.
  • Delete/revoke media access when privacy/deletion changes.

# 14. Interactions and notifications

# Likes/reactions

Store exact viewer state:

(post_id, user_id) -> reaction_type

Use an idempotent mutation:

unique(post_id, user_id, reaction_type)

Show the viewer’s own successful action immediately; allow aggregate count to lag.

# Comments

  • Partition comments by post_id.
  • Paginate comments independently from the home feed.
  • Emit events for counters, notifications, and ranking features.

# Notifications

Notifications are not feed correctness.

  • A notification failure must not hide the post from the feed.
  • Coalesce events: “Asha and 12 others posted.”
  • Respect quiet hours, user preferences, mute/block status, and frequency caps.
  • Use idempotent delivery keys.

# 15. Privacy, deletes, and moderation

# Double privacy check

This is a major production insight.

Check eligibility:

  1. At fanout time to avoid unnecessary writes.
  2. At read time to prevent leaks after later policy changes.

Why read-time checking matters:

  • User unfollows.
  • User blocks author.
  • Author changes audience.
  • Content is deleted/taken down.
  • Moderation changes a post’s state.
  • Cache entries may be stale.

# Tombstone deletion pattern

Do not rely on immediately deleting every copy synchronously.

  1. Mark post deleted or unavailable.
  2. Emit a tombstone/deletion event.
  3. Filter at read time immediately.
  4. Asynchronously purge:
    • feed timelines;
    • feed/post caches;
    • search indexes;
    • recommendation candidates;
    • CDN/media access;
    • replicas.

Invariant:

A deleted or disallowed post must not be returned even if its stale feed entry remains temporarily stored.

# Moderation

A post can be:

pending -> allowed -> limited/removed

A moderation event should use the same revocation/tombstone path as deletion.


# 16. Consistency model

OperationConsistency expectation
Post creationdurable acknowledgment
Author viewing own postread-your-writes
Feed appearanceeventual; seconds acceptable
Rankingeventually consistent
Likes/comments counterseventual/approximate
Follow/block/privacy changefast, policy-safe enforcement
Delete/moderation removalimmediate read-time suppression plus async purge
Media deliveryimmutable/versioned object semantics

# Ordering

  • Preserve order for one author’s posts where possible.
  • Do not promise a globally exact ordering across all authors.
  • Feed order can change as rank signals arrive.

# 17. Failure modes and ideal interview answers

# “What if the queue is down?”

  • Accept writes only if the post plus outbox event are durable.
  • Retry outbox publication until the event log is available.
  • Do not synchronously fan out in the user request.
  • Queue recovery replays pending events.

# “What if fanout workers lag?”

  • Feed remains available from existing cached timelines.
  • Measure post-to-visible freshness lag.
  • Autoscale consumers, prioritize active users, batch writes.
  • Fall back to pulling recent author posts for missed content.
  • Protect read p99 over immediate perfect freshness.

# “What if Redis/feed cache is flushed?”

  • Cache is disposable.
  • Rebuild timelines from durable feed store, event replay, or post indexes.
  • Use request coalescing and gradual warmup to avoid stampedes.
  • Serve a smaller/fallback chronological feed temporarily.

# “What if a celebrity posts?”

  • Do not fan out synchronously to millions of followers.
  • Treat the author as pull-on-read.
  • Merge recent celebrity posts into follower feeds at read time.
  • Optionally precompute for highly active users only.

# “What if ranking is unavailable?”

  • Return a filtered, reverse-chronological feed.
  • Keep hard privacy/moderation filtering active.
  • Degrade relevance, not availability.

# “What if a user is blocked after feed entries were written?”

  • Read-time authorization filters the stale entry.
  • Graph/privacy event invalidates caches and asynchronously removes entries.

# “What if a post event is delivered twice?”

  • Consumer is idempotent.
  • Deduplicate with (viewer_id, post_id) or deterministic event IDs.

# 18. Reliability and observability

# Reliability patterns

  • Stateless API/feed services behind load balancers.
  • Replicated databases and event log across availability zones.
  • At-least-once events plus idempotent consumers.
  • Retries with exponential backoff.
  • Dead-letter queues for poison events.
  • Circuit breakers and bulkheads for slow dependencies.
  • Backpressure and quotas on fanout.
  • Graceful degradation to stale/chronological feeds.

# Metrics

AreaKey metrics
Feedp50/p95/p99 latency, availability, error rate, empty-feed rate
Cachehit rate, evictions, stampedes, fallback rate
Fanoutqueue depth, consumer lag, throughput, retries, DLQ volume
Freshnesspost-to-visible p50/p95/p99
Rankingcandidate count, scoring latency, fallback rate, diversity
Graphfollower lookup latency, hot partitions
Privacy/deleteinvalidation and suppression lag
MediaCDN hit rate, origin load, transcode failures
Productimpressions, dwell time, hides, reports, negative feedback

# 19. Multi-region design

Approach:

  • Serve feed reads from the nearest healthy region.
  • Use a user/account home region for strongly ordered writes.
  • Replicate posts/graph changes asynchronously where latency matters.
  • Accept short cross-region feed staleness.
  • Use globally unique event IDs and tombstones so replication converges.
  • During regional failover, replay durable events and warm caches gradually.

# 20. Design invariants

These are excellent interview statements.

  1. Never show unauthorized content.
  2. Never lose an accepted post event.
  3. A timeline entry may be duplicated internally, but a returned page must deduplicate posts.
  4. Deletion, privacy revocation, and moderation override cached data.
  5. Per-author order should be preserved; global feed order need not be strongly consistent.
  6. Caches are rebuildable optimizations, not the source of truth.
  7. Fanout must be asynchronous and bounded; user-facing writes must not wait for every follower.
  8. A degraded but safe chronological feed is better than a failed home feed.

# 21. Tradeoffs

DecisionDefaultWhy
Feed generationhybrid push/pullprotects read latency and celebrity write load
Feed storageIDs plus metadataavoids content duplication
Consistencyeventual feeds/counterspractical for availability and scale
Paginationopaque cursorscalable, stable infinite scroll
Mediaobject storage + CDNisolates large blobs from feed API
Rankingtwo-stage bounded rankingrelevance without unbounded latency
Delete/privacytombstones + read-time checkprevents stale-cache leaks
Multi-regionlocal reads, async replicationlow latency with acceptable staleness

# 22. Two-minute interview answer

I would split the system into a durable publish path and a low-latency read path. A post service stores the post and an outbox event atomically, then publishes that event to a durable log. Fanout workers fetch followers and append only post IDs to per-viewer timelines. The feed service reads those candidate IDs from cache or a feed store, merges pull-on-read celebrity candidates, filters using current privacy and moderation rules, hydrates post/profile data, ranks a bounded candidate set, and returns cursor-paginated results.

I would use fanout-on-write for normal authors because reads dominate writes, but avoid pushing celebrity posts to millions of followers. Instead, I would pull and merge those candidates at read time. Feed membership, ranking, and counters are eventually consistent, while accepted posts are durable and privacy/deletion checks are enforced at read time. Media lives in object storage behind a CDN, and the system degrades to a safe reverse-chronological feed if ranking or caching is impaired.


# 23. Suggested 40-minute walkthrough

  1. Clarify requirements and scale.
  2. State reads are dominant but fanout makes writes expensive.
  3. Present APIs and core data model.
  4. Draw publish and read paths.
  5. Explain fanout-on-write, fanout-on-read, and hybrid choice.
  6. Explain celebrity handling.
  7. Explain feed retrieval, cursor pagination, and ranking.
  8. Explain cache/store/sharding choices.
  9. Cover media/CDN and interaction counters.
  10. Finish with privacy/deletion, failure handling, observability, and multi-region tradeoffs.

# Final memorable statement

Optimize the home feed for fast, safe reads: asynchronously materialize bounded ID-only timelines for normal authors, pull celebrity content on demand, enforce privacy again at read time, and treat every cache as rebuildable.

Next→API Gateway

On this page

1. Problem framingScope2. RequirementsFunctional requirementsNon-functional requirementsClarifying questions to ask first3. Back-of-the-envelope sizing4. Core APIs5. Data modelCritical principle6. High-level architecture7. Publish pathFlowTransactional outbox patternIdempotency8. Feed retrieval pathStepsCursor pagination9. Fanout strategiesFanout on writeFanout on readRecommended hybrid design10. RankingTwo-stage rankingPolicy and diversity rulesRanking tradeoff11. CachingCache-stampede protectionCache principle12. Storage and shardingPostsFeed timelineSocial graphCounters13. Media and CDNUpload flowImportant details14. Interactions and notificationsLikes/reactionsCommentsNotifications15. Privacy, deletes, and moderationDouble privacy checkTombstone deletion patternModeration16. Consistency modelOrdering17. Failure modes and ideal interview answers“What if the queue is down?”“What if fanout workers lag?”“What if Redis/feed cache is flushed?”“What if a celebrity posts?”“What if ranking is unavailable?”“What if a user is blocked after feed entries were written?”“What if a post event is delivered twice?”18. Reliability and observabilityReliability patternsMetrics19. Multi-region design20. Design invariants21. Tradeoffs22. Two-minute interview answer23. Suggested 40-minute walkthroughFinal memorable statement