Design a Personalized Activity Feed for a High-Scale Social Platform
System DesignModel answerLast updated
Design the backend that publishes user posts and serves each follower a ranked, paginated feed, handling celebrity accounts, deletions, and privacy at scale.
Personalized Activity Feed
A social platform wants to revamp the core feature its users interact with most: the home feed. When someone opens the app, they expect to see a freshly ranked, infinitely scrollable stream of posts from every account they follow. When they publish something new, their followers should see it promptly.
Your task is to design the backend that powers both sides of this: ingesting new posts and assembling each user's feed on request.
You do not need to design media storage or CDN delivery — treat those as existing services. Focus on post metadata, feed assembly, and ranking.
What to address
- Overall architecture and data flow from post creation to feed retrieval
- How you distribute a new post to all relevant followers (fan-out strategy)
- How ranking works within a latency budget
- Pagination that stays coherent as new posts arrive during a scroll session
- Correctness: what happens when a post is deleted, edited, or restricted after it has already been fanned out
- How the system stays healthy at peak load, and how it degrades gracefully if a component falls behind
Constraints and clarifications
- Media assets (images, video) are out of scope; model a post as an ID, author ID, text, timestamp, and audience setting.
- Exact scale, freshness SLAs, and ranking signals are intentionally left open — state your assumptions or ask clarifying questions before designing.
Clarifying questions worth raising
- How many daily active users are there, and what does the follow-graph look like — typical follows per user and the largest follower count the system must support?
- Is the feed ranked by relevance, or strictly chronological? If ranked, which signals are available (recency, engagement, relationship strength, etc.)?
- What is the acceptable delay between a post being published and appearing in a follower's feed?
- Are algorithmically recommended posts (from accounts a user does not follow) or ads in scope?
- What consistency guarantees are required for deletes and audience-restriction changes — eventual is usually fine, but what is the upper bound?
Hints
Hint 1
Start by sizing the fan-out problem: if a user has 50 million followers and posts once, naively writing to 50 million feed rows synchronously will blow your latency and throughput budget. That asymmetry is the core tension the design has to resolve.
Hint 2
Think of feed assembly as two separate stages: candidate generation (which posts are even eligible for this user?) and ranking (in what order should they appear?). Separating them lets you tune each independently and apply ranking only to a manageable shortlist.
Hint 3
A cursor you hand back to the client should encode a stable position in the feed snapshot, not a raw offset. Consider what happens when 20 new posts arrive while a user is mid-scroll — you want to serve consistent pages without repeating or skipping posts.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Before sketching the architecture, name the numbers you are designing for:
- 500 M daily active users; each follows ~300 accounts on average.
- Largest celebrity account: ~50 M followers.
- Freshness target: a new post should reach 99% of followers' feeds within 30 seconds.
- Feed is ranked (recency + engagement signals), not purely chronological.
- Deletions and privacy changes must be reflected within a few minutes.
- Ads and recommendations from non-followed accounts are out of scope for this pass.
High-Level Data Flow
Two paths to design:
Write path — user publishes a post → Post Service validates and persists the post to a Posts store (sharded by author ID) → emits a PostCreated event to a message queue → Fan-out Workers consume the event and propagate it to followers.
Read path — user opens the feed → Feed Service retrieves a pre-assembled candidate list from Feed Store → passes candidates to Ranking Service → returns a ranked, paginated response.
Fan-out Strategy
This is the crux of the design. Three options:
Fan-out on write (push model): When a post is created, write a reference to it into every follower's feed row immediately. Feed reads are cheap (one key lookup). The problem: a celebrity with 50 M followers turns one post into 50 M writes, which is expensive and slow.
Fan-out on read (pull model): Store nothing pre-computed. At read time, fetch the list of accounts a user follows, query recent posts from each, merge, and rank. Read latency is terrible at scale — merging posts from 300 followed accounts in real time is a multi-hundred-millisecond operation even with aggressive caching.
Hybrid (recommended): Use push for ordinary accounts (follower count below a threshold, say 100 K). Use pull for high-follower accounts ("celebrities"). The feed assembly step merges the pre-built push feed with a real-time pull of celebrity posts at read time. This bounds both write amplification and read latency.
The Feed Store (e.g., Redis sorted sets, scored by timestamp or pre-computed rank score) holds per-user lists of post IDs, capped at some depth — 1,000 posts is a reasonable ceiling since users rarely paginate that far.
Ranking
Ranking runs on a candidate set, not the full post corpus. A reasonable pipeline:
- Retrieve candidates — the ~200–500 most recent eligible post IDs from the user's feed store.
- Hydrate — fetch post metadata and author features from cache (write-through cache over the Posts store).
- Score — a lightweight model or rule set combining recency, predicted engagement (CTR, like probability), and relationship strength. This should complete in under 20 ms; batch the scoring to avoid per-post round trips.
- Return top N — typically 20–50 posts per page.
Keep the ranking model simple enough to run inline in the Feed Service, or call a low-latency scoring service co-located in the same region.
Pagination
Do not use numeric offsets. Instead:
- Assign a cursor that encodes the rank score and post ID of the last item returned.
- On the next page request, filter candidates to those scoring below the cursor.
- This keeps the session stable even if 50 new posts arrive while the user is scrolling — those posts surface at the top of a fresh load, not mid-scroll.
Correctness: Deletes, Edits, and Privacy Changes
This is an area candidates often skip but interviewers probe.
- Deletes: The post is tombstoned in the Posts store immediately. At read time, the Feed Service filters out any post IDs that are tombstoned before returning the page. Fan-out workers also run an async sweep to remove deleted post IDs from feed rows, but this is best-effort — the read-time filter is the correctness guarantee.
- Edits: The post is updated in place in the Posts store. Because the Feed Service hydrates metadata at read time, all users automatically see the latest version.
- Privacy changes (e.g., post switched from public to followers-only mid-distribution): The Posts store records the current audience. The Feed Service checks audience eligibility at read time. Again, the read path is the correctness gate; background cleanup is a performance optimization.
- Unfollows: Remove the unfollowed account from the user's follow list. Existing post IDs from that account in the feed store will pass through a staleness filter at read time. A background job can prune them asynchronously.
Caching and Hot Keys
- Post metadata lives in a write-through cache (Redis or Memcached) keyed by post ID. TTL of a few hours covers the window when posts are most actively fetched.
- Celebrity post IDs pulled at read time can be cached per-celebrity per-time-window (e.g., "latest 50 posts from account X, refreshed every 5 s") to prevent thundering-herd reads during a viral moment.
- The follow graph (who does user X follow?) is cached per user with a short TTL. Updates (follow/unfollow) invalidate the entry.
Failure Handling and Degradation
- If the Fan-out queue falls behind, users see slightly stale feeds — acceptable under the 30-second SLA for most cases.
- If the Ranking Service is unavailable, fall back to recency ordering of the cached candidates rather than returning an error.
- Monitor queue lag, feed store miss rate, and p99 feed-load latency as primary health signals.
- Shard the Feed Store by user ID; shard the Posts store by author ID. Consistent hashing limits resharding disruption.
Common Mistakes to Avoid
- Designing only the push path and ignoring the celebrity problem entirely.
- Forgetting that correctness for deletes and privacy changes must be enforced at read time, not just at write time.
- Using offset-based pagination, which produces duplicate or skipped posts when new content arrives.
- Scoring every post in the Posts store at read time instead of working from a bounded candidate list.