Markdown Editor

News Feed System Design Template (Reference Design)

Social feed: hybrid fan-out on write and read, celebrity threshold, ranking pipeline, feed cache, snapshot pagination, media

आर्किटेक्चर और सिस्टम डिज़ाइनपूर्णdesignnewsfeedmath
एडिटर में खोलें.md डाउनलोड करें

उपयोग कैसे करें: Use when building a follow-based feed. Fill the follower distribution (not just averages) before choosing the push/pull threshold. The main pitfall is pure fan-out on write, which breaks for accounts with huge followings.

प्रीव्यू

System Design: [News feed name]

Reference design for a social news feed: users follow other accounts and see a ranked, paginated feed of their posts. It covers hybrid fan-out (push for most authors, pull for accounts with very large followings), a ranking pipeline, feed caching, cursor pagination, media delivery and the consistency the product can tolerate. It follows the structure of the System Design Document template and is pre-filled with a worked design to adapt. Every value marked Example is an assumption: replace it and recompute.

Document control

FieldValue
Document ID[SDD-FEED-001]
System / feature[Home feed]
Version[0.1]
Status[Draft / In review / Approved / Implemented / Superseded]
Author(s)[@author]
Reviewers[@reviewer-1], [@reviewer-2]
Last updatedYYYY-MM-DD
Related[PRD], [Ranking model card], [ADR: fan-out strategy]

Approvals

RoleNameDecisionDate
Tech lead[@name][Approved / Changes requested]YYYY-MM-DD
Staff / principal engineer[@name][Decision]YYYY-MM-DD
SRE / operations[@name][Decision]YYYY-MM-DD
Ranking / ML lead[@name][Decision]YYYY-MM-DD
Trust and safety[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft for design review
0.2YYYY-MM-DD[@name]Example: Hybrid fan-out with threshold at 10 000 followers
0.3YYYY-MM-DD[@name]Example: Two-stage ranking (candidate retrieval, then scoring)
1.0YYYY-MM-DD[@name]Example: Approved

Contents

1. Overview

1.1 Problem statement

[Example: The current feed is computed on every request by querying posts from all followed accounts. p99 latency is 2.4 s for users following more than 1 000 accounts, the database is at 80% CPU at peak, and the order is purely chronological, so engagement drops when users follow active accounts.]

1.2 Proposed solution

[Example: When an author with fewer than 10 000 followers posts, a fan-out service writes the post ID into each follower's precomputed feed in an in-memory store (push). Posts from accounts above the threshold are fetched at read time and merged (pull). A feed service combines both candidate sets, filters blocked and deleted content, ranks with a lightweight model and returns a page with an opaque cursor. Post bodies and media are hydrated from caches and a CDN.]

1.3 Decisions requested from reviewers

IDQuestionRecommended optionSection
Q-01Example: Fan-out on write, on read, or hybrid?Hybrid, threshold 10 000 followers7.2, 10
Q-02Example: How long is the precomputed feed?800 entries per active user3.4, 7.3
Q-03Example: Do we fan out to inactive users?No; rebuild on return7.3
Q-04Example: Is pagination stable while new posts arrive?Yes, cursor holds a ranked snapshot ID7.5
[Q-nn][Question][Option][Section]

2. Requirements

2.1 Functional requirements

IDRequirementPriority
FR-01Example: Create a post with text and up to 4 images or one videoMust
FR-02Example: Follow and unfollow accountsMust
FR-03Example: Show a ranked home feed of followed accounts' postsMust
FR-04Example: Paginate with infinite scroll; no duplicates or skips within a sessionMust
FR-05Example: Show a "new posts" pill when fresh content is availableShould
FR-06Example: Remove deleted, blocked or muted content from feeds within 1 minMust
FR-07Example: Offer a chronological view as a user optionShould
[FR-nn][Requirement][Must / Should / Could]

2.2 Non-functional requirements

IDQualityTargetMeasured as
NFR-01LatencyExample: Feed page p99 at or below 250 ms server timeService metrics
NFR-02AvailabilityExample: 99.95% monthly for feed readsSynthetic checks
NFR-03FreshnessExample: A new post appears in followers' feeds within 10 s at p95Canary account probe
NFR-04DurabilityExample: No acknowledged post is lostRF=3, backups
NFR-05CorrectnessExample: Deleted posts never shown after 60 sDeletion probe
[NFR-nn][Quality][Target][Measurement]

2.3 Out of scope

  • [Example: recommendations from accounts the user does not follow]
  • [Example: ads insertion (separate design; reserved slots only)]
  • [Example: comments and reactions storage]
  • [Item deferred, with the release that will take it]

3. Capacity estimation

3.1 Assumptions

InputSymbolValueSource
Daily active usersUUExample: 300 millionGrowth plan
Feed page requests per user per dayvvExample: 10Product analytics
Posts per user per dayppExample: 0.2Product analytics
Average followers per author (below threshold)ffExample: 200Follow graph
Stored post record (text + metadata)sps_pExample: 1 KBSchema in 5.2
Feed entry (post ID + author ID + score)ses_eExample: 20 bytes7.3
Feed length kept per userLLExample: 800 entriesDecision Q-02
Peak to average factorkkExample: 3Traffic history

3.2 Throughput

Feed reads:

QPSread=U×v86 400=3×108×1086 400≈34 700 req/s,peak≈104 000 req/sQPS_{read} = \frac{U \times v}{86\,400} = \frac{3 \times 10^{8} \times 10}{86\,400} \approx 34\,700 \ \text{req/s}, \qquad \text{peak} \approx 104\,000 \ \text{req/s}

Posts:

Pday=U×p=6×107,QPSpost≈6×10786 400≈700 posts/s,peak≈2 100P_{day} = U \times p = 6 \times 10^{7}, \qquad QPS_{post} \approx \frac{6 \times 10^{7}}{86\,400} \approx 700 \ \text{posts/s}, \qquad \text{peak} \approx 2\,100

Fan-out writes (feed inserts):

Wfan=QPSpost×f≈700×200=140 000 inserts/s,peak≈420 000W_{fan} = QPS_{post} \times f \approx 700 \times 200 = 140\,000 \ \text{inserts/s}, \qquad \text{peak} \approx 420\,000

3.3 Why the celebrity case breaks push

One post from an account with 5×1075 \times 10^{7} followers would require 5×1075 \times 10^{7} inserts. At 420 000 inserts/s of spare capacity that single post would take about 2 minutes to fan out and would delay every other post behind it. This is why accounts above the threshold are pulled at read time.

3.4 Storage and memory

Posts per year:

Sposts=6×107×1 KB×365≈21.9 TB/year (≈66 TB with RF=3)S_{posts} = 6 \times 10^{7} \times 1 \ \text{KB} \times 365 \approx 21.9 \ \text{TB/year} \ (\approx 66 \ \text{TB with RF} = 3)

Precomputed feeds in memory (all daily active users):

Mfeed=U×L×se=3×108×800×20 B=4.8 TBM_{feed} = U \times L \times s_e = 3 \times 10^{8} \times 800 \times 20 \ \text{B} = 4.8 \ \text{TB}

With one replica that is 9.6 TB of memory, for example about 150 nodes with 64 GB usable each. Reducing LL to 400 halves it; measure how deep users actually scroll before deciding.

Media (separate object store):

Smedia=Pday×0.2×500 KB=6 TB/dayS_{media} = P_{day} \times 0.2 \times 500 \ \text{KB} = 6 \ \text{TB/day}

assuming 20% of posts carry media averaging 500 KB after compression.

3.5 Summary

QuantityEstimateDesign consequence
Feed reads~35 000/s average, ~104 000/s peakServe from precomputed in-memory feeds
Fan-out inserts~140 000/s average, ~420 000/s peakAsynchronous workers; skip inactive users
Feed memory~4.8 TB, ~9.6 TB with replicaSharded in-memory store; length cap
Post storage~22 TB/year logicalPartitioned post store; body cache
Media~6 TB/dayObject storage plus CDN, never through feed service

4. API design

4.1 Endpoints

MethodPathPurposeAuthIdempotent
POST/v1/postsCreate a postUser tokenWith Idempotency-Key
DELETE/v1/posts/{id}Delete own postUser tokenYes
GET/v1/feed?cursor=&limit=20Home feed pageUser tokenYes
GET/v1/feed/new-count?since=Count of newer items for the "new posts" pillUser tokenYes
PUT / DELETE/v1/follows/{accountId}Follow or unfollowUser tokenYes

4.2 Request and response examples

A feed page returns hydrated items plus an opaque cursor for the next page:

GET /v1/feed?limit=20 HTTP/1.1
Authorization: Bearer [token]
{
  "items": [
    {"postId": "p_7a91", "author": {"id": "a_12", "name": "City Library"}, "text": "Late opening hours start Monday.", "media": [{"type": "image", "url": "https://media.example/p_7a91/0.webp"}], "createdAt": "2026-03-14T08:01:00Z", "reason": "followed"}
  ],
  "nextCursor": "eyJzbmFwIjoiczg4MiIsIm9mZiI6MjB9"
}

4.3 Errors, limits and versioning

StatusProblem typeWhen
400invalid-cursorCursor malformed or expired (older than 30 min); client restarts from top
413media-too-largeUpload exceeds limit
429rate-limitedPost or follow rate exceeded; Retry-After set
  • Rate limits: [Example: 50 posts per hour, 400 follows per day per user].
  • Versioning: /v1 path prefix; feed item schema is additive only.

5. Data model

5.1 Entities

Posts, the follow graph and the per-user precomputed feed are the three core data sets; engagement events feed ranking.

5.2 Storage choices

DataStorePartition keyMain queriesWhy
PostsExample: Wide-column or sharded relational storepost_id (with author index)Get by IDs (batch); recent by authorBatch point reads for hydration
Follow graphExample: Sharded store with both directions materialisedfollower_id and followee_idFollowers of X (fan-out); followees of Y (pull)Both directions are hot
Precomputed feedsExample: In-memory sorted setsuser_idTop N by score; trim to LLSub-millisecond reads
Author recent postsIn-memory list per pull authorauthor_idLatest 200 postsCheap merge for celebrities
Engagement eventsEvent log, then feature storeuser_idRanking featuresStreaming aggregation
MediaObject storage + CDNContent hashGet by URLLarge objects off the hot path

6. High-level design

The write path (post, fan-out) and the read path (feed, rank, hydrate) share only the stores.

ComponentResponsibilityScales by
Post serviceValidate, store posts, emit events, handle deletesStateless replicas
Fan-out workersRead follower lists in pages, insert into active followers' feedsConsumer partitions
Feed serviceMerge pushed and pulled candidates, filter, call ranking, paginateStateless replicas
Ranking serviceScore candidates with featuresModel replicas, GPU or CPU
HydrationBatch fetch post bodies, author profiles, countersCache cluster size
[Component][Responsibility][Scaling unit]

7. Detailed design

7.1 Feed read (critical path)

The feed service reads the pushed feed and pulled candidates in parallel, then ranks and hydrates only the page it returns.

If ranking times out (budget 60 ms), the service falls back to base_score order (recency with author affinity) so the user always gets a page.

7.2 Hybrid fan-out

  • An account becomes a pull author when follower_count exceeds Example: 10 000, with hysteresis (back to push below 8 000) to avoid flapping.
  • Push: on a post event, workers page through the author's followers (1 000 per batch) and insert (post_id, author_id, base_score) into each active follower's sorted set, trimming to LL entries.
  • Pull: on read, the feed service fetches the latest posts of each pull author the user follows. Most users follow few such accounts; cap at Example: 200 pull authors per user, chosen by affinity.
  • Inactive users (no session for 14 days) are skipped during fan-out. When they return, the feed is rebuilt from followees' recent posts in the background, and the first page is served by a pull-only path meanwhile.

7.3 Feed cache layout

Each user's feed is a sorted set keyed by feed:{user_id}, scored by a time-decayed base score so trimming keeps the most relevant recent items. Entries hold IDs only; bodies live in the post cache so edits and deletes take effect without rewriting feeds. A deletion event adds the post to a short-lived tombstone set consulted by the filter step, and a background job removes the entries.

7.4 Ranking pipeline

StageInputOutputBudget
Candidate generationPushed feed + pulled authorsUp to 500 candidates20 ms
FilteringBlocks, mutes, deleted, already seen in last 24 hValid candidates5 ms
ScoringFeatures: author affinity, post age, engagement velocity, media typePredicted engagement score60 ms
Re-rankingDiversity rules (max 2 consecutive posts per author), freshness boostFinal order5 ms

A typical score combines predicted actions with weights and an age decay:

score=(∑awa P(a∣u,p))×e−λ tage,λ=ln⁡2h\text{score} = \left(\sum_{a} w_a \, P(a \mid u, p)\right) \times e^{-\lambda \, t_{age}}, \qquad \lambda = \frac{\ln 2}{h}

where hh is the half-life, for example 6 hours. Weights waw_a are set by product goals and reviewed for integrity effects (for example down-weighting predicted outrage).

7.5 Pagination and consistency model

  • The first page call stores the ranked list of up to 500 IDs as a snapshot for 30 minutes; the cursor encodes snapshot_id and offset. Later pages read the snapshot, so new posts never shift items and cause duplicates or skips.
  • New content is surfaced through new-count, and pulling to refresh creates a new snapshot.
  • Consistency: feeds are eventually consistent. A post appears in pushed feeds within seconds; follows take effect on the next snapshot; unfollows and blocks are enforced by the filter step at read time, so they apply immediately even before fan-out entries are cleaned up.
  • Read-your-writes: the author's own new posts are injected into their first page from the post service, independent of fan-out lag.

7.6 Media

Clients upload media directly to object storage with pre-signed URLs; a processing job produces resized WebP/AVIF variants and video renditions, and the post becomes visible only when its media are ready. Feed items reference CDN URLs with content-hash names so they can be cached for a year.

8. Scalability and performance

ConcernApproachLimit before redesign
Fan-out volumeSkip inactive users; pull authors above thresholdExample: ~1 million inserts/s with 512 worker partitions
Feed cache memoryLength cap, IDs only, active users onlyMemory per node; reshard by user_id hash
Hot postsPost body cache with request coalescingOne viral post at ~500 000 reads/s via local caches
Ranking costScore at most 500 candidates; cache scores per snapshotModel latency budget 60 ms
Follow graph readsFollowers paged; pull-author list cached per user[Limit]

Latency budget for a first feed page (target p99 250 ms):

StepBudget
Gateway and auth15 ms
Candidate fetch (parallel)30 ms
Merge and filter10 ms
Ranking60 ms
Hydration40 ms
Serialisation10 ms
Headroom85 ms

9. Reliability, security and operations

9.1 Failure modes

FailureImpactDetectionMitigation
Feed cache node lostAffected users get empty pushed feedsCache error ratePull-only fallback for those users; rebuild from followees in background
Fan-out backlogNew posts appear lateConsumer lagAutoscale workers; prioritise recent posts; NFR-03 alert
Ranking service downLower quality orderError and timeout rateFallback to base_score order
Post store partition unavailableSome posts cannot hydrateHydration miss rateDrop unhydratable items from the page rather than fail it
Deletion event lostDeleted post still shownDeletion probeFilter checks post state during hydration as a second guard
[Failure][Impact][Signal][Mitigation]

9.2 Security and abuse

ThreatControl
Private posts leaking to non-followersVisibility checked at hydration against current follow and audience settings
Spam accounts mass-following to harvest contentFollow rate limits, new-account restrictions
Coordinated inauthentic engagement gaming rankingEngagement features weighted by account trust; anomaly detection
Harmful content amplificationIntegrity classifiers feed a demotion signal; removal events honoured within 60 s
[Threat][Control]

9.3 Observability

SignalMetric or logAlert threshold
Feed latencyp50, p99p99 above 250 ms for 10 min
FreshnessCanary post visible in canary follower feedAbove 30 s
Fallback ratePages served without rankingAbove 2% for 10 min
Empty feedsPages with zero items for users with followeesAbove 0.1%
Fan-out lagConsumer lagAbove 60 s

9.4 Cost estimate

ItemUnit costQuantityMonthly cost
Feed cache memory[$/GB-month]Example: 9.6 TB[$]
Fan-out and feed services[$/node-month][n][$]
Ranking inference[$/million scores]Example: ~500 candidates x first pages[$]
Post store[$/TB-month]Example: 66 TB per year of growth[$]
Media storage and CDN egress[$/TB]Example: 180 TB/month new media[$]
Total[$]

10. Trade-offs and alternatives

DecisionOptionsChosenWhyWhat we give up
Fan-outPure push; pure pull; hybridHybridFast reads for most users, bounded write cost for celebritiesTwo candidate paths, threshold tuning
Feed contentsFull post copies; IDs onlyIDs onlySmall memory, edits and deletes apply instantlyHydration step on every read
Inactive usersFan out to all; skip inactiveSkipLarge saving in writes and memorySlower first load after a long absence
PaginationOffset; time cursor; snapshot cursorSnapshot cursorNo duplicates or skips while ranking changesSnapshot storage, 30 min expiry
RankingChronological; single heavy model; two-stageTwo-stage, light scorerFits latency budget, easy fallbackLess accuracy than a heavy model on all candidates
[Decision][Options][Chosen][Why][Cost]

11. Delivery plan and risks

11.1 Milestones

MilestoneScopeExit criterionTarget date
M1Push fan-out, chronological feed, cursor paginationp99 under 250 ms in shadow trafficYYYY-MM-DD
M2Pull authors and hybrid mergeCelebrity post visible to all followers in under 10 sYYYY-MM-DD
M3Ranking v1 behind experimentPositive or neutral on guardrail metrics in A/B testYYYY-MM-DD
M4Inactive-user skip and rebuildMemory down 30% with no freshness regressionYYYY-MM-DD

11.2 Rollout and rollback

[Example: Dual-write feeds for two weeks while the old query path serves traffic; compare outputs on 1% of requests. Switch reads per percentage of users; rollback switches reads back while dual writes continue.]

11.3 Risks

IDRiskLikelihoodImpactMitigationOwner
R-01Example: Threshold flapping causes duplicate or missing postsMediumMediumHysteresis; dedupe by post_id at merge[@name]
R-02Example: Ranking change harms wellbeing metricsMediumHighGuardrail metrics in every experiment; integrity review[@name]
R-03Example: Memory cost exceeds budgetMediumMediumReduce LL; compress entries[@name]
[R-nn][Risk][L / M / H][L / M / H][Mitigation][@name]

12. Appendices

12.1 Open questions

IDQuestionOwnerDue
OQ-01Example: Should muted keywords be filtered server side?[@name]YYYY-MM-DD
OQ-02Example: What half-life works per content type?[@name]YYYY-MM-DD
[OQ-nn][Question][@name]YYYY-MM-DD

12.2 Glossary

TermMeaning
Fan-out on write (push)Copy a post reference into followers' feeds when it is created
Fan-out on read (pull)Fetch followees' posts when the feed is requested
Pull authorAccount whose posts are fetched at read time because of follower count
HydrationReplacing IDs with full post and author data
Snapshot cursorCursor pointing at a stored ranked list for stable pagination
[Term][Meaning]

12.3 References

ReferenceUse
RFC 9110 HTTP SemanticsAPI methods and caching
RFC 9457 Problem Details for HTTP APIsError format in 4.3
[Internal ranking model card]Features and evaluation for 7.4

Standard and licence note

Based on common industry practice for social feed system design. This is a reference design to adapt: the numbers are illustrative assumptions, not measurements. Original text written for this collection. Template licence: MIT.

संबंधित टेम्पलेट