What you'll learn: By the end of this case study you will be able to design the client side of a web messenger: separate a message's local key from its server position, show a sent message at once and reconcile it with the ack and the echo, hold back messages that arrive after a gap and fetch history, express receipts as watermarks, decide when a message counts as read and what the badge shows, and keep several tabs and a flaky connection from breaking any of it.
Think of a mailroom with a numbered pigeonhole wall. You hand a clerk a note; the clerk files it in the next free hole and shouts "filed as number 41". Meanwhile the clerk also shouts every new note to everyone in the room, including you. If you were shouting "mine!" at every note you hear, you would paste your own note onto the wall twice. A chat client is that room: local notes that have no number yet, a wall that fills in order, and a loud clerk who tells you the same thing twice.
This is an educational reference design, not the verified internal architecture of WhatsApp or of any other messenger. The title names the shape of the product (a web client for a phone-first messenger); nothing here is claimed about how any company builds it. Every number is illustrative, and the lab at the end is a model with no network.
The method (requirements, estimates, layers, deep dives, failure modes, a decision record) follows the case-study method lesson, which is planned and not yet published. The transport and presence layers are treated in Reconnection and Message Ordering and Presence and Pub/Sub; this lesson is about everything that sits between them and the screen.
The core idea
- A message has two identities. A client-generated key exists from the moment the user presses Send. A server-assigned sequence number exists only after the server has accepted it. The key lets you match the ack and the echo to the message you already show; the sequence number gives it its place.
- The timeline is a function of a few facts. Confirmed messages by sequence number, plus my unconfirmed ones, plus two receipt watermarks and one "last read" number. Delivery ticks, unread counts, dividers and the badge are all derived, never stored per message.
- Reading is something the user does, not something that happens on arrival. A message is read when the page is visible, the conversation is open and the list is scrolled to its end. Everything else is "received".
Three illustrations run through the lesson: a minimal example (one message sent and confirmed), a realistic example (a team chat with three open conversations and a flaky connection) and a failure example (a gap in the numbers while the user watches).
Requirements and scope
Functional. A list of conversations ordered by recent activity, each with an unread count. An open conversation with a scrollable history that loads older messages on demand. Sending text with immediate feedback and a visible state: sending, sent, delivered, read, failed (with a retry). Typing and online indicators. A badge with the total unread count. Notifications while the tab is in the background.
Non-functional. The screen must feel instant: a sent message appears before any network answer. It must be correct after a dropped connection: nothing lost, nothing shown twice, nothing out of order. It must stay usable with thousands of messages in one conversation and with several tabs open. It must be keyboard- and screen-reader-usable.
Out of scope here. End-to-end encryption, media upload and playback, voice and video calls, group administration, search over message history and the server side of delivery (see the back-end chat case for that). Each of these changes the client, and a real design would add them in that order of cost; this lesson keeps to text.
Illustrative sizing
The numbers below are assumptions for reasoning, not measurements.
| Quantity | Assumed value | Why it matters |
|---|---|---|
| Conversations in the list | 300 | The list needs a cheap unread count per row |
| Messages kept in memory per open conversation | 200 | Older pages are fetched on scroll, not preloaded |
| Page size for history | 50 | One request fills about one screen of scrolling |
| Messages in a very long conversation | 20,000 | Rendering them all is not an option; see windowing |
| Open tabs of the same account | 3 | Each needs the same state without three sockets |
With these assumptions, the state that must be kept hot is small (hundreds of rows, not millions). The expensive parts are rendering a long list and keeping tabs consistent, not storing messages.
The architecture: a pure core between the socket and the screen
Figure 1. The layers of a web chat client
How to read this: the middle box is the only place with rules. The UI sends it events (a key press, a visibility change, an incoming frame) and draws what it returns. Everything that touches the world, such as sending a frame or fetching a page, leaves the core as an effect that another layer performs.
The reason for this shape is testing. A reducer that takes an event and returns the next state plus a list of effects can be driven in a unit test with no socket, no timers and no DOM, including every ugly ordering of events. The transport layer (the reconnecting socket of the earlier lesson) handles one connection's problems. The core handles the conversation's problems: which message is which, what is missing, what has been seen.
The data model
Each conversation holds four things.
| Field | Meaning | Rule |
|---|---|---|
confirmed |
Messages with a server sequence number | Contiguous from 1, ascending; a message is appended only when its number is exactly the last plus one |
pending |
My messages the server has not confirmed | Shown after the confirmed ones, in the order I wrote them |
held |
Messages that arrived ahead of a gap | Released in order once the gap is filled |
| Watermarks | deliveredUpTo, readUpTo, lastReadSeq |
Only ever move forward |
A message's status on screen is derived: not mine means "received"; mine and unconfirmed is "sending" or "failed"; mine and confirmed is "sent", upgraded to "delivered" or "read" when a watermark has passed its number.
Figure 2. The life of one of my messages
How to read this: only the first four states are local. After "Sent" a message never changes by itself; the other side's watermarks move it. There is no arrow from Failed back to nothing: a failed message stays visible until the user retries.
The key is generated on the client. In a browser crypto.randomUUID() returns a version 4 UUID from a cryptographically secure generator, and MDN lists it as available only in secure contexts; that suits a key that must be unique across devices without asking a server. The same key is sent again on every retry, which makes it an idempotency key in the sense of the back-end lesson Idempotency Keys and Safe Retries: a server that remembers keys can answer a duplicate with the original result. HTTP semantics say why this matters: a client should not automatically retry a request with a non-idempotent method unless it knows the request is idempotent or that the first attempt was never applied (RFC 9110, section 9.2.2), and a key is how a server can make a send safe to repeat.
Sending: optimistic, then reconciled
When the user presses Send, the core does three things in one step: it appends the message to pending with its key, emits a send effect, and the screen shows the message at once with the label "Sending". No network answer is awaited. The general technique and its rollback rules are in Optimistic Updates and Rollback; chat has one special feature, which is that the confirmation arrives twice.
The server answers the sender with an ack ("your message is number 41") and also broadcasts the message to every subscriber, which includes the sender's own connection and every other device of the same account. Either copy can arrive first. The rule that makes both orders safe: a message with a key already known, or a number already applied, is a duplicate. The first copy moves the message from pending to confirmed; the second is counted and dropped.
Figure 3. The ack and the echo for one message
How to read this: the two replies can swap places. The result is the same either way, which is what the lab's test "ack then echo, or echo then ack, shows it once" checks.
A second detail: a pending message sits below every confirmed message, even if the user pressed Send before another person's message was numbered earlier. When the ack arrives, the message moves to its true position and may jump above a message that was on screen below it. That is correct (the server's order is the truth) and it is a reason to show the "sending" state clearly: the user can see the message is not placed yet.
Order, gaps and history
The transport guarantees order inside one connection only. A reconnect can skip messages, a broadcast can arrive after a later one, and a client that was asleep wakes up to a world that moved on. The rule from the earlier reconnection lesson applies one level up, per conversation: append a message only if its number is exactly the last applied plus one.
- Lower or equal: duplicate. Drop it and count it.
- Exactly next: append, then release any held messages that now follow.
- Higher: a gap. Keep the message in
held, emit onefetch-historyeffect for "everything after my last number" and do not emit another while one is in flight.
When the history page arrives, each message goes through the same rule, so overlap is harmless: a page that repeats what you have adds nothing. If the page fills the gap, the held messages are released in order. If it makes progress but a gap remains, ask again; if it makes no progress at all, report it instead of looping forever.
Figure 4. What the core does with an incoming message
How to read this: all three branches are cheap and local. The only effect in the whole diagram is the single history request, which is why a burst of messages after a gap costs one request and not one per message.
The same request is used after a reconnect: the core emits fetch-history for every conversation, starting after its last applied number, and resends the unsent pending messages with their original keys. The user sees nothing except, perhaps, a moment of "Sending".
Receipts are watermarks
Delivery and read ticks look like per-message flags, but storing them that way is expensive and fragile: opening a conversation with 500 unread messages would send 500 updates, and a lost update leaves a message stuck on "sent". A cheaper design says "delivered up to 41" and "read up to 38". One number upgrades every message at or below it.
Two rules keep watermarks honest. They only move forward: a late "delivered up to 2" after "read up to 3" changes nothing. Read implies delivered: a read watermark raises the delivered one too. Both are one Math.max in the reducer, and a receipt that changes nothing returns the same state object, so nothing re-renders.
Unread, "read", and the badge
The unread count of a conversation is the number of someone else's confirmed messages with a number above lastReadSeq. The badge is the sum over all conversations. Nothing is stored per message.
When does lastReadSeq advance? The reference design says: when the page is visible, this conversation is open, and the list is scrolled to its end. All three are facts the UI reports as events (focus, open, scroll), and the core derives reading from them after every step. When it advances, one send-read effect goes out with the new number, once per advance rather than once per event.
- Visible.
document.visibilityStateisvisiblewhen the page is the foreground tab of a non-minimized window andhiddenfor a background tab, a minimized window or an active screen lock, and thevisibilitychangeevent reports changes. MDN wordsvisibleas "may be at least partially visible", so treat it as "probably seen", not proof. - Open and at the bottom. Opening a conversation with unread messages sets a "new messages" divider after the old watermark and does not mark anything read yet; the user scrolls, and only the end of the list being in view clears the divider and the count.
- The badge. The core emits a
set-badgeeffect only when the total changes. The Badging API'snavigator.setAppBadge(n)sets a number on the app's icon and0clears it, but MDN marks it as secure-context only and not Baseline, so it is an enhancement: the tab title and an in-page count remain the baseline.
A message that arrives while the page is hidden stays unread, and the moment the page becomes visible the count drops and the read receipt goes out. That behaviour is a one-line difference ("is the page visible") and a common source of wrong counts.
Typing and presence
Typing is a presence-like signal with a short life: "Ana is typing" is true until a deadline, and a new signal extends the deadline. The core stores until per user and a tick event removes expired ones, so the indicator disappears even if the "stopped typing" message is lost. The five-second value in the lab is an assumption, not a standard. Online status and "last seen" belong to the presence layer (grace periods, one record per connection, diffs with versions) and should not be folded into typing: they have different lifetimes and different consequences when wrong. See Presence and Pub/Sub.
Rendering a long conversation
Twenty thousand messages in the DOM is not a design, so the view shows a window of them: List Virtualization covers measuring variable-height rows and keeping only the visible slice. Chat adds three twists.
- The anchor is the bottom. New messages append at the end and the view stays pinned only if the user was already at the end; if they scrolled up to read, an incoming message must not move what they are reading. A "jump to latest" button with the unread count is the usual answer.
- Loading older messages inserts above. Content inserted above the viewport pushes everything down unless scroll position is corrected. Browsers implement scroll anchoring, which "adjusts scroll position to minimize content shifts" and is on by default (MDN,
overflow-anchor); a virtualized list that measures its own rows usually needs its own correction too. Pagination mechanics are in Pagination and Infinite Scroll. - Reading is tied to the viewport. An
IntersectionObservercan report when the last message or a divider enters the view: MDN describes it as asynchronously observing changes in a target's intersection with a root, which is the right shape for "has the end of the list been seen".
Several tabs and an unreliable device
Three tabs of the same account should not open three sockets and send three read receipts. The usual pattern is one tab that holds the connection and tells the others over a BroadcastChannel, which MDN describes as a named channel any browsing context of one origin can subscribe to, delivering a message event to every listening object except the one that sent it. How the tabs choose the connected tab (a lock, a heartbeat) is a design choice this lesson does not prescribe; Cross-Tab Sync with BroadcastChannel works through the options.
Offline is the same problem at a slower pace: pending messages must survive a reload (see Offline Queues and Background Sync and IndexedDB and Storage Quotas), and on restore a message that was in flight is turned back into "pending", because its outcome is unknown and the key makes a repeat safe. Persist the conversation window, not the whole history; a stale cache is acceptable as long as the first thing the core does after connecting is ask for what it missed.
Accessibility
A chat list is a live region by nature. The ARIA log role is defined for "chat logs, messaging history" and has an implicit aria-live of polite and aria-atomic of false, so screen readers announce new items when the user is idle and read only what was added. Use it on the message list. Give the unread badge an accessible name ("3 unread") rather than a bare number, keep the composer as a labelled field, announce typing in a separate status region, and keep the "New messages" divider as a real separator. Focus must stay in the composer after sending. More on live regions is in Accessible Forms and Dynamic Content and Keyboard, Focus and Screen Readers.
Build it: the conversation core and a thin React layer
Goal. Drive the core through a send, an echo race, a gap, receipts, unread messages and a retry, and read the effects it emits.
Setup. The lab web-chat-client is in the course's example workspace (Node 26). It is new, so it does not duplicate the others: reconnecting-socket keeps one connection correct, presence-pubsub models who is online, offline-outbox persists writes, and chat-message-model handles a streaming AI reply. Here the transport is only a list of effects. The logic is one pure function, step(state, event); a small store and a React component ChatApp read it with useSyncExternalStore. Nothing runs against a network or a real browser.
cd examples/frontend
pnpm install
cd labs/web-chat-client
pnpm test # 35 tests: 27 for the core, 8 React (jsdom)
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare section 1 with the output below. Whichever copy of the confirmation arrives second is counted as a duplicate, and the message is shown once.
Expected output, captured from a real run (Node 26.13.1; section 1):
=== 1. Send: the message shows at once, the ack and the echo are the same message
I press send (key c1)
effect: send ana key=c1
seq - me "Lunch at 1?" sending
unread in ana: 0, held: none, duplicates dropped: 0
the server's echo reaches us first
then the ack for the same key
seq 1 me "Lunch at 1?" sent
unread in ana: 0, held: none, duplicates dropped: 1
- In section 2, the user's pending message stays below a confirmed message from Ana until its own ack gives it seq 3.
- In section 4, a message numbered 6 arrives when only 1 to 3 are known. One
fetch-historyeffect is emitted, the message numbered 7 does not cause a second request, and the history page releases 4 to 7 in order.
Expected output, captured from a real run (Node 26.13.1; section 4):
=== 4. A gap: seq 6 arrives while we only have seq 3
incoming seq 6 (we have 3)
effect: fetch-history ana after seq 3
incoming seq 7 (same gap, no second request)
seq 1 me "Lunch at 1?" read
seq 2 ana "1 is fine" received
seq 3 me "Or 1:30?" read
unread in ana: 1, held: 6,7, duplicates dropped: 1
the history page arrives with seq 4 and 5
effect: set-badge 4
seq 1 me "Lunch at 1?" read
seq 2 ana "1 is fine" received
seq 3 me "Or 1:30?" read
seq 4 ana "booked a table" received
seq 5 me "great" sent
seq 6 ana "see you there" received
seq 7 ana "bring the laptop" received
unread in ana: 4, held: none, duplicates dropped: 1
- In section 5, three messages arrive in a closed conversation and the badge reads 7 in total. Opening the conversation shows the divider but reads nothing; scrolling to the end while the page is hidden still reads nothing; making the page visible emits
send-readfor seq 3 and the badge drops to 4.
Expected output, captured from a real run (Node 26.13.1; section 5):
=== 5. Unread: three messages in a chat that is closed, then open it and scroll to the end
Dev team: seq 1
effect: set-badge 5
Dev team: seq 2
effect: set-badge 6
Dev team: seq 3
effect: set-badge 7
badge value: 7, total unread: 7
open Dev team (not scrolled to the end yet)
--- new messages ---
seq 1 bo "deploy at 4" received
seq 2 cy "ok" received
seq 3 bo "rolled back" received
unread in dev: 3, held: none, duplicates dropped: 0
the page is hidden, then scrolled to the end
scroll to the end while hidden: still unread
the page becomes visible
effect: send-read dev up to seq 3
effect: set-badge 4
seq 1 bo "deploy at 4" received
seq 2 cy "ok" received
seq 3 bo "rolled back" received
unread in dev: 0, held: none, duplicates dropped: 0
What the lab does not show. No real socket, no timing, no real scrolling or visibility (the React tests supply the geometry and the visibility state by hand), no server and no persistence. The numbering, the receipts and the history request are this lab's own protocol, not any product's. Group chats, deletion and edits are not modelled.
Break it. In src/chat.ts, in markRead, delete || !state.atBottom. Messages are then marked read when a chat is opened, before they were scrolled to; two tests fail. Restore the line and run the tests again.
Trade-offs
| Decision | Option A | Option B | Reference choice |
|---|---|---|---|
| Where order comes from | Client timestamps | Server sequence per conversation | Server sequence; timestamps are only for display |
| Receipts | Flag per message | Watermark per conversation | Watermark: fewer writes, no stuck ticks |
| Own message on echo | Append again, dedupe by text | Match by key | Key; text is not unique |
| Gap handling | Reload the conversation | Hold and fetch after last seq | Hold and fetch: no flicker |
| Read rule | Read on arrival | Read when seen | Read when seen: visible, open, at end |
| Tabs | Each tab has a socket | One connected tab, others follow | One connected tab; costs coordination code |
| Cache | Whole history | A window per conversation | A window; ask for what was missed on connect |
In practice: a team chat that showed the wrong unread count
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A company runs an internal web chat. People keep it open in a background tab all day. Support receives two kinds of complaint: "the badge says 4 but I have read everything" and "I replied, and my reply showed up twice, then once".
Starting architecture
Figure 5. Starting point: arrival means read, echo means append
How to read this: nothing in the path knows which messages are mine or already seen, so every echo is appended and every frame is counted.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Dedupe by text and time | Duplicate replies | Cheap | Two identical short messages collapse into one |
| Recompute the count from the server on every frame | Correct count | One request per frame | Slow and racy |
| Key for matching, watermark for reading, derived count | Both symptoms | A small core with tests | The server must echo the key and accept read watermarks |
The decision
| Field | Decision record |
|---|---|
| Context | Wrong counts and doubled replies in a long-lived background tab. |
| Decision | Give each message a client key echoed by the server, derive unread from a per-conversation read watermark, and advance it only when the page is visible, the conversation is open and the list is at its end. |
| Consequences, good | One message per key; counts agree across tabs because they derive from the same watermark. |
| Consequences, bad | The server contract grows (keys, watermarks); there is a core to maintain. |
| Revisit when | Group chats need per-member receipts, or a mobile client must share the read rule. |
Rollout and verification
- Drive the reducer with recorded event sequences from the field, including echo-before-ack and a gap.
- Ship the server echo of the key first, so old clients keep working and new ones can match.
- Watch two counters: duplicates dropped (a few are normal, a spike means the server is replaying) and held messages older than a few seconds (a gap that is not closing).
The 2 a.m. failure
A deploy restarts the chat servers and every client reconnects at once. Some conversations show a "New messages" divider with a count of 40 that does not clear. The sequence numbers of one conversation restarted at 1 on a server that lost its counter, so the client treats the new messages as duplicates (illustrative).
First three checks: (1) does the history request return numbers lower than the client's last; (2) did the server change the conversation's epoch; (3) is the duplicate counter rising for one conversation only. Mitigation: on a number lower than the last applied for a conversation, discard the local window and reload it instead of dropping messages. Follow-up: put an epoch in the protocol so a reset is detected and not guessed.
The other side of this topic
On the back end, the same problem is who assigns the sequence number, how a message is stored and fanned out, and what "delivered" means across devices. See the back-end chat case study and Delivery Guarantees. The client's rules are only as good as the server's promises about numbering and echo.
Architect's notes
- Decide what the sequence number is scoped to. Per conversation is the simplest rule a client can check; a global number forces gaps that are not gaps.
- Write the server contract before the UI. Key echo, history after a number, cumulative receipts and an epoch are the four things the client depends on.
- Keep reading derived. If "read" is a flag set by a component's effect, tabs and devices will disagree; if it is a watermark moved by a rule, they converge.
- Test event orders, not components. The bugs are in orders: echo before ack, history before the gap message, a read receipt before the page was visible.
- Treat the badge as an enhancement. The App Badging API is not available everywhere, so the in-page count must be correct on its own.
Common mistakes
- Using client time to order messages. Clocks differ; use the server's number.
- Deduping by text. Two "ok" messages are two messages.
- Marking messages read on arrival, especially in a hidden tab.
- Per-message receipt updates that cost one request per message and leave stuck ticks.
- Looping on history when a page does not fill the gap.
- Moving the user's scroll position when a message arrives while they read older ones.
- Opening a socket per tab.
Key takeaways
- A message has a client key and a server number; the key matches, the number orders.
- Show your own message at once as pending; the ack and the echo are the same message, and the second copy is a duplicate.
- Append only the next number; hold what arrives early and fetch the gap once.
- Receipts are forward-only watermarks; read implies delivered.
- A message is read when the page is visible, the chat is open and the list is at its end.
- Keep rules in a pure core with effects, so the hard orderings are unit tests.
Practice exercises
- Epoch. Add an
epochfield to the conversation and make the reducer discard the local window when the server's epoch changes. Write the test first. - Per-member receipts. Change the two watermarks to one per member and render "read by 2 of 5". What happens to a message sent before a member joined?
- Break the rule. Remove the check that stops a second history request while one is in flight, and write the test that shows the cost of a burst of messages after a gap.
- Plan the tabs. Draw a sequence diagram for three tabs where one holds the socket and the others receive state over a broadcast channel. What happens when the connected tab is closed?
- Accessibility pass. List what a screen reader announces when a message arrives in the open conversation, in a closed one, and while typing; decide which should be silent.