Design a chat app (like WhatsApp Web or Slack)
Design the web client of a chat app, like WhatsApp Web, Slack or Messenger: a list of conversations, a message thread, real-time delivery, and typing and read indicators.
A typical framing: "Users have hundreds of conversations, some with years of history. Messages must arrive instantly, never get lost or duplicated, and appear in the right order. The app should keep working on a flaky mobile connection."
TL;DR
Use a persistent connection (WebSocket) for real-time events, and plain HTTP for loading history. Every message the user sends gets a client-generated id, appears immediately with a "sending" status (optimistic UI), and is matched with the server's acknowledgement, which makes retries safe and prevents duplicates. Order messages by a server-assigned sequence number per conversation, not by client clocks. When the connection drops, reconnect with exponential backoff and sync from the last sequence number you saw, so no messages are missed. Store conversations in a normalized client store, persisted to IndexedDB for instant startup and offline reading, and queue outgoing messages while offline. The message list is a reversed, virtualized list that loads older messages as you scroll up and keeps the scroll position stable.
1. Requirements
Questions worth asking:
- One-to-one only, or groups too? How big can a group be?
- Which message types: text, images, files, voice, reactions, replies, edits?
- Do we need read receipts, typing indicators and online presence?
- Is end-to-end encryption in scope? (It changes a lot, see the follow-ups.)
- Multiple devices per user, all in sync?
Functional
- Conversation list sorted by latest activity, with unread counts and a last-message preview.
- Open a conversation, read history (scrolling back years), send text and images.
- Real-time delivery, delivery and read status, typing indicators.
- Notifications when the tab is in the background.
Non-functional
- Low latency: a message appears for the recipient in well under a second.
- Reliability: no lost messages, no duplicates, correct order.
- Resilience: reconnects automatically. Works offline in a read-only way, and queues sends.
- Performance: smooth with long histories and many conversations.
2. Architecture
- Connection manager: owns the WebSocket. It authenticates, sends heartbeats, reconnects with backoff, and turns socket frames into typed events (
message.new,message.ack,receipt.read,typing). - Outbox: outgoing messages waiting for an ack. Persisted, so they survive a refresh, and retried on reconnect.
- Store: conversations, messages and users by id. UI components subscribe to slices of it.
- IndexedDB: a local copy of recent conversations and messages, so the app opens instantly and works offline.
Why WebSocket?
| Option | Direction | Notes |
|---|---|---|
| Short polling | Client asks repeatedly | Simple, but slow and wasteful |
| Long polling | Server holds the request open | Works everywhere, more overhead per message |
| SSE | Server to client only | Simple and auto-reconnects, but sends still need HTTP |
| WebSocket | Both directions | Low overhead, best fit for chat |
Chat is bidirectional and chatty (typing indicators, receipts), so WebSocket is the natural choice. Keep HTTP for history pages, which are cacheable and easy to retry.
3. Data model
type Message = {
/** Generated on the client before sending: makes retries idempotent. */
clientId: string
/** Assigned by the server on ack. */
id?: string
conversationId: string
senderId: string
body: string
/** Server-assigned, increasing per conversation. The source of truth for order. */
seq?: number
createdAt: string
status: 'pending' | 'sent' | 'delivered' | 'read' | 'failed'
}
type Conversation = {
id: string
title: string
memberIds: string[]
lastMessageId: string | null
unreadCount: number
/** The highest sequence number this client has seen, used to resync. */
lastSeq: number
}4. Interface (API)
WebSocket events (JSON frames):
{ "type": "message.send", "clientId": "c_81f", "conversationId": "conv_1", "body": "Hi!" }
{ "type": "message.ack", "clientId": "c_81f", "id": "m_9001", "seq": 4521 }
{ "type": "message.new", "message": { "id": "m_9002", "seq": 4522, "senderId": "u_2", "body": "Hey" } }
{ "type": "receipt.read", "conversationId": "conv_1", "userId": "u_2", "upToSeq": 4522 }
{ "type": "typing", "conversationId": "conv_1", "userId": "u_2" }HTTP:
GET /api/conversations?cursor=...
GET /api/conversations/:id/messages?beforeSeq=4500&limit=50 -> older history
GET /api/sync?since=<per-conversation lastSeq map> -> what I missed5. Optimizations and deep dives
Sending reliably (optimistic UI + acks)
- The user hits Enter. Create the message with a new
clientId(e.g.crypto.randomUUID()), statuspending, add it to the store and the outbox. It appears instantly with a clock icon. - Send it over the socket.
- On
message.ackwith the sameclientId, store the serveridandseq, and set statussent. - No ack within a timeout, or the socket dropped? Resend from the outbox. The server deduplicates by
clientId, so a retry never creates a second message. - After several failures, mark it
failedwith a "Tap to retry" action.
Ordering
Client clocks are wrong and messages arrive over different paths, so never sort by the client's timestamp. The server assigns a sequence number per conversation. Insert incoming messages by seq. Pending messages (no seq yet) stay at the bottom in the order they were sent. If you receive seq 4525 but last saw 4522, there's a gap: fetch the missing range over HTTP.
Reconnecting and syncing
- Detect drops with heartbeats (ping every ~25 s, reconnect if no pong) and the browser's
online/offlineevents. - Reconnect with exponential backoff and jitter (1 s, 2 s, 4 s... up to 30 s, randomized), so millions of clients don't reconnect at the same moment after an outage.
- After reconnecting, call
/syncwith yourlastSeqper conversation to get everything you missed, then flush the outbox. - Show a small "Connecting..." banner instead of failing silently.
The message list
- A reversed list: the newest message is at the bottom, and opening a chat starts scrolled to the bottom.
- Virtualize it, since conversations can have thousands of messages.
- Load older pages with an
IntersectionObserverat the top. When they are prepended, preserve the scroll position (measure the scroll height before and after, and adjust), or the view jumps. - Auto-scroll to new messages only if the user is already near the bottom. Otherwise show a "3 new messages ↓" button.
Read receipts and typing
- Send a read receipt when a message is actually visible (
IntersectionObserver) and the tab is focused. Batch them: "read up to seq X" instead of one event per message. - Throttle typing events (at most one every 2-3 s) and expire them on the receiver after a few seconds without updates.
Offline and multiple tabs
- Persist conversations, recent messages and the outbox in IndexedDB. On startup, render from it instantly, then sync.
- Several tabs open would mean several sockets. Use a SharedWorker (or a
BroadcastChannelwith one elected leader tab) to keep one connection and share events with all tabs.
Notifications
Use the Notifications API when the tab is hidden (document.visibilityState), with an unread count in the title and favicon. For notifications when the app is closed, you need a service worker and Web Push.
Media
Upload images directly to object storage with a pre-signed URL (with progress and cancel), then send a message that references the uploaded file. Show a local preview (URL.createObjectURL) right away, and generate thumbnails so the list doesn't download full-size images.
Common follow-ups
- "How does end-to-end encryption change the design?" The server can no longer read messages, so search, previews and link unfurling move to the client. Keys are managed per device (the Signal protocol), and adding a new device needs a key exchange. History sync becomes much harder.
- "How do you search message history?" Server-side search for full history. For E2E apps, a local index in IndexedDB of the messages on the device.
- "What happens in a 10,000-member group?" Don't send typing indicators or per-user read receipts to everyone. Use counts ("read by 1,203"), paginate the member list, and rate-limit events.
What interviewers look for
- The right transport choice and why, with HTTP still used for history.
- Client ids, acks and dedup: optimistic sending that's safe to retry.
- Server-assigned ordering and gap detection, not client timestamps.
- A real reconnect and sync strategy (heartbeats, backoff with jitter, sync from the last sequence number).
- A reversed virtualized list with stable scroll position, plus offline storage.