Designing a chat app
The final design: a chat application like WhatsApp, Slack or Messenger. It combines everything in this track (persistent connections, routing messages between servers, ordering, storage at enormous scale, offline delivery, presence, fan-out to groups) with strict latency expectations: messages should arrive in well under a second.
1. Requirements
Functional
- One-to-one and group chats (groups up to, say, 1,000 members).
- Messages are delivered in real time when the recipient is online, and stored for when they're offline or switch devices.
- Delivery status: sent ✓, delivered ✓✓, read.
- Online/offline presence and "last seen".
- Multiple devices per user. (Attachments, search and end-to-end encryption can be follow-ups.)
Non-functional
- Low latency: under ~500 ms end to end on a good connection.
- No lost messages, and messages in a conversation appear in the same order for everyone.
- High availability; huge scale.
2. Estimates
Hundreds of thousands of messages a second, petabytes of history and 150 million open connections. Every part needs horizontal scaling.
3. Real-time connections
HTTP request/response doesn't suit chat: the server must push messages the moment they arrive. Options:
| Technique | Fit for chat |
|---|---|
| Polling (ask every few seconds) | Wasteful and slow |
| Long polling | Works; inefficient at scale |
| Server-Sent Events | One-way (server → client) only |
| WebSockets | ✔ A persistent two-way connection, the standard choice |
Mobile apps also use push notifications (APNs, FCM) to wake the app when it's in the background.
4. High-level design
clients ══WebSocket══▶ gateway servers (hold connections, stateless otherwise)
│ ▲
send message │ │ deliver
▼ │
chat service ──▶ message store (sharded by conversation_id)
│
├──▶ session registry: user → which gateway(s) they're connected to (Redis)
├──▶ pub/sub or message bus between gateways
└──▶ push notification service (offline users)Sending a message from Asha to Rahul:
- Asha's app sends the message over its WebSocket to gateway 3.
- The chat service assigns it a sequence number in the conversation and stores it (durably) before acknowledging: "sent ✓".
- It looks up Rahul in the session registry: connected to gateway 7.
- It publishes the message to gateway 7 (via pub/sub), which pushes it down Rahul's WebSocket. Rahul's app acknowledges: "delivered ✓✓".
- If Rahul is offline, the message waits in storage, and a push notification is sent. When he reconnects, his app asks for everything after the last sequence number it has.
5. A working miniature
6. Deep dives
Message ordering
Clocks on phones and servers disagree, so timestamps can't order messages reliably. Instead, assign each message a per-conversation sequence number at the server (a counter per conversation, kept on the conversation's shard). Clients sort by it and detect gaps (missing 41 between 40 and 42 → fetch it). Ordering is only needed within a conversation, which keeps it scalable: no global counter.
Delivery guarantees
Messages are delivered at least once: if an acknowledgement is lost, the message is resent. Each message carries a client-generated ID, so the server and recipients can drop duplicates (idempotency, as in the queues lesson).
Storage
The access pattern is "the latest N messages of a conversation, then older pages": partition by conversation_id and cluster by sequence number. Wide-column stores (Cassandra, ScyllaDB, Bigtable) excel at this huge, append-heavy, time-ordered workload, which is why Discord moved its messages there. Recent messages also live in a cache for instant loading.
Group chats and fan-out
A message to a 1,000-member group must reach up to 1,000 connections. Fan-out on write: the chat service looks up all members and publishes to each member's gateway. Very large channels (broadcast channels with millions of followers) instead use fan-out on read: followers fetch from the channel's feed when they open it.
Presence
Presence changes constantly and is "eventually correct" by nature, so it's kept in memory (Redis) with heartbeats: each connected client pings every ~30 seconds; a user with no heartbeat for a minute is marked offline. Presence updates are only sent to people who are currently viewing that user (open conversations, contact lists), not broadcast to everyone.
Multiple devices
The registry maps a user to all their connected devices. Each device tracks its own last-synced sequence number per conversation, so a laptop opened after a week catches up independently of the phone.
End-to-end encryption
With E2EE (the Signal protocol, used by WhatsApp and Signal), devices exchange keys and encrypt messages so the servers only store and relay ciphertext. The architecture is the same; the servers just can't read the content, which also means server-side search isn't possible.
7. Bottlenecks and failure handling
- Gateway failure drops its connections; clients reconnect (with jittered backoff!) to another gateway and sync from their last sequence number. Nothing is lost because messages were stored before being delivered.
- Hot conversations (a huge, busy group) concentrate load on one shard: split very large channels, and cache aggressively.
- Registry (user → gateway) must be fast and replicated; entries expire if a gateway dies.
- Back-pressure: if a slow client can't keep up, buffer briefly, then drop the connection and let it sync.
🎓 System Design track complete!
You've learned how to approach design problems, how the internet works, estimation, scaling, load balancing, caching, databases and replication, sharding and consistent hashing, queues and streams, consistency and distributed transactions, reliability and observability, and you've designed a URL shortener and a chat app.
Capstone: design it yourself
Pick one, and work through all seven steps (requirements, estimates, API, data model, high-level design, deep dives, trade-offs). Draw the diagram, and write a one-page design document:
- A news feed (like Instagram's): fan-out on write vs on read, the celebrity problem, ranking, caching feeds.
- A ride-hailing service (like Uber): location updates every few seconds, finding nearby drivers (geohashing), matching, surge pricing.
- A video streaming platform (like YouTube): uploads, transcoding pipelines, adaptive bitrate streaming, CDNs, view counts.
- A distributed rate limiter used by every service in a company.
- A ticket booking system for concerts: thousands of people competing for the same seats, holds that expire, no double booking.
1.Why do chat apps use WebSockets instead of plain HTTP requests?
2.How should messages in a conversation be ordered?
3.Why store a message before delivering it to online recipients?