Lesson 241 of 296
Design: chat app and news feed
What you will learn
- Designing one-to-one and group chat
- Real-time delivery, ordering, offline users, read receipts and presence
- Designing a news feed
- Fan-out on write vs fan-out on read, and the celebrity problem
- Ranking and pagination
On this page
Part A: a chat app (like WhatsApp or Slack)
Requirements: one-to-one and group chats; real-time delivery; message history; delivered and read receipts; online presence; works for offline users (deliver later, push notification). Non-functional: low latency (under a few hundred milliseconds), messages never lost, ordered within a conversation.
Estimates (example): 50 million DAU, 40 messages per user per day = 2 billion messages a day, about 23,000 per second on average. At 200 bytes each, about 400 GB of messages a day.
High-level design:
Clients ⇄ WebSocket gateway servers ⇄ Chat service ─→ Message store (Cassandra / DynamoDB)
↑ ↓ ↓
Connection registry (Redis: Pub/sub or queue between gateways
userId → gateway server) ↓
Push notification service (offline users)Sending a message:
- Sender's app sends the message over its WebSocket (Lesson 205) with a client-generated message ID (for de-duplication on retries).
- The chat service stores the message first (durability), assigning a sequence number per conversation.
- It acknowledges to the sender ("sent", one tick).
- It looks up which gateway servers the recipients are connected to (the connection registry in Redis) and forwards the message through pub/sub.
- Online recipients receive it; their apps acknowledge ("delivered", two ticks). Offline recipients get a push notification and fetch missed messages when they reconnect.
Deep dives:
- Storage: an append-heavy, huge dataset read as "latest messages of conversation X": a wide-column or key-value store with partition key
conversation_idand sort keysequenceor time (Cassandra, ScyllaDB, DynamoDB) fits well. PostgreSQL works at smaller scale. - Ordering: clocks on different servers disagree, so do not order by server time alone; use a per-conversation sequence number (assigned by the conversation's owner shard), or time-sortable IDs plus tie-breaking.
- Sync after offline: the client sends "last sequence I have is 1042"; the server returns everything after it (cursor pagination, Lesson 222).
- Group chats: for small groups, fan out to each member's connection. For huge channels (thousands of members), members fetch from the channel's timeline rather than each receiving a copy.
- Read receipts: store per user per conversation the "last read sequence", not a flag on every message.
- Presence (online/last seen): clients send heartbeats; Redis keys with short TTLs (if no heartbeat in 60 seconds, the key expires: offline). Presence is eventually consistent and best-effort.
- End-to-end encryption: messages are encrypted on devices (Signal protocol); the server stores ciphertext it cannot read. Mention it; do not design the cryptography.
- Media: images and videos go to object storage with pre-signed uploads (Lesson 242); messages hold references.
Part B: a news feed (like Twitter/X or LinkedIn)
Requirements: users follow others; the home feed shows recent posts from people they follow (time-ordered or ranked); posting is fast; feed loads fast with infinite scroll.
Estimates (example): 100 million DAU each opening the feed 10 times a day = 1 billion feed reads a day, about 11,600 per second. 10 million new posts a day, about 116 per second. Very read-heavy.
The core question: when do you build the feed?
| Fan-out on write (push) | Fan-out on read (pull) | |
|---|---|---|
| How | When Alice posts, insert the post ID into every follower's feed list (precomputed, often in Redis) | When Bob opens his feed, fetch recent posts from everyone he follows and merge them |
| Reads | Very fast: read one precomputed list | Slow: many queries and a merge per request |
| Writes | Expensive: one post becomes N inserts | Cheap |
| Problem | Celebrities: one post by an account with 50 million followers means 50 million writes | Users who follow thousands of accounts |
The hybrid (the standard answer):
- Normal users: fan-out on write into followers' feed caches.
- Celebrities (above a follower threshold): not fanned out; their recent posts are fetched at read time and merged into the precomputed feed.
- Skip fan-out for inactive users; build their feed on demand when they return.
High-level design:
Post service ─→ Posts DB ─→ "PostCreated" event ─→ Fan-out workers ─→ Feed cache (Redis lists per user: post IDs)
↑ follower lists (Graph / followers table)
Feed service: read feed cache IDs + celebrity posts ─→ hydrate post details (cache) ─→ rank ─→ return page- Feed caches store post IDs only (small); post content, author names and counts come from a separate post cache (hydration).
- Keep only the latest few hundred IDs per user; older pages come from the database.
- Pagination: cursor-based (Lesson 222), so new posts do not shift pages.
- Ranking: chronological is simplest; ranked feeds score posts (relationship strength, engagement, recency, content type) with a model, usually in a separate ranking service.
- Media served from a CDN.
- Counters (likes, comments) updated asynchronously and cached; eventually consistent is fine (Lesson 237).
- Deletes and privacy: deleted or blocked content must be filtered at read time even if IDs remain in caches.
How to say it in an interview
"For chat I keep persistent WebSocket connections on gateway servers, with a Redis registry of which gateway each user is on and pub/sub between gateways. A message is stored first with a per-conversation sequence number and a client-generated ID for de-duplication, acknowledged, then forwarded to online recipients, with push notifications for offline ones who sync from their last sequence on reconnect. Messages go in a store partitioned by conversation. For a news feed I use a hybrid: fan-out on write of post IDs into followers' Redis feed lists for normal users, and fetch celebrities' posts at read time to avoid millions of writes per post, then hydrate, rank and paginate with cursors."
Key words
| Word | Meaning |
|---|---|
| WebSocket gateway | Servers holding persistent client connections |
| Connection registry | A map of which server each user is connected to |
| Sequence number | An increasing number ordering messages in a conversation |
| Presence | Online / last-seen status |
| Fan-out on write / read | Build feeds when posting / when reading |
| Celebrity problem | Accounts with huge follower counts breaking fan-out on write |
| Hydration | Turning a list of IDs into full objects |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.