System Design · Worked case study
Designing a Social News Feed
Serve a responsive social feed with hybrid fanout while enforcing private-account, block, and deletion rules across caches and replicas.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Compare fanout-on-write and fanout-on-read using follower distributions and workload math.
- Build a hybrid feed that rechecks privacy, blocks, and deletion at response time.
- Explain cursor stability, ranking trade-offs, cache invalidation, and regional failure behavior.
Set feed behavior and privacy contract
Design a microblog-style educational social feed for short text posts, replies, follows, likes, and media references; actual media bytes come from a separate service. The product-style label describes only the interaction pattern; this is an original design, not an account of any company's architecture. A user sees recent posts from accounts they follow, with a ranked default and a chronological option. Assume 20 million registered users, 2 million daily active readers, and 300,000 active authors. Public posts are broadly visible; private accounts require accepted follow relationships. Blocks, mutes, deleted posts, and suspended accounts affect visibility. Exclude direct messages, live video, ads, trending discovery, and full-text search. The feed may be eventually consistent: a post can take seconds to appear, and like counts can be approximate, but private or deleted content must not leak because a fanout copy is stale. Define whether a private-account follow request grants access before acceptance (it must not), what happens to old posts after privacy changes, and how blocks affect replies and cached timeline entries. Use a simple transparent score initially: recency, relationship strength, and explicit quality signals, with caps that prevent a single source from dominating. Let the user switch to chronological ordering when ranking surprises them.
Model skewed author and reader traffic
Suppose 2 million daily readers open the feed 8 times per day: 16 million feed requests daily, about 185 requests/s average, with a 10× peak of 1,850/s. Each page requests 30 posts, giving 48 million post references per day, although cache hits reduce repeated author and post reads. If 300,000 authors create 4 posts daily, there are 1.2 million posts/day, roughly 14/s average and perhaps 170/s peak. A normal author with 250 followers creates at most 1,000 fanout references per day; a creator with 5 million followers creates 20 million references for the same four posts. That skew makes unconditional fanout-on-write unsafe. If feed references use 40 bytes before index overhead, fanout for the ordinary author is modest, but celebrity posts need to be merged at read time or asynchronously capped. A reader follows 400 accounts on average, while the top 1% follow 5,000; querying every followed author synchronously on each request is expensive. Use a precomputed inbox for ordinary authors, and fetch a bounded recent candidate set from high-follower authors at read time. Reserve 30% CPU and storage headroom and protect feed reads from backfill jobs. Revisit estimates for actual follower power-law distributions, active-follower overlap, and media-preview requests.
| Quantity | Illustrative calculation | Design consequence |
|---|---|---|
| Feed requests | 16M / 86,400 ≈ 185/s; 10× = 1,850/s | Cache and load-test bursty reads |
| Ordinary author fanout | 4 posts × 250 followers = 1,000 refs/day | Write fanout is affordable for typical accounts |
| Large creator fanout | 4 × 5M = 20M refs/day | Use threshold and read-time merge |
| Reference storage | 1.2M posts × active follower fanout | Measure skew and expire old inbox references |
Evolve from a simple monolith to hybrid fanout
A small application can store users, follows, posts, and a chronological query in PostgreSQL, with a cache for popular public profiles. It is an appropriate prototype and makes authorization understandable. It becomes slow when a reader follows hundreds of accounts, post reads scan too much history, and one popular author causes a large write burst. The next design writes a durable post event after the canonical post transaction. A fanout worker copies post IDs into inbox partitions for ordinary authors; high-follower authors are marked for read-time merge. Feed APIs fetch recent candidate IDs, batch-load post records, filter current privacy and deletion state, rank, and return a cursor. Post creation remains cheap and independent of delivering to every follower. The inbox is a derived index and can be rebuilt from posts plus follow relationships, but that rebuild is expensive and should be bounded by retained history. Follow changes, blocks, and privacy changes should update relationship state immediately, then invalidate or filter cached inbox entries. The design can scale database partitions by reader ID for inbox and author ID for posts, but cross-partition queries need explicit fanout or denormalization. Keep a canonical source for content and relationships; do not let an eventually consistent inbox become authority for access.
Validates and stores canonical post
Author-owned post records and versions
Durable publish event, keyed by author
Copy ordinary-author post IDs to reader inboxes
Reader partitions, derived recent references
Merge inbox with bounded high-follower candidates
Current follows, blocks, privacy, deletes
Ranked or chronological page
- Author API → Post store: canonical transaction
- Post store → Outbox and stream: committed post event
- Outbox and stream → Fanout workers: at-least-once work
- Fanout workers → Inbox store: ordinary author references
- Reader → Feed API: page request
- Feed API → Inbox store: precomputed candidates
- Feed API → Post store: candidate details
- Feed API → Visibility policy: current visibility filters
- Visibility policy → Reader: authorized page
Define feed APIs and canonical data
POST /v1/posts creates a post with a client idempotency key and returns canonical post ID and creation sequence. GET /v1/feed?mode=ranked&limit=30&cursor=... returns authorized post summaries, a signed cursor, and a feed generation; GET /v1/users/{id}/posts is separately scoped by profile visibility. Follow and block endpoints update relationship state synchronously and return the effective state. DELETE /v1/posts/{id} creates a tombstone and schedules physical cleanup. Core records include User(userId, privacyMode, stateVersion, suspendedAt), Follow(followerId, authorId, status, version), Block(blockerId, blockedId, createdAt), Post(postId, authorId, authorSequence, createdAt, body, visibilityVersion, deletedAt), InboxReference(readerId, authorId, postId, createdAt, fanoutVersion), and FeedCursor(readerId, mode, lastSortTuple, generation, expiresAt). Enforce one active follow relation per pair and idempotent post creation per client key. Media references must be separately authorized and signed with short-lived access. A feed cursor binds the reader, mode, ranking model version, and last stable sort tuple; it is not an entitlement. The API can return a short page if policy filtering removes candidates, rather than refilling from unbounded untrusted sources.
json · Illustrative example; validate before production use
{"mode":"ranked","limit":30,"cursor":"signed-reader-bound-token"}
{"posts":[{"id":"p_301","authorId":"u_44","createdAt":"2026-11-08T17:22:00Z","body":"A practical way to size a retry queue…"}],"nextCursor":"signed-reader-bound-token-2","feedGeneration":"rank-v6"}Trace publish, feed read, and deletion
On publish, authenticate the author, apply text and rate limits, allocate an author sequence, and commit the post plus an outbox event. The fanout consumer deduplicates by post ID and event version. If the author is ordinary, it writes references to recent active followers in bounded batches; if a threshold is exceeded, it stores the post once and marks it for read-time merge. On a read, the service obtains inbox candidates and recent posts from a bounded set of high-follower accounts, removes duplicates, loads canonical post fields, evaluates current visibility, then ranks. A private profile's posts require an accepted follow at the moment of reading. Deletion writes a tombstone first, invalidates caches, and makes the policy layer reject the post immediately; asynchronous cleanup removes copied references later. Privacy mode changes and blocks use the same immediate policy path. If a user follows an author, the feed may take a brief moment to include older content depending on product policy, but the access control must already be correct. Cursors use a stable timestamp-plus-ID or author sequence sort, and clients deduplicate by post ID across pages. Like counts can be fetched from a counter service and lag, but visibility cannot.
Requests ranked page with its own cursor
Authenticates and gathers bounded candidates
May contain stale or duplicate IDs
Authoritative current content and tombstones
Current follow, block, privacy and suspension state
Score only authorized candidates
Visible posts and reader-bound cursor
- Reader client → Feed API: feed request
- Feed API → Inbox references: ordinary candidates
- Feed API → Canonical post store: canonical batch load
- Feed API → Relationship policy: current policy lookup
- Canonical post store → Rank and paginate: non-deleted content
- Relationship policy → Rank and paginate: allowed IDs
- Rank and paginate → Response: stable sorted page
Reason about stale copies, privacy, and pagination
Fanout is at least once: repeated events may place duplicate references, so use a uniqueness key such as readerId+postId and idempotent upsert. A post edit or delete increments a canonical version; an older fanout event cannot override newer metadata. Do not copy full private bodies into inbox rows, and do not authorize from a cached follow snapshot. For every candidate, evaluate current block relationships, private-account follow acceptance, author suspension, and post deletion before constructing a response. Batch policy checks to control latency but bind cache entries to relationship versions and short invalidation windows. A block can race a response already in flight; define the practical boundary as the policy version observed when the request is authorized and ensure subsequent requests deny. Deletion needs tombstones retained beyond the maximum event replay and cache lifetime. A ranked cursor can become unstable as scores or relationships change; bind it to ranking version and last sort tuple, and deduplicate post IDs client-side. If a content item disappears, a page may be shorter. Never return an item from a prior cursor merely to fill the page. A chronological mode has clearer semantics but still must filter current privacy. Repair tools should compare canonical recent posts against expected inbox references and report missing or orphaned IDs without loosening access controls.
- Derived fanout may be eventually consistent; access control cannot be delegated to that derived store.
- Deletion and privacy revocation propagate as a hard deny first, then physical cleanup.
Recover fanout, cache, and regional incidents
A fanout worker outage creates delayed ordinary-author posts but should not block canonical publishing. The durable stream retains work; alert on oldest unprocessed event and per-shard lag. If inbox storage is down, feed reads can fall back to a bounded chronological query for followed accounts or serve a clearly stale page, but must preserve privacy filters and control load. If a cache is wrong, bypass or invalidate it; never use cache availability as a reason to skip current authorization. During a region failure, one region owns each author's canonical writes. A second region can serve replicas, but asynchronous lag means it may omit recent posts; it must not resurrect deleted content after a stale failover. Versioned tombstones and relationship state replicate with priority. On failover, fence the prior writer and establish a replication point before accepting new author sequences. Feed inboxes can be regenerated from canonical posts and follows within a retention horizon, but that is a large backfill; prioritize recent active users and show a freshness indicator while repair proceeds. A hot celebrity source can overload read-time merge, so cap candidates and use cached public post lists while rechecking privacy. Run region drills that include private-account revocation, not merely public timeline availability.
| Failure | Safe degradation | Recovery check |
|---|---|---|
| Fanout backlog | Serve slightly incomplete feed or bounded fallback | Lag and missing-reference sampling |
| Inbox partition loss | Rebuild from canonical posts/follows | Dedup and restore deletion tombstones |
| Policy cache outage | Bypass cache or fail closed for protected content | Verify current block and privacy decisions |
| Regional failover | Fence old owner; expose stale window for public data | Sequence continuity and denylist replication |
Limit abuse and prevent privacy leaks
A public social feed attracts spam, harassment, scraping, and coordinated manipulation. Validate post size and format, rate-limit by account and device, use risk-based controls, and provide reporting, blocking, muting, and appeals. Automated scoring can prioritize review but should not silently become the only enforcement mechanism. Protect private-account follow decisions from race conditions and unauthorized API access. Signed media URLs should be short-lived and scoped; changing a post to private must invalidate or outlive existing media links only for the documented cache window. Do not expose private follower lists, hidden post counts, or recommendation explanations that reveal sensitive relationships. Minimize behavioral logging, define retention and access controls, and distinguish public posts from private content in analytics pipelines. Content removal should propagate to feed caches, previews, notifications, search, and media references. Avoid placing full post bodies into logs or high-cardinality metrics. Abuse controls should not infer sensitive traits or punish entire shared networks. Test account enumeration, follow-request replay, blocked-user content access, deleted-post cursor replay, cache poisoning, bot rate bypass, and feed response injection. A moderation action should be auditable with actor, reason category, and policy version while retaining only necessary content evidence under a defined process.
- Every derived feed surface, including notifications and previews, must honor the same visibility policy.
- Treat a signed media URL as a temporary capability and document its expiry behavior.
Measure freshness, quality, and privacy outcomes
Feed read availability measures authorized pages returned for valid requests; a 99.9% monthly goal with p95 below 250 ms and p99 below 700 ms is a starting hypothesis. Publish freshness measures post commit to first eligible follower feed appearance, for example p95 under 10 seconds for ordinary authors; high-follower sources can have a separately defined objective. Track fanout backlog age, inbox write failures, candidate counts, policy-filter rate, cache hit rate, stale tombstone detections, and per-region replica lag. Ranking quality uses sampled human relevance judgments, hide/report rates, diversity, and successful interactions; engagement alone can reward harmful content. Privacy leakage has a zero-tolerance objective and synthetic tests should attempt access after block, private-mode change, deletion, and suspension. Measure page duplicates and cursor restart rates. Keep labels low-cardinality; author and reader IDs belong in controlled traces only when necessary and should be pseudonymized. Use separate dashboards for public and private surfaces. Error-budget policy can pause ranking experiments while continuing security fixes. Do not use a high cache-hit percentage as a proxy for freshness or correct authorization.
| Indicator | Measurement | Example target |
|---|---|---|
| Feed read latency | Authorized request to page response | p95 < 250 ms; p99 < 700 ms |
| Ordinary post freshness | Commit to first eligible inbox/feed visibility | p95 < 10 s |
| Privacy enforcement | Access after deletion/block/private transition | Zero confirmed leaks |
Compare fanout strategies and plan migration
An illustrative monthly cost at this scale might be $12,000 for canonical post and relationship storage with replicas, $9,000 for inbox partitions and caches, $6,000 for event processing and fanout workers, $5,000 for feed API compute, and $4,000 for logs, safety tooling, and regional recovery: about $36,000 before staffing and media delivery. Estimate actual spend from active-follower fanout, retention, and cache churn; total registered users alone is misleading. Full fanout-on-write yields fast reads but pays enormous write amplification for a few large authors. Full fanout-on-read avoids copied references but makes each request query many sources and can create unpredictable tail latency. Hybrid fanout trades complexity for bounded work. A follow graph adjacency service may help at scale but is unnecessary until relational or partitioned storage cannot meet measured needs. Migrate from a simple timeline by dual-writing references for a sampled cohort, compare canonical visible IDs and ordering, then switch reads while preserving a chronological fallback. Do not route a reader to two independently writable inbox systems. Backfill from canonical post and follow histories, retain tombstones, and canary privacy cases. Interview follow-ups include ranking feedback loops, private quote posts, post edits, deletion guarantees, content moderation, and a viral post that floods worker queues.
- Budget for remediation and moderation operations, not only feed serving.
- Measure cost per active reader and per delivered post reference to reveal celebrity skew.
Operate fanout backlogs without weakening privacy
When feed lag rises, operators should first isolate the hot author or partition and inspect queue age, worker error classes, inbox write latency, and policy service health. Increasing worker concurrency without limits can overload the relationship store and make every feed read slower. Apply per-author quotas, prioritize recent active followers, and keep high-follower fanout work on a separate lane. If a follower graph lookup is degraded, do not guess that a private follow was accepted; use the last authoritative relationship state or omit the post until it can be checked. Stale inbox records can be cleaned after policy filtering is confirmed, but a cleanup job must use post and visibility versions so it cannot delete a newer permitted reference. A privacy incident runbook should invalidate caches, deny the affected post or account, verify media links, and preserve a minimal audit trail before broad cleanup. After a backlog recovery, compare a sample of canonical posts against eligible feed candidates and inspect both duplicates and omissions. Record the oldest event age and the number of readers impacted, not just worker utilization. The service should communicate that feeds may be delayed while preserving a strict rule that delay is preferable to showing someone else's private or deleted content.
Terms in plain language
- Fanout-on-write
- Copying a new post reference into follower feed indexes when the author publishes.
- Fanout-on-read
- Combining recent posts from followed authors when a reader requests the feed.
- Celebrity threshold
- A workload-based rule that avoids copying one high-follower author's every post to all followers synchronously.
- Tombstone
- A durable deletion marker that prevents delayed replicas or cached references from restoring removed content.
Capacity lab
Change the assumptions and inspect the math. This teaching model assumes every request creates one stored record. Real systems separate reads, writes, uploads and background work.
- Average QPS
- 231.48
- daily users × requests per user / 86,400
- Peak QPS
- 1,157.41
- average QPS × peak multiplier
- Peak payload bandwidth (MB/s)
- 1.16
- peak QPS × bytes/request / 1,000,000
- Logical retained storage (GB)
- 600
- requests/day × bytes/request × retention / 1,000,000,000
- Replicated storage (GB)
- 1,800
- logical storage × stored copies
- Serving nodes
- 1
- ceil(peak QPS / (node throughput × utilization))
Decimal MB/GB, not MiB/GiB. Indexes, protocol overhead, compression, retries, backups and failover capacity are excluded. Measure throughput on your workload; this is not a sizing guarantee or a cloud price quote.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Defines general HTTP request semantics relevant to API behavior; it does not validate the hypothetical feed architecture.
Provides authoritative messaging delivery background for fanout events, not a source for the invented social-feed design.
Documents database constraints that can support canonical relationships and idempotency; it does not establish the full privacy policy.