News Feed (Scaling & Ranking)

A news feed aggregates content from the people or entities you follow, orders it, and returns a page fast. The design question is when the aggregation happens: on write, on read, or both. Every other decision — ranking, caching, deletes, backfills — follows from that choice.

A feed is a derived view, not a source of truth. Posts are the truth. Feed entries are a cache that can be rebuilt. Systems get into trouble when they start treating the derived view as authoritative.

Scope

In scope for v1

  • Create posts (text + media references).
  • Follow/unfollow users.
  • Home feed: posts from followees, newest or ranked, cursor paginated.
  • Profile feed.
  • Like/reply counts (eventually consistent).
  • Delete and edit with visible tombstones.
  • Private accounts with follow approval (optional v1).

Out of scope for v1

  • Ads, recommendations, trending.
  • Full-text search.
  • Edit history.
  • Moderation tooling (but leave hooks).
  • Cross-region active-active feed writes.

Actors and journeys

Actor Goal What can go wrong
Reader Open the feed and see fresh, relevant posts Empty feed, duplicates, stale pages, deleted content
Author Publish to followers quickly Fan-out lag, celebrity overload, post disappears
New follower See recent posts from a new followee Empty backfill, duplicate backfill
Moderator Remove harmful content Post remains in caches/feeds
Operator Keep read p99 low during a spike Cache stampede, hot shard, fan-out backlog

The critical journeys are:

  1. Publish a post and have it appear for followers within the freshness SLO.
  2. Page through a ranked feed without duplicates or skips.
  3. Delete a post and have it disappear everywhere.

Invariants

  1. Feed entries are derived and rebuildable. Deleting the feed store must not delete posts.
  2. A feed page is stable while the user pages through it. The order and cursor must not change due to new posts or a score recomputation.
  3. Cursors are (score, postId) pairs with a total order. Offset pagination is not allowed on a live feed.
  4. A deleted or private post never renders, even if it is still in a feed cache.
  5. Fan-out is asynchronous. Publishing must not wait for every follower’s feed to be written.
  6. Backfills are idempotent and bounded. Re-running a backfill must not duplicate entries.
  7. Hot authors do not block normal fan-out. One celebrity must not consume the entire worker pool.
  8. Ranking is deterministic for a frozen page window. A score change mid-session must not move an item behind the cursor.

Estimates

50M DAU × 5 sessions/day × 10 feed pages/session = 2.5B feed reads/day
average: ~29,000 RPS; peak: ~90,000 RPS
posts: 5M/day ≈ 58 RPS average
average followees: 200
write-time fan-out: 5M × 200 = 1B feed entries/day

Reads dominate. The fan-out strategy decides whether you pay on writes or reads. The follower distribution decides whether a uniform strategy is viable.

End-to-end flows

1. Publish a post

author
  → POST /posts
  → auth + rate limit
  → validate body/media references
  → insert post (source of truth)
  → publish event: post.created
  → return post immediately
  → async workers:
      → resolve followers (bounded batch)
      → write feed entries for normal accounts
      → mark celebrity posts for read-time merge
      → update author's profile feed
      → invalidate cached first pages of active followers

Failure branches:

  • Post insert succeeds, event publish fails: the post exists but fan-out did not start. A reconciliation job scans recent posts without a fan-out marker.
  • Fan-out worker dies: retry the batch idempotently. Do not re-publish the post.
  • Follower list is huge: split into batches, cap concurrency, and apply a per-author budget.
  • Media upload incomplete: publish only after media is confirmed, or publish with a placeholder and patch later. Do not create feed entries with broken URLs.

2. Read the home feed

reader
  → GET /feed?cursor=...
  → auth
  → try first-page cache (short TTL, per user)
  → if miss:
      → read precomputed feed entries for normal followees
      → merge recent posts from celebrities/large accounts
      → hydrate post metadata (batch, not N+1)
      → filter deleted/private/blocked
      → rank and freeze order for this page window
      → generate next cursor
  → return page + cursor

The merge is where most bugs live:

  • Deduplicate posts that appear in both the precomputed feed and the celebrity merge.
  • Bound the merge by time and count: “last 50 posts from accounts with >1M followers in the last 7 days.”
  • Hydrate in batches; a feed of 50 posts must not trigger 50 separate queries.
  • Filter after hydration so deleted/private posts do not consume page slots.
  • Freeze the ranking window so the next page uses the same score inputs.

3. Follow a user

reader
  → POST /follows/{userId}
  → validate target, block relationship, privacy
  → insert follow row (unique)
  → async backfill:
      → fetch last N posts or M days from followee
      → insert feed entries (upsert on user_id, post_id)
      → mark backfill cursor
  → invalidate the reader's first-page cache

Edge decisions:

  • Does a new follower see history? Decide by product: last 7 days, last 50 posts, or nothing.
  • Does the follow apply to posts created before the follow? Usually the backfill does, but this is a product policy.
  • If the followee is private, the follow may be pending. Do not backfill until approved.

4. Unfollow a user

  • Remove the follow row immediately so new posts do not fan out.
  • Remove existing feed entries for that author asynchronously, or filter them at read time until the cleanup completes.
  • Invalidate the reader’s first page.
  • Decide whether the unfollow is retroactive for already-seen content; usually the feed should stop showing the author, even if old entries remain briefly.

5. Delete or edit a post

author/moderator
  → mark post deleted (tombstone), or update body with version
  → publish post.deleted / post.updated
  → workers remove or flag feed entries
  → invalidate caches for affected users
  → read path filters tombstones even if cache is stale

Rules:

  • The read path must filter tombstones. Async cleanup is not a correctness guarantee.
  • A deleted post must disappear from profile feeds, home feeds, and cached first pages.
  • An edit must not break ranking or cursor stability. If the score changes, either keep the old score for the current window or accept a controlled reorder.
  • Media deletion is separate from text deletion; purge object storage on a lifecycle, not inline.

6. Backfill and repair

A feed will drift. Plan for it:

  • Backfill on follow: bounded by count and age.
  • Repair job: rebuild a user’s feed from followees’ posts when entries are missing.
  • Reconciliation: compare a sample of feeds against a pull-model compute.
  • Idempotency: upsert on (user_id, post_id), never blind insert.
  • Rate limits: cap backfill work per user and per worker.
  • Progress: store a cursor per user/author so a restart can resume.

Data model and state

CREATE TABLE posts (
  id         uuid PRIMARY KEY,
  author_id  uuid NOT NULL,
  body       text,
  media_ref  text,
  created_at timestamptz NOT NULL,
  edited_at  timestamptz,
  deleted_at timestamptz,
  visibility text NOT NULL DEFAULT 'public'
);
CREATE INDEX posts_author_created_idx ON posts (author_id, created_at DESC, id DESC);

CREATE TABLE follows (
  follower_id uuid,
  followee_id uuid,
  created_at  timestamptz NOT NULL,
  PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX follows_followee_idx ON follows (followee_id);

CREATE TABLE feed_entries (
  user_id uuid,
  post_id uuid,
  author_id uuid,
  score   bigint,
  PRIMARY KEY (user_id, post_id)
);
CREATE INDEX feed_user_score_idx ON feed_entries (user_id, score DESC, post_id DESC);

Feed entries are a cache. Keep them in a store that can be rebuilt without touching posts. If you use Redis sorted sets, treat Redis as a cache and keep a durable rebuild source.

Ranking

Start with reverse chronological. If you add ranking:

  • Score = function of recency, affinity, engagement, and content type.
  • Compute at fan-out time (cheap, stale) or read time (fresh, expensive).
  • Keep a deterministic tiebreaker (post_id) for cursors.
  • Store the score used for ordering if it must be stable across pages.
  • Freeze the ranking window per session or page set.

A ranked feed with non-deterministic scores cannot paginate reliably. If scores change between page 1 and page 2, items can be skipped or duplicated. The fix is not a better score; it is a stable ordering contract.

Edge cases

Case Expected behavior Notes
Celebrity with 100M followers Do not write 100M entries synchronously Merge their recent posts at read time
New follower of a celebrity Backfill is bounded; merge covers recent posts Do not rely on backfill alone
Unfollow mid-page Author disappears from subsequent pages Filter at read time until cleanup
Post deleted after page 1 Not shown on page 2 Tombstone filter
Post edited after page 1 Stable ordering; body may update Versioned hydration
Duplicate post in precomputed + merge Deduplicate by post id Merge path must dedupe
Empty feed Return empty state, not an error New users need onboarding
Followee posted between pages New post appears above cursor; not duplicated Cursor is exclusive
Cursor points to deleted post Continue from a stable score/id boundary Cursor must not depend on the deleted row existing
Cache stampede on a hot user Single-flight, jittered TTL Do not let all requests hit the DB
Hot shard by user id Shard uniformly; bound page size A single viral user can overload one shard
Private account request Filter before hydration Do not leak existence
Blocked relationship Filter both directions Block is not just a UI feature
Media object missing Show a placeholder or omit; do not break the feed Hydration must be resilient
Like count stale Render count with eventual consistency Do not block feed on counts
Backfill re-run Upsert, no duplicates Idempotency
Fan-out worker restarts Resume from cursor; no duplicate entries Durable progress
Ranking score changes Frozen window or versioned score Cursor correctness
Clock skew Order by stored score/time from one source Do not trust client time

Failure modes and recovery

Failure Impact Detection Mitigation Recovery
Fan-out backlog Followers see stale feeds Queue depth, fan-out lag Autoscale workers, priority queues Drain backlog; repair missing entries
Celebrity post Queue explosion Per-author fan-out cost Read-time merge, per-author budget Skip write fan-out; merge at read
Cache stampede DB meltdown Miss rate, DB QPS Single-flight, jitter, stale-while-revalidate Warm cache gradually
Missing feed entries Empty or incomplete feed Empty-rate, sample compares Repair job, pull fallback Rebuild affected users
Deleted post in cache Policy violation Synthetic checks, reports Tombstone filter at read Purge caches; audit fan-out
Hot shard Latency for a subset Shard QPS/CPU Uniform sharding, page caps Rebalance; dedicated hot tier
Offset pagination Duplicates/skips Cursor audit Keyset cursors Migrate clients; freeze windows
Ranking service down Feed fails or falls back Error rate Fallback to chronological Serve fallback; alert
Backfill overload DB/worker saturation Backfill rate Per-user caps, token bucket Pause low-priority backfills
Post hydration N+1 Read latency Query count Batch hydration, cache Add batching; fix queries

Degraded-mode rules:

  1. Serve a chronological fallback if ranking is unavailable.
  2. Prefer a slightly stale feed over a failed feed.
  3. Prefer filtering a deleted post late over showing it forever. The read path must filter.
  4. Prefer a bounded pull fallback over an empty screen when feed entries are missing.

Operations

Backfill and repair

  • Run backfills in a separate worker pool from live fan-out.
  • Cap per-user and per-author work; use fairness scheduling.
  • Store progress so restarts do not start over.
  • Compare rebuilt feeds against a pull-model sample; alert on drift.
  • Run a nightly repair for users with recent empty or short feeds.

Cache operations

  • Cache first pages only, not full histories.
  • Use short TTLs and jitter to avoid synchronized expiry.
  • Invalidate on post create/delete for active users; otherwise accept bounded staleness.
  • Protect with single-flight and request collapsing.

Monitoring

  • Feed read p50/p95/p99, empty rate, duplicate rate.
  • Fan-out lag, queue depth, per-author fan-out cost.
  • Cache hit ratio and stampede indicators.
  • Backfill progress and repair drift.
  • Deleted-post sightings and filter counts.
  • Hot shard QPS and latency.

Incident process

  1. Is the feed empty, stale, or wrong? Check read errors, fan-out lag, and repair drift.
  2. Is it global or a subset? Check cache, shard, region, and author distribution.
  3. Contain: serve chronological fallback, pause backfills, raise cache TTL, shed ranking.
  4. Recover: drain fan-out, repair affected users, purge deleted posts, verify with a sample.
  5. Learn: add an alert or invariant; add a regression test for the failure.

Testing strategy

  • Cursor stability: insert/delete/rank changes between pages; assert no duplicates or skips.
  • Fan-out: normal, celebrity, 100k followers; assert bounded worker usage.
  • Idempotency: replay fan-out and backfill; assert one entry per user/post.
  • Deletes: delete between pages, in cache, during hydration.
  • Follow/unfollow races: follow while posting; unfollow while reading.
  • Cache: stampede, expiry jitter, cold cache, stale first page.
  • Load: peak read RPS, hot shard, empty feed, ranked feed.
  • Chaos: kill fan-out workers, pause ranking, fill queue, delay DB.

Milestones and acceptance criteria

Milestone Build Accept when
1. Posts + follow Post/follow schema, profile feed A post appears on the author’s profile; follow is unique
2. Pull feed Merge followees’ posts at read time Correct chronological feed with stable cursor
3. Cache First-page cache + invalidation Peak reads hit cache; cold cache stays within latency budget
4. Hybrid fan-out Write fan-out for normal accounts Normal posts appear without read-time merge cost
5. Celebrity path Read-time merge for hot authors Celebrity post does not explode the fan-out queue
6. Ranking Deterministic score + frozen window Paging remains stable under score changes
7. Delete/repair Tombstones + backfill/repair jobs Deleted posts vanish; missing entries can be rebuilt
8. Drills Load + chaos Hot shard, queue backlog, and cache stampede meet recovery SLO

Review questions

  • Why did you choose write vs read fan-out for each account class?
  • How does a user with 50M followers publish without blocking everyone else?
  • How do you paginate a ranked feed without duplicates or skips?
  • What happens when a post is deleted between page 1 and page 2?
  • What is the cache hit ratio and the fallback at 0%?
  • How fresh is a new post for a follower, and what is the SLO?
  • How do you repair a feed that has drifted?
  • Which path fails closed, and which degrades to chronological?
  • Can you trace one feed request through cache, merge, hydration, and ranking?

Checklist

  • Fan-out strategy is explicit and justified by follower distribution.
  • Feed entries are derived and rebuildable.
  • Cursors are stable (score, id) pairs with a total order.
  • Ranking is deterministic for a frozen page window.
  • Celebrity/hot authors are handled at read time with a bound.
  • Cache TTLs, jitter, and stampede protection exist.
  • Backfill and repair are idempotent, resumable, and rate-limited.
  • Deletes are filtered at read time and cleaned asynchronously.
  • Follow/unfollow changes have a defined history policy.
  • Hydration is batched; no N+1 on the feed path.
  • Peak read load and hot-shard behavior are tested.
  • A chronological fallback exists when ranking fails.