Design the web client of a chat application like Facebook Messenger or WhatsApp Web.
Users see a list of their conversations (one-to-one and groups up to ~250 people), open one, read history, and send messages that arrive in near real time for the other participants.
Requirements given by the interviewer:
Design the client architecture, data model, the protocol with the server, and the techniques that keep it fast, correct and resilient. End-to-end encryption can be discussed as a stretch topic.
Chat is a distributed systems problem that happens to have a UI. The hard parts are ordering, delivery guarantees, reconnection, multi-tab consistency and long histories, not the message bubble. Establish that early.
| Concern | Target |
|---|---|
| Message latency | p95 < 500 ms sender → recipient when both online |
| Send feedback | the bubble appears in < 50 ms (optimistic) |
| Delivery guarantee | at-least-once over the wire, exactly-once in the UI (dedupe) |
| Ordering | consistent per conversation for all participants |
| Reconnect | resume within 2 s after network returns, without losing or duplicating messages |
| Scroll | smooth through 10k+ loaded messages; bounded memory |
| Cold start | conversation list visible in < 1.5 s on repeat visits (from local cache) |
| Multi-tab | read state and new messages consistent across tabs |
Assumptions: groups ≤ 250, no E2EE in v1 (discussed at the end), last 30 days cached offline, edit/delete supported as events, WebSocket gateway available.
The UI never talks to the network directly. It reads from a local store (in-memory + IndexedDB) and writes commands into an outbox. A sync engine reconciles the local store with the server over a WebSocket. This makes the app instant (reads are local), offline-capable (writes queue), and correct across reconnections (sync is resumable from a cursor). Messenger's "LightSpeed" rewrite moved logic into a local database for similar reasons.
<ChatApp>
<ConnectionBanner /> // "Connecting…", "Offline – messages will send later"
<Sidebar>
<ConversationSearch />
<ConversationList> // virtualized
<ConversationRow /> // avatar, name, preview, time, unread badge, presence
<ConversationPane>
<ConversationHeader /> // name, presence, call buttons
<MessageList> // reverse-scrolling, virtualized
<DayDivider />
<MessageGroup> // consecutive messages by same sender
<MessageBubble /> // text, image, reply preview, reactions, status
<TypingIndicator />
<Composer /> // textarea, attachments, emoji, send
clientMessageIds.BroadcastChannel. Alternative: a SharedWorker holds the socket (not available on all mobile
browsers, so keep the leader election fallback).document.title
badge for unread count.| Data | Owner | Client location |
|---|---|---|
| Conversations, participants | server | IndexedDB + memory |
| Messages | server (authoritative order) | IndexedDB (recent N per conversation) + memory window |
| Pending outgoing messages | client until acked | outbox (IndexedDB) |
| Read/delivered watermarks | server | memory + IndexedDB |
| Typing, presence | server, ephemeral | memory only, TTL-based |
| Draft text per conversation | client | IndexedDB / localStorage |
| Scroll position, open conversation | client | memory / URL (/t/:conversationId) |
type ID = string;
interface Conversation {
id: ID;
type: 'direct' | 'group';
title?: string;
participantIds: ID[];
lastMessageId: ID | null;
lastActivityAt: string;
unreadCount: number; // derived on server, adjusted locally
myReadSeq: number; // highest seq I have read
muted: boolean;
}
interface Message {
id: ID | null; // server id, null until acked
clientMessageId: ID; // uuid generated on the client, stable forever
conversationId: ID;
senderId: ID;
seq: number | null; // server-assigned, monotonic per conversation
createdAt: string; // server time once acked; local time while pending
kind: 'text' | 'image' | 'system';
text?: string;
attachments?: { uploadId: ID; url?: string; width: number; height: number; localBlobUrl?: string }[];
replyToId?: ID;
reactions: Record<string, ID[]>; // emoji -> userIds
editedAt?: string;
deleted?: boolean;
status: 'pending' | 'sent' | 'failed'; // client-only for own messages
}
interface ParticipantReceipt {
userId: ID;
deliveredSeq: number; // watermark, not per-message flags
readSeq: number;
}
interface ChatStore {
conversations: Record<ID, Conversation>;
conversationOrder: ID[]; // sorted by lastActivityAt
messagesByConversation: Record<ID, {
byKey: Record<ID, Message>; // keyed by clientMessageId
orderedKeys: ID[]; // by seq, pending at the end
oldestLoadedSeq: number | null;
hasMoreBefore: boolean;
}>;
receipts: Record<ID, Record<ID, ParticipantReceipt>>; // conversationId -> userId -> receipt
typing: Record<ID, Record<ID, number>>; // conversationId -> userId -> expiresAt
syncCursor: string | null; // global per-user sync position
}
Key decisions:
message.seq <= receipt.readSeq.seq defines order, not client timestamps (clocks drift). Pending messages render at the
bottom in local order until their seq arrives.clientMessageId is the stable key for React and for dedupe, so the bubble does not remount (and lose focus or
animation state) when the server id arrives.Last-Event-ID. A good fallback.I would use a WebSocket with an SSE/long-poll fallback, behind one transport interface.
// Client -> server after connect (auth via cookie or a short-lived token in the first frame, never in the URL)
{ "type": "hello", "cursor": "c_88310", "clientVersion": "2025.03.1" }
// Server -> client: events since the cursor, paged
{ "type": "sync", "events": [
{ "type": "message.new", "conversationId": "cv_1", "message": { "id": "m_901", "clientMessageId": "a1b2", "seq": 1043, "senderId": "u_2", "text": "hey", "createdAt": "2025-03-02T10:00:00Z" } },
{ "type": "receipt", "conversationId": "cv_1", "userId": "u_2", "readSeq": 1041 }
],
"nextCursor": "c_88312", "hasMore": false }
// Client -> server: send
{ "type": "message.send", "conversationId": "cv_1", "clientMessageId": "5f0c-...", "text": "On my way" }
// Server -> client: ack (also broadcast as message.new to other devices, carrying the same clientMessageId)
{ "type": "ack", "clientMessageId": "5f0c-...", "id": "m_902", "seq": 1044, "createdAt": "2025-03-02T10:00:03Z" }
// Ephemeral
{ "type": "typing", "conversationId": "cv_1", "userId": "u_2", "state": "start" }
{ "type": "presence", "userId": "u_2", "status": "online" }
// Client -> server: read watermark (throttled)
{ "type": "read", "conversationId": "cv_1", "readSeq": 1044 }
Every event that changes durable state carries a position in the user's event stream. After a disconnect, the
client sends its last cursor and receives exactly what it missed. If the cursor is too old (e.g. offline for a
month), the server responds with resync_required and the client refetches conversations from scratch.
GET /api/conversations?cursor=...&limit=30
GET /api/conversations/cv_1/messages?beforeSeq=1000&limit=50
POST /api/uploads -> { "uploadId": "up_9", "putUrl": "https://storage.example.com/...signed" }
History pagination uses beforeSeq (a keyset cursor): new messages keep arriving at the end, so an offset
would shift on every incoming message. Keyset pagination is also an efficient index lookup on the server.
interface MessageListProps {
conversationId: ID;
keys: ID[]; // clientMessageIds in display order
hasMoreBefore: boolean;
onLoadOlder: () => Promise<void>;
onVisibleRangeChange: (lastVisibleSeq: number) => void; // drives read receipts
}
interface ComposerProps {
conversationId: ID;
initialDraft: string;
onSend: (input: { text: string; files: File[]; replyToId?: ID }) => void;
onTyping: () => void; // throttled inside the composer
disabled?: boolean;
}
clientMessageId (crypto.randomUUID()), insert the message with status: 'pending', append to the
outbox in IndexedDB (so a crash or reload doesn't lose it).ack, set id, seq, createdAt, status: 'sent', remove from outbox, and move the message into its seq
position (usually unchanged).clientMessageId; the server dedupes. After N attempts,
mark failed with "Tap to retry".Images: show the local URL.createObjectURL(file) preview immediately, resize/compress client-side (canvas or
createImageBitmap in a worker) to cap size, upload via pre-signed URL with progress, then send the message
referencing uploadId. Revoke the object URL afterwards.
The same message can arrive via the live socket, the sync replay and the sender's own ack. Merge by
clientMessageId and treat updates as idempotent upserts. Ignore events whose entity version is older than what is
stored (edits can race).
online and visibilitychange to visible.hello with cursor → apply delta → flush outbox in order.scrollTop by the height added (or use
overflow-anchor / a virtualizer that supports prepending). Variable heights (images, long text) need measured
sizes cached by clientMessageId.IntersectionObserver on the last bubbles, only while the
document is visible and focused. Throttle read events (e.g. at most every 1 s) and send only the max seq.start at most every 3 s while the user types, stop on send/blur. Receivers expire typing state
after ~5 s without a refresh, so a crashed client never shows "typing…" forever.navigator.locks.request('chat-socket', ...) to elect a leader that owns the socket; other tabs receive events
via BroadcastChannel and send commands to the leader. When the leader closes, the lock is released and another
tab takes over.tag to
collapse duplicates).postMessage with transferable data.role="log" with aria-live="polite" so screen readers announce new incoming messages
(but not every historical message on load — set the live region only after initial render).Enter sends, Shift+Enter newline, documented; IME composition (isComposing) must not send on
Enter for CJK input.Alt+↑/↓), focus moves to the composer on open, and focus is not
stolen when new messages arrive.dir="auto" so mixed-language conversations render correctly; the bubble alignment uses logical
properties so "my messages" flip sides in RTL.Intl.DateTimeFormat in the user's time zone ("Today", "Yesterday" via
Intl.RelativeTimeFormat).Intl.Segmenter) so a family emoji isn't cut in half.dangerouslySetInnerHTML.Origin on the
server to prevent cross-site WebSocket hijacking.connect-src limited to the gateway; images served from a separate sandboxed domain;
link previews generated server-side to avoid leaking the user's IP.With E2EE (Signal protocol, as in WhatsApp and Messenger), the server only stores ciphertext. The client must
manage keys per device (stored in IndexedDB, non-extractable CryptoKey via WebCrypto where possible), decrypt
every message, generate previews and search indexes locally, and handle device linking/history sync. Search and
notifications become client problems: push payloads carry no plaintext, and the service worker decrypts.
clientMessageId as a correlation id across client logs and server.context.setOffline(true).seq.resync_required), not as a socket
listener. This is what makes multi-device, multi-tab and offline fall out naturally.How do you guarantee order if two people send at the same time? The server assigns seq per conversation;
both clients reorder their optimistic messages once acks/events arrive. Locally, a user's own messages stay in send
order because the outbox is sequential per conversation.
What if the ack is lost but the server stored the message? The client retries with the same
clientMessageId; the server returns the existing message instead of creating a duplicate.
How do you show unread counts correctly across devices? The server owns readSeq; unread = messages with seq
greater than readSeq not sent by me. Locally we update optimistically and reconcile on the next event.
How would you implement search? Server-side search API for full history; local search over IndexedDB for recent messages to get instant results. With E2EE, only local search (build an index in a worker).
Why not store everything in IndexedDB forever? Storage quotas and eviction (browsers may clear storage under
pressure unless navigator.storage.persist() is granted). Cache a bounded window and treat the server as the source
of truth.
How do you handle 10,000 unread messages in a group? Don't load them all: jump to the first unread with a "Jump to latest" button, load windows around the anchor, and show the count from the server.
Spotted a mistake or a rights concern? Report an issue