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
| Requirement | Target example |
|---|---|
| Feed first-page latency | p95 < 300 ms |
| Feed availability | 99.99% |
| Post creation acknowledgment | < 500 ms after durable write |
| New-post propagation | seconds for normal authors |
| Consistency | eventual for feed/rank/counters; stronger for privacy/deletes |
| Scale | hundreds of millions of DAU |
| Durability | accepted post must not be lost |
Clarifying questions to ask first
- Is the feed chronological or ranked?
- Are relationships follows, friends, pages, groups, or all of them?
- What is the freshness requirement?
- Are media, likes, comments, and notifications in scope?
- How many DAU, feed opens/day, posts/day, follows/user, and max followers?
- Is eventual consistency acceptable?
- Do privacy, blocks, deletes, and moderation need immediate behavior?
3. Back-of-the-envelope sizing
Example assumptions:
| Item | Assumption | Result |
|---|---|---|
| DAU | 100 M | — |
| Feed opens/user/day | 10 | 1 B feed reads/day |
| Average read rate | 1 B / 86,400 | ~11.6 K RPS |
| Peak multiplier | 10x | ~116 K RPS |
| Posts/user/day | 0.2 | 20 M posts/day |
| Average post rate | 20 M / 86,400 | ~230 posts/s |
| Average followers | 300 | ~6 B potential fanout writes/day |
| Cached feed window | 500 post IDs/user | 50 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}/reportUse:
- 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
| Entity | Important fields | Storage approach |
|---|---|---|
| User | user_id, profile, settings | relational/KV |
| Follow edge | follower_id, followee_id | graph or adjacency-list KV store |
| Post | post_id, author_id, body, media, visibility, status, created_at | distributed post store |
| Media | media_id, object key, variants, status | object storage + metadata DB |
| Feed entry | viewer_id, post_id, sort key, source, score | feed store/cache |
| Reaction | post_id, user_id, type | interaction store |
| Comment | comment_id, post_id, author_id, body | partitioned comment store |
| Counter | post_id, count type | sharded counter store |
| Event | event_id, type, payload/version | durable 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:
- Write/publish path: create a post, durably emit an event, asynchronously distribute it.
- 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
- Authenticate the viewer.
- Load cached block, mute, follow, and audience-policy information.
- Read materialized candidate IDs from the viewer’s feed timeline.
- Merge pull-on-read candidates, such as celebrity posts.
- Filter:
- deleted posts;
- blocked/muted authors;
- invalid audience;
- hidden/reported content;
- expired or moderated content;
- duplicates.
- Hydrate post bodies, author profiles, media URLs, counters, and viewer state.
- Rank a bounded candidate set.
- 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
| Strategy | How it works | Benefit | Main cost |
|---|---|---|---|
| Fanout on write | Push post ID to every follower feed after publish | Very fast reads | Huge write amplification |
| Fanout on read | Read recent posts from all followed authors, merge and rank on request | Cheap writes | Slow/read-heavy |
| Hybrid | Push normal authors; pull celebrities and cold users | Best balance at scale | More complex merge logic |
Fanout on write
author posts
-> retrieve followers
-> append post ID to each follower timelineBest 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, rankBest 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_penaltyPolicy 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
| Cache | Stores | Key | Important behavior |
|---|---|---|---|
| CDN | images, video segments, thumbnails | versioned media URL | immutable/versioned objects |
| Feed cache | candidate IDs/ranked window | viewer_id | bounded and rebuildable |
| Post cache | post body/status | post_id | invalidate/update on edit/delete |
| Profile cache | display-safe author data | user_id | TTL/versioned |
| Graph/privacy cache | follow/block/mute/audience state | viewer-author pair | short TTL + event invalidation |
| Counter cache | likes/comments/shares | post_id | approximate/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_idsWhy 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_countAggregate asynchronously for display.
13. Media and CDN
Upload flow
- Client requests short-lived upload authorization.
- Client uploads directly to object storage.
- Media pipeline scans, validates, transcodes, and creates thumbnails.
- Post references the approved media ID.
- 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_typeUse 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:
- At fanout time to avoid unnecessary writes.
- 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.
- Mark post
deletedorunavailable. - Emit a tombstone/deletion event.
- Filter at read time immediately.
- 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/removedA moderation event should use the same revocation/tombstone path as deletion.
16. Consistency model
| Operation | Consistency expectation |
|---|---|
| Post creation | durable acknowledgment |
| Author viewing own post | read-your-writes |
| Feed appearance | eventual; seconds acceptable |
| Ranking | eventually consistent |
| Likes/comments counters | eventual/approximate |
| Follow/block/privacy change | fast, policy-safe enforcement |
| Delete/moderation removal | immediate read-time suppression plus async purge |
| Media delivery | immutable/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
| Area | Key metrics |
|---|---|
| Feed | p50/p95/p99 latency, availability, error rate, empty-feed rate |
| Cache | hit rate, evictions, stampedes, fallback rate |
| Fanout | queue depth, consumer lag, throughput, retries, DLQ volume |
| Freshness | post-to-visible p50/p95/p99 |
| Ranking | candidate count, scoring latency, fallback rate, diversity |
| Graph | follower lookup latency, hot partitions |
| Privacy/delete | invalidation and suppression lag |
| Media | CDN hit rate, origin load, transcode failures |
| Product | impressions, 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.
- Never show unauthorized content.
- Never lose an accepted post event.
- A timeline entry may be duplicated internally, but a returned page must deduplicate posts.
- Deletion, privacy revocation, and moderation override cached data.
- Per-author order should be preserved; global feed order need not be strongly consistent.
- Caches are rebuildable optimizations, not the source of truth.
- Fanout must be asynchronous and bounded; user-facing writes must not wait for every follower.
- A degraded but safe chronological feed is better than a failed home feed.
21. Tradeoffs
| Decision | Default | Why |
|---|---|---|
| Feed generation | hybrid push/pull | protects read latency and celebrity write load |
| Feed storage | IDs plus metadata | avoids content duplication |
| Consistency | eventual feeds/counters | practical for availability and scale |
| Pagination | opaque cursor | scalable, stable infinite scroll |
| Media | object storage + CDN | isolates large blobs from feed API |
| Ranking | two-stage bounded ranking | relevance without unbounded latency |
| Delete/privacy | tombstones + read-time check | prevents stale-cache leaks |
| Multi-region | local reads, async replication | low 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
- Clarify requirements and scale.
- State reads are dominant but fanout makes writes expensive.
- Present APIs and core data model.
- Draw publish and read paths.
- Explain fanout-on-write, fanout-on-read, and hybrid choice.
- Explain celebrity handling.
- Explain feed retrieval, cursor pagination, and ranking.
- Explain cache/store/sharding choices.
- Cover media/CDN and interaction counters.
- 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.