Design a Real-Time Social Activity Feed
System DesignModel answerLast updated
Design a scalable system that delivers a personalized, real-time activity feed to millions of users with low latency and high throughput.
Scenario
You are a senior engineer at a mid-sized social platform (think: a professional networking app). Users follow other users and organizations. When someone posts an update, their followers should see it in their feed within a few seconds.
The product team has the following requirements:
- A user's feed shows the 200 most recent activities from the accounts they follow.
- New posts should appear in a follower's feed within 3 seconds of being published.
- Users can follow up to 5,000 accounts; some celebrities have 10 million+ followers.
- The platform has 50 million daily active users (DAU), with peak traffic around 3x the average.
- Feed reads are 10x more frequent than feed writes.
- Feeds do not need to be perfectly ordered to the millisecond; eventual consistency within a few seconds is acceptable.
What is expected
Walk the interviewer through:
- Requirements & scale estimation — clarify ambiguities and back-of-envelope numbers.
- API design — the key endpoints a client calls.
- Data model — what you store and where.
- Core architecture — how a post flows from creation to a follower's screen.
- Deep dives — handle celebrity/high-fan-out accounts, feed ranking, and storage costs.
- Trade-offs — fan-out-on-write vs. fan-out-on-read vs. a hybrid.
Hints
Hint 1
Start with the read/write ratio to justify your caching strategy before jumping into components.
Hint 2
Think about what happens when a celebrity with 10M followers posts — a naive fan-out-on-write will create a write storm. How do you handle it?
Hint 3
Consider what the feed cache actually stores: full post objects vs. just post IDs. Each choice has real memory and consistency implications.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scale Estimation
Clarifications worth making explicit:
- Feeds are personalized but not heavily ranked initially (chronological is fine, ranking is a later deep dive).
- Deleted posts should disappear from feeds within a reasonable window (~30 s is acceptable).
- We store feeds for active users only; inactive users can reconstruct on demand.
Back-of-envelope:
- 50M DAU; assume each user opens the feed 5x/day → 250M feed reads/day ≈ 3,000 reads/sec (peak ~9,000/sec).
- Assume 5% of DAU post once/day → 2.5M writes/day ≈ 30 writes/sec (peak ~90/sec).
- Average follower count: 500. Fan-out events: 30 writes/sec × 500 = 15,000 feed-update events/sec on average; celebrity bursts can spike to 10M events in seconds.
- Feed cache entry: 200 post IDs × 8 bytes = 1.6 KB per user. For 50M active users: ~80 GB — fits in a Redis cluster.
2. API Design
GET /v1/feed?cursor=<timestamp_or_id>&limit=20
→ { posts: [...], next_cursor: "..." }
POST /v1/posts
Body: { content, media_ids[], visibility }
→ { post_id, created_at }
DELETE /v1/posts/{post_id}
- Cursor-based pagination (not offset) to handle real-time inserts gracefully.
- Feed endpoint is the hot path; it must be served from cache.
3. Data Model
Posts table (PostgreSQL or Cassandra):
post_id UUID PK
author_id UUID
content TEXT
media_ids UUID[]
created_at TIMESTAMP
is_deleted BOOL
Feed cache (Redis Sorted Set per user):
Key: feed:{user_id}
Value: post_id (member)
Score: unix_timestamp_ms (for ordering)
TTL: 7 days (evict inactive users)
Storing only post_id in the cache (not full post content) keeps memory low and avoids stale content — posts are hydrated from a separate post cache or DB on read.
Follow graph (graph DB or adjacency table):
follower_id UUID
followee_id UUID
created_at TIMESTAMP
PK: (follower_id, followee_id)
4. Core Architecture
Write path (post created):
- Client → Post Service → writes to Posts DB, publishes event to message queue (Kafka topic
post.created). - Fan-out Workers (consumer group) read from Kafka. For each post event, they fetch the author's follower list from the Follow Service and push the
post_idinto each follower's Redis sorted set (ZADD feed:{follower_id} <ts> <post_id>). - A push notification or WebSocket signal is sent to online followers via a Notification Service.
Read path (user opens feed):
- Client → Feed Service →
ZREVRANGE feed:{user_id} 0 19from Redis (top 20 by timestamp). - Post IDs are batched and resolved against a Post Cache (Redis or Memcached). Cache misses fall back to Posts DB.
- Assembled feed returned to client in <50 ms p99.
5. Deep Dives
Celebrity / High Fan-out Problem
A naive fan-out-on-write for a 10M-follower account creates 10M Redis writes in seconds — a write storm that can lag behind by minutes and delay feeds for all users.
Hybrid fan-out strategy:
- Define a celebrity threshold (e.g., >100K followers).
- For regular users: fan-out-on-write (push
post_idinto follower feeds immediately). - For celebrities: fan-out-on-read. The celebrity's recent posts are stored in a celebrity feed list (
recent:{celebrity_id}). When a follower reads their feed, the Feed Service merges:- Their precomputed personal feed (from Redis)
- The latest N posts from each celebrity they follow (fetched live and merged in-memory)
- This merge adds ~5–10 ms latency but avoids the write storm entirely.
Feed Ranking
Initially serve chronological order. To add ranking:
- Attach an engagement score (likes, comments, recency decay) at fan-out time or at read time.
- Use a lightweight ML model offline to compute scores; store a
scoreas the sorted set's score instead of raw timestamp. - Avoid recomputing scores on every read — recompute on new engagement events and update the sorted set.
Storage Cost & TTL
- Cap each feed sorted set at 200 entries;
ZREMRANGEBYRANKtrims older entries on every write. - Apply a 7-day TTL; cold-start reconstruction queries the Posts DB for recent posts from followed accounts (acceptable for inactive users, rare case).
6. Trade-offs
| Approach | Reads | Writes | Consistency | Best for |
|---|---|---|---|---|
| Fan-out-on-write | O(1) — read from cache | O(followers) | Near-real-time | Users with small follower counts |
| Fan-out-on-read | O(followees) merge | O(1) | Real-time | Celebrities, rarely-active users |
| Hybrid | O(1) + small merge | Moderate | Near-real-time | Mixed workloads (recommended) |
Other trade-offs to mention:
- Post IDs vs. full objects in cache: IDs save memory and keep content fresh; objects avoid extra DB round-trips. IDs win at this scale.
- Kafka vs. direct DB writes: Kafka decouples the write path, buffers bursts, and allows fan-out workers to scale independently. Adds ~200 ms latency but prevents DB overload.
- WebSocket vs. polling: WebSockets give true real-time delivery but add connection state complexity; long-polling is simpler and often good enough.
Common Mistakes to Avoid
- Skipping the celebrity problem — interviewers will probe it directly.
- Storing full post payloads in feed caches — wastes memory and causes stale-content bugs on edits/deletes.
- Using a single fan-out worker — it becomes a bottleneck; always partition Kafka by
author_idso workers scale horizontally. - Forgetting TTLs — unbounded Redis keys will exhaust memory silently.