Social News Feed (Facebook and Instagram)
A blocked user receives an old cached feed page after fanout completed.
Topic tools
Layout updated
Problem statement
Design a home feed like Instagram or Facebook. Users can publish posts, follow accounts, and browse a ranked feed that respects who can see each post.
Functional requirements
- Publish posts and follow or unfollow accounts.
- Read a ranked feed with pagination.
- Apply privacy, block and delete changes.
Non-functional requirements
- Aim for feed under 300 ms and 99.95% availability.
- Show ordinary new posts within 5 s; always check privacy.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 100M DAU × 10 page reads/day = 1B pages/day ≈ 11.6k average; 5× peak ≈ 58k |
| 100M posts/day ≈ 1.16k writes/s average; 5× peak ≈ 5.8k/s |
| Illustrative 200 active recipients/post × 100M posts = 20B timeline inserts/day ≈ 231k/s average |
| 10M-followed author posting once generates 10M push tasks; one at 10k inserts/s needs 1,000 seconds |
| Backlog B / (consumer rate μ − arrival rate λ); require μ > λ |
Entities
| Entity / logical owner |
|---|
| Home timeline: (viewerId, bucket), ordered candidate keys |
| Author timeline: (authorId, time bucket), sort (sequence, postId) |
| Media: opaque object ID + derivatives + readiness state |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/posts {clientPostId, text, mediaIds, visibility} | Sharded PostgreSQL by authorId; unique (authorId, clientPostId). Same transaction stores Post, author sequence, and . Return the same postId on retry; reject payload mismatch. |
PUT/follows/{authorId}; DELETE /follows/{authorId} | Authoritative relationship rows with version and approval state in . Derived followee/follower adjacency indexes support reads; inverse updates use /, not an assumed cross- transaction. |
GET/feed?cursor=…&limit=20 | Opaque signed cursor binds viewer, /session, ranking version, position and expiry. Response has hydrated posts and nextCursor. Bound limit and candidate budget. |
DELETE/posts/{postId}; visibility update | Canonical or policy-version increment; emit invalidations. Read path checks latest authorized state before sending each page. |
High-level design
How to draw this design
- Publish a postPost service, PostgreSQL, and
- Build timelinesKafka, workers, follow graph, and Cassandra
- Collect and merge candidatesFeed query, Redis, and candidate merge
- Check access and serveVisibility check, ranking, reader, and media
Publish posts into candidate timelines, then merge and check visibility before returning a page.
- State ownership
- PostgreSQL owns posts and relationships. Timeline tables hold derived candidates.
- Scale
- Push ordinary posts and pull from authors with very large audiences.
- Correctness
- Check current visibility and keep the page cursor tied to a stable order.
- Failure and recovery
- Rebuild timelines from durable data and withhold restricted content if access cannot be verified.
- Edge
- Compute
- State
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 15 flow steps
High-level design component walkthrough
Publisher / Reader Clients
Idempotent publish; cursor reads
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Network retries and stale sessions
Connected operations: Publish post; Request feed page; Return feed page; Fetch media from
Post Write Service
Authenticate; validate; commit once
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Media readiness and policy checks
Connected operations: Publish post; Commit post and
PostgreSQL / Post DB + Outbox
Canonical post + event in one txn
Why, tradeoff and connected operations
PostgreSQL commits a post and its event together. Indexed post IDs and controlled visibility updates keep canonical content easy to manage. fits authoritative edits; large fan-out timelines are maintained separately as derived data.
Tradeoff: ownership; storage growth
Connected operations: Commit post and ; Relay committed post events
PostgreSQL: Follow and Visibility Graph
Store relationship rows by user, with independent keys and projections from post storage.
Why, tradeoff and connected operations
PostgreSQL stores follow and visibility relationships with useful user-based indexes. Transactions and constraints keep relationship changes consistent. Bounded adjacency queries do not require a graph database; this relationship workload is separate from post storage.
Tradeoff: High-degree users; stale indexes
Connected operations: Read follower pages; Read current policy
Fanout Workers
Batch ordinary-author post IDs
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Write amplification; replay lag
Connected operations: Process new post; Read follower pages; Project home and author timelines
Kafka / CDC / Stream
Durable replayable work
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: At-least-once; limits
Connected operations: Relay committed post events; Process new post
Cassandra: Home and Author Timelines
Store two rebuildable timeline tables, keyed by viewer and author respectively.
Why, tradeoff and connected operations
Cassandra stores ordered candidate IDs by viewer or author. These predictable access patterns suit high fan-out writes and paginated timeline reads. Unlike canonical posts in , timelines are denormalized projections that can be rebuilt.
Tradeoff: Rebuildable; never policy authority
Connected operations: Project home and author timelines; Read durable candidates; Refresh recent candidate cache
Feed Query / Merge
Push + pull candidates; deduplicate
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Bound work; partial freshness
Connected operations: Request feed page; Read recent candidate IDs; Read durable candidates; Check current visibility
Visibility / Block Gate
Authorize current post version
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Fail closed when authority is absent
Connected operations: Check current visibility; Read current policy; Rank and allowed posts
Rank + Hydrate / Response
Stable page session; fallback order
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Ranking cost; expiry
Connected operations: Rank and allowed posts; Return feed page
Object Storage + CDN
Direct upload; cached media delivery
Why, tradeoff and connected operations
Object storage retains uploaded photos and videos, while a delivers popular bytes nearby. This keeps media size and bandwidth out of the post database. stores metadata and visibility; object storage stores large files.
Tradeoff: Egress cost; revocation window
Connected operations: Fetch media from
Redis Timeline Head
Cache recently read candidate IDs.
Why, tradeoff and connected operations
Redis caches the most recently requested timeline IDs. It reduces repeated reads of hot timeline partitions. It is a rebuildable memory layer over Cassandra, not the post or privacy authority.
Tradeoff: Cached candidates may be stale. Recheck visibility when serving.
Connected operations: Read recent candidate IDs; Refresh recent candidate cache
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Additional technical detail
End-to-end: Commit a post and atomically → durable event → ordinary-author push / celebrity pull → merge candidate IDs → current visibility checks → rank and → return a stable page plus media URLs. Media bytes bypass feed servers.
1 · Scope, guarantees, and a 45-minute interview plan
Design a Facebook/Instagram-style home feed for followed accounts: publish text/photo/video posts, follow/unfollow, browse a ranked feed, paginate, and delete or restrict posts. Clarify public versus private accounts, mutual friendship versus one-way following, and whether recommendations are in scope. Comments, ads, Stories, and training an ML model are extensions; a heuristic ranker is sufficient here.
- Availability/freshness: target 99.95% feed-read availability, server page latency under 300 ms, and ordinary-author propagation within 5 seconds in healthy conditions. These are design targets, not product measurements. A stale feed is acceptable; unauthorized content is not.
- Consistency: read-your-own-post via an authoritative overlay; other viewers see eventual feed insertion. Strong authorization at the serving boundary for private content. No global chronological order across authors.
- Drive the interview: 0–5 min scope; 5–10 scale//state; 10–20 architecture; 20–32 hybrid and correctness; 32–42 failures/regions; 42–45 final synthesis. State each decision, reason, and tradeoff, then stop.
2 · Scale assumptions and capacity math
| Assumption / calculation | Design implication |
|---|---|
| 100M DAU × 10 page reads/day = 1B pages/day ≈ 11.6k average; 5× peak ≈ 58k | At 20 posts/page, peak hydration demand is up to 1.16M object lookups/s before batching and cache hits. |
| 100M posts/day ≈ 1.16k writes/s average; 5× peak ≈ 5.8k/s | At 1 KB metadata/post: 100 GB/day raw; 30 days ≈ 3 TB before indexes and replication. Media is a separate budget. |
| Illustrative 200 active recipients/post × 100M posts = 20B timeline inserts/day ≈ 231k/s average | At 32 bytes/entry: 640 GB/day raw insert volume. Keep only recent K IDs; hybrid avoids the celebrity tail. |
| 10M-followed author posting once generates 10M push tasks; one at 10k inserts/s needs 1,000 seconds | Partitioned batches help, but read-time pull is preferable when cost exceeds expected reads. |
| Backlog B / (consumer rate μ − arrival rate λ); require μ > λ | For B=120M, μ=600k/s, λ=400k/s: drain time 600 s. Lag and recovery headroom matter more than queue depth alone. |
3 · APIs and ownership of state
| / state | Key, storage, and guarantee |
|---|---|
POST /posts {clientPostId, text, mediaIds, visibility} | Sharded PostgreSQL by authorId; unique (authorId, clientPostId). Same transaction stores Post, author sequence, and . Return the same postId on retry; reject payload mismatch. |
PUT /follows/{authorId}; DELETE /follows/{authorId} | Authoritative relationship rows with version and approval state in . Derived followee/follower adjacency indexes support reads; inverse updates use /, not an assumed cross- transaction. |
GET /feed?cursor=…&limit=20 | Opaque signed cursor binds viewer, /session, ranking version, position and expiry. Response has hydrated posts and nextCursor. Bound limit and candidate budget. |
DELETE /posts/{postId}; visibility update | Canonical or policy-version increment; emit invalidations. Read path checks latest authorized state before sending each page. |
| Home timeline: (viewerId, bucket), ordered candidate keys | Cassandra/Bigtable-style wide-column index for bounded ranges; Redis caches hot head IDs. by (viewerId, postId) is idempotent. Rebuild from source posts and follow graph. |
| Author timeline: (authorId, time bucket), sort (sequence, postId) | Wide-column projection of published posts; hot recent slices replicated in caches. Buckets cap partition size; extremely hot authors need read replication and, if necessary, stripes. |
| Media: opaque object ID + derivatives + readiness state | Object storage and . Signed upload, size/content validation, asynchronous transcoding, then READY metadata; do not publish broken media. Garbage-collect orphan uploads after a grace period. |
4 · Write path, read path, and hybrid fanout
- Publish: authorize the writer; resolve ready media; commit post + + stable request key together. A lost response is retried with the same key. /relay publishes after commit; consumer replays the same candidate, never duplicate a post.
- Ordinary authors: workers page through followers, split work by follower ranges, and write post IDs to bounded home timelines. batches only after writes. Prioritize recently active followers; inactive users rebuild on return.
- Celebrities: keep posts in author timelines and merge at read time. Choose the cutoff using posting rate × active followers versus follower read demand and latency, not a magic follower number. Cache/ popular author slices.
- Read: authenticate viewer → fetch home IDs and high-degree followee IDs in parallel → bounded pull of recent author slices → deduplicate by postId → batch → visibility/block/deletion checks → lightweight score and diversity constraints → return top K and references.
- Ranking: recency, relationship strength, and engagement are enough for this infrastructure interview. If optional ranking/features time out, use eligible cached candidates in recency order; never bypass the visibility gate.
- Mode changes: a versioned author mode with a transition allows a temporary overlap of push and pull. Deduplicate during overlap; stop the old mode only after backfill/catch-up. Otherwise a threshold change can lose or duplicate candidates.
5 · Correctness under concurrency
| Pressure point | Decision → reason → tradeoff |
|---|---|
| DB write succeeds; Kafka publish fails | row and post share one local transaction. Relay retries until durable publication; consumers deduplicate eventId/postId and compare versions. There is no -to-Kafka write. |
| Delete / private-account change races with old | is only a candidate index. Hydration checks canonical and authorized policy version, so old candidates cannot resurrect visible content. Tombstones outlive replay windows; expired events are rejected or revalidated. |
| Privacy cache is stale | For private posts, validate against a current authority or a provably current policy ; fail closed if unavailable. Async invalidation alone gives only bounded staleness. Public media already downloaded cannot be revoked. |
| Block/unfollow during pagination | Re-evaluate authorization on every page. Unfollow stops future candidate inclusion and may filter existing entries per agreed product semantics; block is a security decision and uses the strict gate. |
| New post or re-ranking shifts page boundaries | Freeze a bounded candidate ordering in a short-lived page session; cursor carries ID and last position with a stable postId tie-breaker. New posts arrive on refresh. Expired sessions explicitly restart; do not silently promise gap-free infinite scrolling. |
| Read-your-writes with a lagging feed projection | Overlay the author’s freshly committed posts from the owner, or use a write and wait/read owner. Other feeds remain eventual. A client optimistic tile alone is not a server read guarantee. |
| Follow accepted after a post is published | Backfill a bounded recent author window after follow approval; reconcile against current relationship state. Version relationship changes so delayed add events cannot override newer removal. |
6 · STATE → SCALE → CORRECTNESS → FAILURE → MULTI-REGION
| Failure / bottleneck | Response and relaxed guarantee |
|---|---|
| One hot viewer, celebrity, or graph partition | Hash home timelines by viewer; split high-degree follower lists into pages/stripes; replicate author caches; batch hydration. A single hot key needs replication or explicit splitting, not merely more hash slots. |
| Redis loss / cache stampede | Fall back to bounded durable-index reads; misses, TTLs, use admission control and per-dependency budgets. Serve a shorter eligible feed or return overload instead of rebuilding every user at once. |
| Worker crash / poisoned event / growing lag | At-least-once replay with idempotent writes, retry budgets and /quarantine with alert + repair. Pause low-priority backfills first. Show older content while catch-up runs; do not acknowledge lost work. |
| Ranker / graph / canonical-store outage | Fallback recency ranking; bounded cached graph candidates where safe. Missing authoritative visibility means omit those posts. A partial page or error is preferable to serving restricted content. |
| Regional failure | Serve regional read replicas and rebuildable caches; route author writes to a home authority with fenced failover. Async cross-region post replication permits nonzero . If zero loss is required, synchronously replicate acceptance across regions and pay WAN latency. |
| Network partition | One -selected owner per author ; fence old writers with epochs. Minority cannot publish or change protected policy. Cached public reads can continue; private reads need valid authority. Availability and freshness are explicitly relaxed. |
| Reshard / configuration rollout | Backfill then replay changes to a , validate counts/checksums, switch versioned routing and fence old owner. Canary /ranking changes with kill switches; preserve dedup keys and schema compatibility. |
7 · Operations, abuse, and cost
- Observe: p50// page latency by stage; publish-to-feed freshness; age, partition lag and estimated drain time; cache miss/coalescing ratio; amplification; empty/partial feed rate; duplicate candidates; deletion propagation and authorization failures. Trace a postId from commit to first served impression without logging private payloads.
- Protect: rate-limit per account/device/IP, prevent scraping and spam, authorize object access, validate uploads, isolate transcoding, protect signed cursors, and audit policy changes. Private-media revocation requires an authorization-capable edge/origin or a stated short URL lifetime.
- Spend deliberately: cap timeline length, avoid dormant-user , batch writes and reads, cache shared celebrity slices, resize/compress media and use . Estimate media bandwidth and egress separately; it often dominates metadata storage.
8 · Interview pressure tests and 90-second synthesis
Pause before reading a solution: A celebrity posts to 50M followers; a delete races with a delayed event; Redis is empty; the author’s region is isolated; a cursor expires halfway through scrolling. For each, name the owner, boundary, recovery path, and guarantee you relax.
Final architecture: “I separate canonical posts and policy from rebuildable feed indexes. A post and commit together on the author’s . Workers push IDs for ordinary authors; reads pull celebrity timelines and merge with the home timeline. I batch- and recheck current visibility before ranking. Redis accelerates recent IDs, and serves media. Duplicate delivery is harmless because candidate writes are idempotent and versioned. During failures I accept stale or shorter feeds, but fail closed for restricted content. Author writes have one fenced regional authority; zero- failover would require synchronous cross-region replication. I watch feed freshness, amplification, latency, and recovery headroom.”
Background reading
The designs and capacity numbers above are proposed interview choices. These primary sources support the underlying patterns, not a claim that Meta uses this exact architecture.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Do not write millions of inbox entries for every celebrity post | Changing between push and pull needs overlap tracking and duplicate removal. Keep author history available to rebuild missing candidates. |
| Check permission again before showing a post | Withhold private content when current permission is uncertain. Optional ranking can degrade independently; privacy is not another ranking feature. |
| Keep page order stable and serving work limited | Expire saved lists explicitly and rebuild missing feed data from committed posts. More retained sessions cost memory but improve browsing continuity. |
| What happens if a region fails? | Asynchronous projections keep reads fast; synchronous global privacy authority is costlier and may reject reads when required evidence is unavailable. |
| Keep feed pages from doing too much work | Larger candidate pools may improve ranking but increase latency, remote calls and the chance of running out of request budget. |
Production scars & failure modes
A blocked user receives an old cached feed page after fanout completed.
Look for: Inspect policy version, cache age and final hydration authorization.
Recovery and invariant: Treat timeline IDs as candidates; recheck current block/privacy state before exposing content. deletion is cleanup, not the security boundary.
| Component / failure | Required behavior / recovery | Operational implication |
|---|---|---|
| DB write succeeds; Kafka publish fails | row and post share one local transaction. | Relay retries until durable publication; consumers deduplicate eventId/postId and compare versions There is no -to-Kafka write. |
| Delete / private-account change races with old | is only a candidate index. | Hydration checks canonical and authorized policy version, so old candidates cannot resurrect visible content Tombstones outlive replay windows; expired events are rejected or revalidated. |
| Privacy cache is stale | For private posts, validate against a current authority or a provably current policy ; fail closed if unavailable. | Async invalidation alone gives only bounded staleness Public media already downloaded cannot be revoked. |
| Block/unfollow during pagination | Re-evaluate authorization on every page. | Unfollow stops future candidate inclusion and may filter existing entries per agreed product semantics; block is a security decision and uses the strict gate. |
| New post or re-ranking shifts page boundaries | Freeze a bounded candidate ordering in a short-lived page session; cursor carries ID and last position with a stable postId tie-breaker. | New posts arrive on refresh Expired sessions explicitly restart; do not silently promise gap-free infinite scrolling. |
| Read-your-writes with a lagging feed projection | Overlay the author’s freshly committed posts from the owner, or use a write and wait/read owner. | Other feeds remain eventual A client optimistic tile alone is not a server read guarantee. |
| Follow accepted after a post is published | Backfill a bounded recent author window after follow approval; reconcile against current relationship state. | Version relationship changes so delayed add events cannot override newer removal. |
90-second interview summary
I would separate canonical post writes from derived timeline serving. A post transaction records the post and publication intent, while background workers prepare home-timeline IDs. Ordinary authors use on write; very high-degree authors keep recent author timelines that readers merge in bounded slices.
The read service combines those candidates, removes duplicates and ranks/hydrates within a request budget. Cassandra holds durable timeline projections and Redis caches hot heads. A session and opaque cursor stabilize pagination even while new posts arrive.
Candidate presence is not permission. Before returning content, the system checks current visibility, block and deletion state. Old cached pages or delayed cleanup must not expose a post that became private. Retried projection work uses stable post/version identities and is rebuildable from canonical source history.
I would isolate hot authors, cap candidate amplification and monitor lag, hydration cost and policy failures. Regional timelines may differ temporarily, while canonical visibility has a fenced authority and uncertain private access is withheld. The tradeoff is extra projection and cache complexity for fast reads, plus a deliberate push/pull balance rather than treating every follower relationship as equal-cost work.
Explain it without looking
Explain do not write millions of inbox entries for every celebrity post
Reveal answer
Prepare ordinary feeds in advance and merge popular-author posts when users read.
A single celebrity post can otherwise delay the background work for everyone else.
Changing between push and pull needs overlap tracking and duplicate removal. Keep author history available to rebuild missing candidates.
Explain check permission again before showing a post
Reveal answer
Treat cached timeline IDs as candidates, not proof of access.
A post can become private after its ID was written into a follower's feed.
Withhold private content when current permission is uncertain. Optional ranking can degrade independently; privacy is not another ranking feature.
Explain keep page order stable and serving work limited
Reveal answer
Use a saved candidate order and cap merging and article lookups.
Re-ranking each page can skip or repeat posts and turn one slow source into a slow whole page.
Expire saved lists explicitly and rebuild missing feed data from committed posts. More retained sessions cost memory but improve browsing continuity.
Explain what happens if a region fails?
Reveal answer
Keep checking current privacy even when regional feed copies are behind.
A feed can degrade in relevance while still respecting the security boundary.
Asynchronous projections keep reads fast; synchronous global privacy authority is costlier and may reject reads when required evidence is unavailable.
Explain keep feed pages from doing too much work
Reveal answer
Limit how many candidates and article lookups one feed page can request.
Hybrid changes where the work happens; it does not remove that work.
Larger candidate pools may improve ranking but increase latency, remote calls and the chance of running out of request budget.
Revision checklist
Revision checklist
- Reconstruct do not write millions of inbox entries for every celebrity post: Prepare ordinary feeds in advance and merge popular-author posts when users read.
- Reconstruct check permission again before showing a post: Treat cached timeline IDs as candidates, not proof of access.
- Reconstruct keep page order stable and serving work limited: Use a saved candidate order and cap merging and article lookups.
- Reconstruct what happens if a region fails?: Keep checking current privacy even when regional feed copies are behind.
- Reconstruct keep feed pages from doing too much work: Limit how many candidates and article lookups one feed page can request.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope posting and reading a home feed. Estimate read traffic and highlight authors with unusually large audiences. |
| 15–30 min | High-level design | Trace a post through its and workers, then a reader request through candidate merge, visibility checks, and ranking. |
| 30–45 min | Deep dives | Explain hybrid push and pull . Show how a stable cursor and a current visibility check work together. |
| 45–55 min | Failure and recovery | Walk through a backlog or stale privacy projection. Rebuild candidates and fail closed when restricted access is uncertain. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough