A chat screen looks like a list and a text box, and it is one of the hardest frontends to get right, because the data arrives whenever it likes and the network keeps going away. This chapter designs the client of a chat application, following the seven steps of the method chapter.
Step one lists what people can do. The functional requirements for this design are these.
Send and receive text messages in one-to-one and group conversations.
See whether a message you sent is sent, delivered or read.
See an unread marker, and jump to the first message you have not read.
Keep working when the connection drops: messages typed offline are sent when it returns.
Open the app in several tabs, and see the same conversations in each.
See light signals, such as who is typing, over the same connection.
Out of scope, said aloud: end-to-end encryption, which is named and not built and has its own design; voice and video calls; pictures and files; message search; editing and deleting; and push notifications to a closed browser, which depend on a service worker and a push service. The backend half of chat, with its fan-out, storage and delivery to offline devices, is in the group chat chapter of the System Design course.
Question
Because the answer changes
How large can a group be?
whether the client can show every member's receipts, or only a count
Must every member see messages in the same order?
ordering by the server or by each device's clock
How much history should be one scroll away?
paging, storage and the memory plan
Is the app open on several devices or tabs at once?
one connection per device, and how tabs coordinate
Which scripts and languages?
text direction, emoji, and what a character limit counts
Targets
The quality requirements need numbers and a way to check each. The targets below are ours, chosen for a phone on 4G.
Area
Target
How it is checked
Latency
a message appears on the other side within about a second
timestamps in a lab run with a local server
Correctness
no message lost, none shown twice, the same order for every member
drop connections and replay in a test; compare lists
Reconnect
after a drop the list catches up without a reload and without a flood of requests
cut the connection in a lab run
Offline
a message typed offline is kept, shown as sending, and sent later exactly once
reload with unsent messages
Resources
one connection per device, not one per tab
count sockets on the server
Accessibility
new messages are announced politely; the list and the composer work by keyboard
role and live-region checks
Languages
right-to-left and mixed scripts, emoji, accurate length limits
render and count test strings
Security
message text is data, never markup
inject markup in a test message
What counts as a character
The composer has a limit, and the first question is what it counts. String.length counts UTF-16 code units, which are not what a person sees. A Hindi word, an emoji with a skin tone and a flag are each one thing to the reader and several to the engine. The script counts a few strings three ways. The third way uses Intl.Segmenter with grapheme granularity, which splits text the way a reader would.
js
const seg = new Intl.Segmenter('en', { granularity: 'grapheme' })
const graphemes = (s) => [...seg.segment(s)].length
const samples = [
['hello', 'hello'],
['Hindi word', 'नमस्ते'],
['emoji', '👍🏽'],
['family emoji', '👨👩👧'],
['flag', '🇮🇳'],
]
console.log('text'.padEnd(14), 'UTF-16', 'code points', 'what you see')
for (const [name, s] of samples) {
const units = String(s.length).padStart(6)
const points = String([...s].length).padStart(11)
console.log(name.padEnd(14), units, points,
String(graphemes(s)).padStart(12))
}
length.mjs: three counts.
js
// the limit is for what people see, and a byte cap stops abuseconst LIMIT = 1000const BYTE_CAP = 16 * 1024const check = (s) => {
const bytes = new TextEncoder().encode(s).length
if (bytes > BYTE_CAP) return'too many bytes'if (graphemes(s) > LIMIT) return'too long'return'ok'
}
console.log('1,000 emoji :', check('👍🏽'.repeat(1000)))
console.log('1,001 letters :', check('a'.repeat(1001)))
console.log('1,000 Hindi :', check('नमस्ते'.repeat(1000)))
for (const n of [5000, 9000]) {
const s = 'e' + '\u0301'.repeat(n) // one letter, n accents
console.log(`one letter, ${n} accents:`.padEnd(26),
graphemes(s), 'grapheme ->', check(s))
}
length.mjs: a limit for what people see, and a byte cap.
text
text UTF-16 code points what you see
hello 555
Hindi word 663
emoji 421
family emoji 851
flag 4211,000 emoji : ok
1,001 letters : too long
1,000 Hindi : too many bytes
one letter, 5000 accents: 1 grapheme -> ok
one letter, 9000 accents: 1 grapheme -> too many bytes
Output (Node 24)
'नमस्ते' has six code units and three graphemes. The thumbs-up with a skin tone is four code units, two code points and one grapheme. The family emoji is eight code units and one grapheme. So a limit of 1,000 should count graphemes, and then 1,000 emoji are allowed. A limit alone is not enough, because one letter followed by thousands of combining accents is still one grapheme. The run shows that 5,000 accents pass the grapheme limit, and a byte cap, 16 KiB here, stops 9,000. The cap protects the server, and the server must enforce both, because the client's count is a convenience.
Why does the design limit message length in graphemes and also in bytes?
Graphemes match what the reader sees, so a short Hindi word or an emoji is not counted as several characters.
One letter with thousands of accents is one grapheme but many bytes, so the byte cap is what stops it.
The family emoji has length 8 in JavaScript. What does the run show for the reader's count?
One grapheme.
A limit based on length would treat it as eight characters.
Why is the client's character count not enough on its own?
Any client can skip the interface and send a longer message, so the server must check too.
The client count is for the person typing.
Part 2 · Architecture and data model
The pieces of a chat client
Step two draws the client from the standard skeleton. In a chat the weight is on the transport and on a part that the feed and the video player did not need: a sync engine, the code that keeps the client and the server in step across drops, restarts and several tabs.
Piece
Its job
Message list and composer
draw messages, keep the reader's place, take new text
State store
every message once, in the server's order, with its status
Outbox
messages typed but not yet acknowledged, kept in IndexedDB so a reload cannot lose them
Socket
a WebSocket with a heartbeat, reconnect with jitter, and resume from a sequence number
Tab coordinator
one tab owns the socket; the others hear it through a broadcast
The server boundary says what the client may trust. The server owns the order of messages in a conversation, the identity of the sender, and who may read what. The client owns only how things look and what is typed but not yet sent.
Identity and order
Two identifiers do two different jobs. The client id is made on the device when the message is typed, and it is the message's identity from the first moment. It lets the client track a message before the server has seen it, and it lets the server recognise a retry. This is the idempotency key from the method chapter, carried inside the message, and it is a full random UUID: a shortened id would make two messages collide, and the server would take the second for a repeat of the first. The sequence number, seq, is given by the server, one number per conversation, going up by one. It is the order.
The order cannot come from the device clock. Two phones disagree about the time, and a message typed offline at 9:00 may reach the server after one typed at 9:05. So the screen shows messages in seq order, and a message that has no seq yet, one that is still sending, is shown after all the confirmed ones, in the order it was typed. The types in the store say this directly.
ts
exporttype Status =
'sending' | 'failed' | 'sent' | 'delivered' | 'read'exporttype Message = {
clientId: string // made on the device: its identity
seq: number | null// the server's order; null until it has spoken
convo: string
from: string
mine: boolean
text: string
createdAt: number // device clock, ms: only orders unsent messages
status: Status
}
exporttype ChatStore = {
messages: Record<string, Message> // by clientId
order: Record<string, string[]> // convo -> clientIds, in order
contiguous: Record<string, number> // highest seq, none missing below
}
exportconst emptyChat = (): ChatStore =>
({ messages: {}, order: {}, contiguous: {} })
chat-store.ts: a message, and what the store keeps.
State
Home
Why
Messages and their order
client store, copied from the server
the server decides the order
Unsent messages
the store and the IndexedDB outbox
they must survive a reload
Connection status
local UI state
a view of the socket, not data
Draft text in the composer
local UI state
a draft is not a message yet
Which conversation is open
the URL
a link or Back should restore it
The store, and what it does with bad input
Five functions change the store, and each has a case that real traffic produces. A message may be pressed twice, arrive twice, arrive in the wrong order, or arrive as the answer to a message we sent. Receipts may arrive in any order. The core is one function that takes a batch of stored messages.
chat-store.ts: receipts only move a message forward.
The driver replays the cases against it. Each pair of lines shows the display order as id:seq, then the status of the three messages this user typed, a, b and c, and whether a hole was found.
text
empty (empty)
| hole after null
typed a, a again, b a:- b:-
a=sending b=sending | hole after null
theirs arrives (seq 1) x:1 a:- b:-
a=sending b=sending | hole after null
seq 3 before seq 2 x:1 z:3 a:- b:-
a=sending b=sending | hole after 1
seq 2 fills the hole x:1 y:2 z:3 a:- b:-
a=sending b=sending | hole after null
seq 2 again x:1 y:2 z:3 a:- b:-
a=sending b=sending | hole after null
server confirms a x:1 y:2 z:3 a:4 b:-
a=sent b=sending | hole after null
read, then late delivered x:1 y:2 z:3 a:4 b:5
a=read b=read | hole after null
b forced to failed x:1 y:2 z:3 a:4 b:5
a=read b=failed | hole after null
c fails, no ack in time x:1 y:2 z:3 a:4 b:5 c:-
a=read b=failed c=failed | hole after null
the ack arrives late x:1 y:2 z:3 a:4 b:5 c:6
a=read b=failed c=sent | hole after null
Output (Node 24)
Pressing send twice with the same id made one message. Seq 3 arriving before seq 2 produced a hole after 1, which the store reports so that the socket can ask again. Seq 2 filling the hole removed it, and seq 2 arriving again changed nothing. The server's confirmation of a gave it seq 4 and the status sent, while b, still waiting, stayed at the end. A read receipt for 5 moved both messages to read, and a late delivered receipt did not move them back. A message marked failed because its ack was slow turned to sent when the ack did arrive, and not stayed failed. The compiler checks the types too, and it catches a typo in a status name.
text
chat-bad.ts(4,19): error TS2345: Argument of type '"delivrd"' is not
assignable to parameter of type 'Status'.
Output (tsc 7.0.2, --strict)
A server frame is untrusted input as well. receiveMany skips any message whose seq is not a whole number from 1 up, since a NaN would corrupt the sort. A second driver feeds it the bad values, then a batch that is out of order and has a repeat, then a status change for a message that is not in the store, which the first version turned into a half-empty message.
text
seq NaN -> messages kept: 0
seq 0 -> messages kept: 0
seq -3 -> messages kept: 0
seq 1.5 -> messages kept: 0
seq 4 -> messages kept: 0
seq null -> messages kept: 0
seq undefined -> messages kept: 0
batch 2,1,2,3 (a repeat, out of order) -> a:1 b:2 c:3 | contiguous 3
status for a message that is gone -> 3 messages, same store: true
Output (Node 24), bad input
None of the seven bad seq values, including the string '4', created a message. The batch of 2, 1, 2 and 3 produced 1, 2 and 3 once each. The status change for a missing message returned the same store. One assumption remains: the store counts holes from seq 1, so it expects to hold a conversation from its start. A client that loads only the newest page of a long history needs a floor, the lowest seq it expects to hold, so that since and the hole check start there. This chapter keeps the simple case.
Why the batch function exists
The first version of the store took one message at a time. It was correct on every case above and slow on one the cases did not include: a long replay. Each call copies the maps, so n messages one by one cost n times n copies. The driver builds replays of different lengths and applies them both ways.
text
messages one at a time as one batch
50047 ms 1 ms | held 500 contiguous 5002000760 ms 1 ms | held 2000 contiguous 200050005492 ms 1 ms | held 5000 contiguous 500020000 skipped 17 ms | held 20000 contiguous 20000
Output (Node 24, this machine)
Five thousand messages one at a time took over five seconds on this machine (4.8 to 5.8 s in three runs). The same messages as one batch took 1 to 3 ms, and 20,000 took 9 to 31 ms. The batch function copies the maps once, adds every message, and sorts once. A client that reconnects after a long absence, or opens a conversation with a long history, hits this case on the first day. The socket lesson shows the same difference in a real page.
Why does a message that is still sending appear after every confirmed message?
It has no sequence number yet, and the server's order is the only order every member shares.
Among unsent messages the order they were typed in is kept.
What does the store report when seq 3 arrives before seq 2, and what is it for?
A hole after seq 1, which is the highest sequence number with nothing missing below it.
The socket uses it to ask the server to resend from there.
Five thousand messages took over five seconds one at a time and 1 ms as a batch. Why?
Each single call copies the maps, so the cost grows with the square of the number of messages.
The batch copies them once.
Part 3 · The transport: a WebSocket you can trust
Messages on the wire
Chat needs the server to push messages to the client the moment they exist, and the client to send at any time. The API chapter compared the transports and ran the WebSocket handshake. This design uses one WebSocket per device and puts small JSON messages on it.
Direction
Message
Meaning
client to server
{ t: "hello", convo, since }
I hold messages up to since; send me the rest
client to server
{ t: "send", convo, clientId, text }
store this message
client to server
{ t: "ping", n }
are you there?
client to server
{ t: "read", convo, upTo }
I have read up to this seq
server to client
{ t: "ready" }
the replay after hello is complete
server to client
{ t: "msg", convo, seq, clientId, from, text }
a stored message
server to client
{ t: "ack", clientId, seq }
your message was stored, in this place
server to client
{ t: "receipt", convo, kind, upTo }
your messages up to this seq are delivered or read
server to client
{ t: "pong", n }
yes, I am here
hello comes first on every connection, so a new connection and a reconnection are the same thing: the client says what it holds and the server fills in the rest. The server replies to a send with an ack for the sender and a msg for everyone else. A repeated send with the same clientId gets the same ack and does not create a second message. That is the idempotency again, at the message level. The lab server implements every frame except read and receipt, which reach the store through its receipt function, which the store run drives directly.
Two limits of the browser's WebSocket API shape the rest. RFC 6455 lets either end send a Ping frame and requires a Pong in reply, but MDN lists only send() and close() on the interface, so the page cannot send one and sends its own ping message instead. And MDN says the API has no backpressure: if messages arrive faster than the page can process them, it buffers them in memory or becomes unresponsive. bufferedAmount reports bytes still queued for sending. For backpressure MDN points to WebSocketStream, which this chapter names and does not use.
The socket, in code
The socket module keeps one WebSocket at a time and does three jobs: open and say hello, handle what arrives, and drop and retry. An old socket must never be able to affect the new one, so each handler checks that its socket is still the current one. Every timer is kept in a variable, so that a drop can clear all of them.
js
exportfunction createSocket({ url, convo, since, onMessage, onState,
pingEvery = 5000, pongWithin = 2000, readyWithin = 10000,
random = Math.random }) {
let ws = null, attempt = 0, stopped = falselet pingTimer = null, pongTimer = null, readyTimer = nulllet retryTimer = null, n = 0const put = (m) => {
if (ws?.readyState !== 1) returnfalse// not open: not sent
ws.send(JSON.stringify(m))
returntrue
}
socket.mjs: the state it keeps, and a guarded send.
js
function open() {
onState('connecting')
const mine = (ws = new WebSocket(url))
// a connection that never becomes ready is as dead as a silent one
readyTimer = setTimeout(() => drop('no ready'), readyWithin)
mine.onopen = () => put({ t: 'hello', convo, since: since() })
mine.onmessage = (e) => {
if (mine !== ws) return// an old socket, ignore itlet m
try { m = JSON.parse(e.data) } catch {}
if (!m || typeof m !== 'object') return onState('bad frame')
if (m.t === 'pong') return clearTimeout(pongTimer)
if (m.t !== 'ready') return onMessage(m)
attempt = 0// a good connection resets it
clearTimeout(readyTimer)
onState('open')
clearInterval(pingTimer)
pingTimer = setInterval(() => {
put({ t: 'ping', n: ++n })
clearTimeout(pongTimer) // one deadline at a time
pongTimer = setTimeout(() => drop('no pong'), pongWithin)
}, pingEvery)
}
mine.onclose = () => { if (mine === ws) drop('closed') }
}
socket.mjs: open a connection and handle its frames.
The first frame after a good hello is ready. Only then does the socket treat the connection as healthy: it resets the retry counter and starts the heartbeat. A frame that is not valid JSON, or is JSON but not an object, is reported and ignored, and the connection stays up. An unknown frame type goes to the caller, which ignores what it does not know. A connection that never becomes ready is dropped after a deadline, the same way as one that stops answering pings.
socket.mjs: drop a connection and try again, and what the module returns.
The wait comes from backoff, which is the subject of the next lesson.
Heartbeats, and what the run showed
A connection can look open and be dead. A phone that moves out of coverage, or a proxy that forgets a connection, may give the page no close event for a long time. The cure is a heartbeat: every so often the client sends a ping, and if no pong comes back within a deadline, it treats the connection as lost and replaces it. The lab uses a ping every 300 ms and a deadline of 200 ms so that the run is short. A real page would use intervals of tens of seconds.
A page that holds a WebSocket is not slowed by the browser's throttling of background tabs: MDN's page on the visibility API says tabs with WebSocket or WebRTC connections go unthrottled, so that the connection is not closed unexpectedly. The heartbeat timer keeps its schedule.
The driver makes the server stop answering pings while keeping the connection open, then lets it answer again, and then sends two frames that are not messages: text that is not JSON and an object with an unknown type.
text
silent server | lost (no pong), retry in 19 ms; connecting; open
server answers | lost (no pong), retry in 228 ms; connecting; open
Output (Chrome 157), a silent server
text
two bad frames | bad frame
seqs held | 1234567891011
Output (Chrome 157), two bad frames
When the server went silent, the client reported lost (no pong), picked a wait of 19 ms, and connected again. The server was still silent for the new connection too, so after it answered again, a second loss was reported, with a wait of 228 ms, before the connection settled. The waits are random, and 19 ms is a legal draw, a point the next lesson explains. A frame that was not JSON produced bad frame, and the connection and the list survived: the next message, seq 11, arrived normally.
Three probes
Three more cases came from a probe. The lab server accepts the connection and then ignores every frame, so the socket never becomes ready. A client that waits for a connection that never answers would sit there for good, because the heartbeat starts only after ready. Other frames are valid JSON but not objects, and the last case is a call to stop() while a retry is waiting.
text
mute server | connecting; lost (no ready), retry in 344 ms
server speaks | connecting; open
odd frames | bad frame; bad frame; bad frame | held 0
after stop | lost (closed), retry in 386 ms | new connections 0
Output (Chrome 157), the three probes
With a deadline of 0.4 s for the lab, the mute server was dropped as no ready and the next try went through once the server spoke. In the first version the socket stayed on the dead connection and never retried. Three of the odd frames were reported as bad frame: null, a number and a string. The array and the two objects without a usable seq went to the caller and created no message. After stop() no new connection was made. In the first version the retry that was already waiting opened one, so a socket that had been stopped on purpose reconnected.
Why does the client send its own ping, when the WebSocket protocol has ping frames?
The browser's API has no method to send a ping frame, so the page sends a message and waits for the reply.
Without one a half-open connection can look healthy for a long time.
Why does each handler in the socket compare its socket with the current one?
A replaced socket can still fire late events, and they must not change the state of the new connection.
Without the check an old close event could start a second retry loop.
What did the client do with a frame that was not valid JSON?
It reported it, ignored it and stayed connected.
Closing the connection for one bad frame would turn a small fault into an outage.
Part 4 · Reconnecting and resuming
How long to wait
When a connection drops, the client must try again, and the question is when. Trying at once is wrong if the cause is a server restart, because every client tries in the same second. A fixed wait is little better, because the clients stay in step. The usual answer is exponential backoff with jitter: the ceiling for the wait doubles with each failed attempt, up to a cap, and the actual wait is a random number from zero up to the ceiling.
js
exportfunction backoff(attempt, { base = 500, cap = 30000,
random = Math.random } = {}) {
const ceiling = Math.min(cap, base * 2 ** attempt)
return Math.floor(random() * ceiling) // anywhere from 0 to ceiling
}
The ceiling starts at 500 ms and doubles, 1 s, 2 s, 4 s, 8 s, 16 s, and stops at 30 s. A random draw from zero to the ceiling can be small, which is why an earlier run showed a wait of 19 ms. That is by design: a client that happens to draw a small number reconnects quickly, and the others are spread out. After a good connection the counter goes back to zero, so one blip does not make the next one slow.
What jitter does to a crowd
A model shows the effect. Ten thousand clients lose the server at the same moment. The server takes 500 new connections a second and turns the rest away, and each turned-away client tries again by its own rule. The model is one pass over the clients for each simulated second with a seeded random generator. It is a model, with assumptions in the numbers, and not a measurement of anything real.
text
10,000 clients, the server takes 500 connections a second
retry rule all back attempts to the server
fixed 1 s wait 20 s 105000
exponential + jitter 45 s 53327
Output (Node 24, a model)
With a fixed one-second wait every client came back every second, 1,05,000 attempts in all, and the last one connected at 20 seconds. With exponential backoff and jitter the attempts were spread out and halved, to 53,327, and the last client connected at 45 seconds. So jitter did not make recovery faster in this model. It made it gentler: half as many requests reached a struggling server, and in exchange some clients waited longer than they had to. The cap bounds that cost. Whether it is a good trade depends on how the server fails. A server that melts under a storm of retries needs the spread, and one with spare capacity might prefer the faster return.
Resuming from a sequence number
Reconnecting is only half the job. The client must also get the messages it missed. The hello frame carries since, the highest sequence number the client holds with nothing missing below it, which is the store's contiguous value. The server replays everything after it. A message that arrives again is ignored by the store, so asking for too much is harmless, and asking for too little is the error to avoid.
The same mechanism mends a hole. If a message arrives with a gap below it, the store reports a hole, and the client sends hello again on the open connection with the same since. The page asks once for each hole and not on every message, because the replay is still arriving and a hole that is being filled would be asked about again and again. If a server bug left a hole that could never be filled, asking on every frame would also loop for ever. The driver cuts the connection with two messages stored while the client is away, and later pushes only the last of three stored messages to the open connection.
text
connect | connecting; open
seqs held | 123
send, receive | 12345
connection cut | lost (closed), retry in 360 ms
after the wait | connecting; open
seqs held | 1234567
server saw | hello since 5
Output (Chrome 157)
text
only seq 10 | hole after seq 7: ask again; open
seqs held | 12345678910
Output (Chrome 157), a hole
The client held 1 to 5. After the cut it waited 360 ms, connected, said hello, since 5, and held 1 to 7. In the second case seq 10 arrived alone, the store saw a hole after 7, the client asked once, and the server replayed 8, 9 and 10. The scene shows both.
Animated sceneResuming after a drop0:21
Watch for the sequence number that the client resumes from
Read it as steps
The client says what it holds, and the server fills in the rest.
A long replay
The last case is the one the store lesson measured in isolation: a client that has been away, or is new, receives thousands of messages at once. The page can make the same mistake as the store, applying each frame as it arrives. A page that collects the frames that arrive within 30 ms and applies them with one call avoids it. A timer does the collecting and not requestAnimationFrame, because MDN says animation frame callbacks are paused in most browsers in background tabs, and a chat tab spends most of its life in the background. The driver opens a fresh page against a server that holds 5,000 messages, once with each approach, and waits until the page holds them all.
text
batching off | 5516 ms to hold 5,000
batching on | 160 ms to hold 5,000
Output (Chrome 157, lab, this machine)
Applying every frame separately took about five and a half seconds to hold 5,000 messages (5,516, 5,501 and 5,493 ms in three runs), and batching them took 160 to 233 ms. The cost sits in the store, as the earlier run showed, and the fix is to hand it batches.
Why does the wait use a random number from zero to the ceiling and not a fixed doubling?
A fixed schedule keeps clients in step, so they all return together. Random waits spread them out.
A small draw is allowed, which lets some clients return at once.
In the model, jitter halved the attempts and the last client connected later. What does that say?
Jitter protects the server from a storm of retries and costs some clients extra waiting.
Whether it is the right trade depends on how the server fails.
Why does the page ask for a resend once for each hole and not on every frame?
The replay is still arriving, so the hole is still there for a moment, and asking on every frame floods the server.
Asking again from the same position adds nothing.
Part 5 · Message lifecycle and the outbox
Five states for a sent message
A message the reader sends goes through states, and the screen should show them. It is sending from the moment the reader presses send until the server confirms it. It is sent when the server has stored it. It is delivered when the recipient's device has received it, and read when the recipient has seen it. If the server does not confirm within a deadline, it is failed, and the reader can retry.
Animated sceneThe states of a sent message0:15
Watch for the failed message that goes back to sending on retry
Read it as steps
A message that gets no ack fails, and retrying makes it sending again.
The first half of the scene is the run on the next pages. The second half comes from receipts, which only move a message forward and may arrive in any order, as the store lesson showed.
An outbox that survives a reload
A message the reader typed is data, and it must not be lost if the connection drops or the tab closes before the server confirms it. The page therefore writes each message to an outbox in IndexedDB before it sends anything, and removes it only when the ack arrives. IndexedDB is asynchronous and holds structured data, as the fundamentals chapter showed.
js
const open = (version = 1, waitMs = 3000) => new Promise((ok, fail) => {
const req = indexedDB.open('chat', version)
let late = false// another tab holding an older connection blocks an upgrade: give up// after a while instead of waiting for itconst timer = setTimeout(() => {
late = true
fail(new Error('storage busy: another tab holds the database'))
}, waitMs)
req.onupgradeneeded = () => {
if (!req.result.objectStoreNames.contains('outbox')) {
req.result.createObjectStore('outbox', { keyPath: 'clientId' })
}
}
req.onsuccess = () => {
const db = req.result
db.onversionchange = () => db.close() // let a newer version inif (late) return db.close()
clearTimeout(timer)
ok(db)
}
req.onerror = () => { clearTimeout(timer); fail(req.error) }
})
outbox.mjs: open the database, and never wait for ever.
js
// one transaction per call; inside it, only IndexedDB requestsconst run = async (mode, work, version) => {
const db = await open(version)
returnnew Promise((ok, fail) => {
const tx = db.transaction('outbox', mode)
const req = work(tx.objectStore('outbox'))
tx.oncomplete = () => { db.close(); ok(req.result) }
tx.onerror = () => { db.close(); fail(tx.error) }
tx.onabort = () => {
db.close()
fail(tx.error ?? new Error('aborted'))
}
})
}
exportconst outbox = {
add: (msg) => run('readwrite', (s) => s.put(msg)),
remove: (clientId) => run('readwrite', (s) => s.delete(clientId)),
all: async () => (await run('readonly', (s) => s.getAll()))
.sort((a, b) => a.createdAt - b.createdAt),
}
outbox.mjs: one small transaction for each call.
MDN explains the rule behind the shape of run. A transaction stays active only while requests are pending on it, and it commits once they are done, so a transaction must not wait for a network call. The wrapper therefore does only IndexedDB work inside the transaction. MDN also says that an object store can have only one readwrite transaction at a time, so concurrent writes wait their turn.
Two failures of the database itself need a rule. A new deploy that raises the database version has to wait for every older connection to close, and a tab that keeps one open blocks it. MDN describes the blocked event for the request that waits, and a versionchange event for the connection that is in the way, which should close itself. The wrapper closes its connection after every call and also on versionchange, gives up on an open that takes more than three seconds, and treats an aborted transaction as a failure. The page then still sends the message, unsaved, and notes that it could not save it. A probe opens version 2 from a second tab while the first holds version 1.
text
tab A has no handler -> tab B: blocked ... waiting at 1.5 s
tab A closes itself -> tab B: opened
Output (Chrome 157)
Without a handler the upgrade was blocked and was still waiting after 1.5 s. When the other tab closed itself on versionchange, the upgrade opened at once.
The sending code is short. The message is added to the store and to the outbox, then sent if the socket is open. When the socket opens, the whole outbox is sent, in the order the messages were typed. Each send starts a deadline, and if no ack comes, the message is marked failed.
The driver runs three situations in a real page against the lab server. The server refuses connections, three messages are typed, and the server then accepts again. Next, the server stores a message and loses its ack. Last, a tab is closed with two unsent messages, and opened again.
text
open : this tab owns the socket; connecting; open
offline : -:sending:one | -:sending:two | -:sending:three | outbox 3
back online : 1:sent:one | 2:sent:two | 3:sent:three | outbox 0
server order: 1:one 2:two 3:three
ack lost : -:failed:lost ack
after retry : 4:sent:lost ack | outbox 0
server saw : stored 0899ecfe as seq 4; duplicate 0899ecfe: ack seq 4
stored once : 1
reopened : -:sending:typed offline A | -:sending:typed offline B
then : 5:sent:typed offline A | 6:sent:typed offline B
Output (Chrome 157)
While the server refused connections, the three messages showed as sending and sat in the outbox. When it came back they were sent, acknowledged with seq 1, 2 and 3 in the order typed, and the outbox emptied. With the ack lost, the message showed as failed after the deadline, 0.7 s in the lab. A retry sent the same clientId, and the server's own log says what happened: it stored the message once, then recognised the duplicate and answered with seq 4 again. The list has one such message. After the tab was closed with two unsent messages and opened again, they came back as sending from the outbox and were sent when the server returned, as seq 5 and 6.
Why is the message written to the outbox before it is sent?
If the tab closes or the connection drops first, the message would exist only in memory and be lost.
The run shows two messages surviving a closed tab.
After a lost ack the server stored the message once, though it was sent twice. How?
Both sends carried the same clientId, and the server answers a known clientId with its existing seq.
The server log shows "stored" once and "duplicate" once.
Why does the outbox wrapper not wait for a network call inside a transaction?
A transaction commits when it has no pending requests, so waiting for something else would let it end.
Only IndexedDB requests are made inside it.
Part 6 · Several tabs
One socket for the device
People open the same chat in two tabs. If every tab opens its own WebSocket, the server holds more connections than devices, each tab sends its own heartbeat, and the same message arrives several times on one device. A better plan has one tab own the socket and the others receive what it receives.
Two browser features fit. The Web Locks API lets a script ask for a named lock. MDN describes the steps: the lock is requested, work is done while holding it in an asynchronous task, and it is released when the task ends. A callback that returns a promise which never settles keeps the lock held, so the tab that gets the lock first becomes the owner, and the others wait in a queue. MDN does not say what happens to a lock when its tab closes. The Web Locks specification releases the locks of a terminating agent but marks that part as vaguely defined, so the run below is the evidence, and each browser you support needs the same test. The BroadcastChannel API sends messages between tabs of the same origin. MDN says it is widely available since March 2022, and that tabs communicate only within the same storage partition.
js
exportfunction joinTabs({ onLead, onMessage }) {
const channel = new BroadcastChannel('chat')
let leader = false
channel.onmessage = (e) => onMessage(e.data)
// the lock is held while this promise is pending: until the tab ends
navigator.locks.request('chat-socket', () => {
leader = true
onLead()
returnnew Promise(() => {})
})
return { post: (m) => channel.postMessage(m), isLeader: () => leader }
}
tabs.mjs: a lock for the owner, a channel for everyone.
The cost of the plan is one structured copy of each frame for each other tab, which is small next to the cost of a second connection. The benefit is the rule the requirements asked for: the server sees one connection for the device, however many tabs are open, and it sends each message to the device once.
A quick run settled one question: does a channel hear its own message? A post from one channel object was heard by another object on the same channel, and not by itself.
text
post from a: a heard 0, b heard 1
Output (Chrome 157)
The tabs at work
The wiring has three rules. The owner's socket frames are applied locally and also posted to the channel as frame messages. A tab that is not the owner applies frames from the channel, and posts its own sends as send messages for the owner to put on the socket. Every tab tells the others about a message it has just typed, as pending, so each store shows it at once.
js
// the tab that owns the socketconst tabs = joinTabs({
onLead: () => { note('this tab owns the socket'); sock.start() },
onMessage: (m) => {
if (m.kind === 'frame') apply(m.frame)
if (m.kind === 'pending') {
window.store = addPending(window.store, m.typed)
}
if (m.kind === 'send' && tabs.isLeader()) trySend(m.typed)
// a tab opened late asks the owner what it already holdsif (m.kind === 'need' && tabs.isLeader()) {
tabs.post({ kind: 'snapshot', messages: Object.values(
window.store.messages).filter((x) => x.seq !== null) })
}
if (m.kind === 'snapshot' && !tabs.isLeader()) {
window.store = receiveMany(window.store, me, m.messages)
}
},
})
tabs.post({ kind: 'need' })
app.html: the tab that owns the socket, and the others.
js
const sock = createSocket({
url: `ws://${location.host}/ws`, convo: 'c1',
since: () => window.store.contiguous.c1 ?? 0,
pingEvery: 60000,
onState: (s) => { note(s); if (s === 'open') flush() },
onMessage: (frame) => {
if (frame.t === 'ack') outbox.remove(frame.clientId)
apply(frame)
tabs.post({ kind: 'frame', frame }) // the other tabs hear it
},
})
app.html: the socket, and what it does with a frame.
The driver opens two pages in one browser context. It sends one message from the tab that does not own the socket, then one from the owner, and then closes the owner.
text
tab A leader=true
tab B leader=false
tab A leader=true 1:sent:typed in B | 2:sent:typed in A
tab B leader=false 1:sent:typed in B | 2:sent:typed in A
server : 1:typed in B | 2:typed in A
sockets : 1
-- tab A closes
tab B leader=true 1:sent:typed in B | 2:sent:typed in A
sockets : 1 | server saw hello since 2
tab B leader=true 1:sent:typed in B | 2:sent:typed in A |
3:sent:sent by someone else
Output (Chrome 157)
Animated sceneTwo tabs, one socket0:15
Watch for tab B: it never talks to the server itself
Read it as steps
The follower never talks to the server. Its messages travel through the owner.
Both messages were stored once, 1 and 2, by one socket. After the owner closed, the other tab got the lock, connected with hello, since 2, and then received a message sent by someone else, seq 3. The server saw one connection throughout.
Late tabs and lost owners
One case the first version missed is a tab opened late. It joins as a follower, hears only the frames that come after it, and shows an empty list. So a new tab asks the owner for what it holds, with a need message, and the owner answers with a snapshot of the messages that have a seq. The follower applies it with the same batch function. The driver opens a third tab last.
text
tab C leader=false 1:sent:typed in B | 2:sent:typed in A |
3:sent:sent by someone else
Output (Chrome 157), a tab opened last
The third tab showed the same three messages. Before the snapshot it showed none.
The design has one more case that the run did not combine. If the owner closes while a message is waiting for its ack, nothing is lost: the outbox is in IndexedDB, which all tabs share, and the new owner sends the whole outbox as soon as its connection is ready. The message goes out with the same clientId, so if the first send did reach the server, the server recognises the duplicate. That path is the one the previous lesson ran for a reload, and the two features were not run together here.
Why does the follower tab post a pending message to the channel?
Every tab's store should show the new message at once, and the channel is how tabs share what they know.
The follower's send then goes to the owner for the socket.
What happened to the lock when the owner tab closed, according to the run?
It was released and the other tab acquired it, so that tab connected.
The server's log shows a new hello with since 2.
Why is one socket for each device better than one for each tab?
The server holds fewer connections, heartbeats are not repeated, and a message arrives once on the device.
The tabs share state through a broadcast instead.
Part 7 · Deep dive: the message list
Keeping the reader's place
The message list has two edges that grow. New messages arrive at the bottom, and history loads at the top as the reader scrolls up. Both can move what the reader is looking at, and a reader who is reading an old message does not want it to jump. The top edge comes first. When older messages are added above the visible ones, the content below moves down, and the scroll position stays where it was, so the reader sees different messages.
js
exportfunction addOlder(box, els, { compensate = true } = {}) {
const before = box.scrollHeight
box.prepend(...els)
if (compensate) box.scrollTop += box.scrollHeight - before
}
list.mjs: add older messages and fix the scroll position.
The function measures the height before, adds the messages, and moves the scroll position by the difference. Browsers also have scroll anchoring, which does the same automatically. MDN describes the overflow-anchor property as the way to opt out of it, and lists it as newly available in Baseline since September 2026. The driver adds 30 older messages in a 300 px box in six cases, and reports the number of the message at the top edge before and after.
text
older messages added above (30 of them)
case top message before -> after
scrolled to the very top 101 -> 71
scrolled to the top, fixed 101 -> 101100 px down, browser anchoring 103 -> 103100 px down, anchoring and fixed 103 -> 133100 px down, anchoring off 103 -> 73100 px down, anchoring off, fixed 103 -> 103
Output (Chrome 157)
At the very top, with no fix, the top message went from 101 to 71, so the reader's place was lost: in this run Chrome did not anchor at a scroll position of zero. The scroll anchoring specification lists a scroll offset of zero among the conditions that suppress anchoring, which fits. With the fix it stayed at 101. At 100 px down the browser's own anchoring held the message at 103. With anchoring off and no fix the position was lost, 103 to 73, and with anchoring off and the fix it held. The sixth case is the trap: with anchoring on and the fix as well, the correction was applied twice and the top message went from 103 to 133. So choose one. Setting overflow-anchor: none on the list and doing the correction in code does not depend on what a browser's anchoring does.
The newest end, and the unread marker
At the bottom the rule is different. If the reader is at the bottom, a new message should keep them there. If they have scrolled up to read something, a new message must not move them, and a small count of unseen messages tells them more have arrived. The decision must be made before the new element is added, because adding it changes the height.
js
exportfunction addNewest(box, el, onUnseen) {
const stick = nearBottom(box) // decide before the list grows
box.append(el)
if (stick) box.scrollTop = box.scrollHeight
else onUnseen() // the reader is up the page
}
list.mjs: stay at the bottom only if the reader is there.
nearBottom allows 40 px of slack, so a reader who is a few pixels off the bottom still follows the conversation. The driver puts the reader at four distances from the bottom and adds a message.
text
reader position after a new message: at bottom unseen
at the bottom true 030 px above the bottom true 060 px above the bottom false 1500 px above the bottom false 1
Output (Chrome 157)
At the bottom and 30 px above it the list followed the new message, and nothing was counted as unseen. At 60 px and 500 px above it, the reader stayed where they were and one message was counted. The unread marker is a separate question: where does the line "new messages" go? It goes before the first message from someone else after the last one read. A function finds it, and the run feeds it five cases.
text
read up to 0 seq 1
read up to 2 seq 3
read up to 4 (only mine after) none
read up to 9 (past the end) none
empty list none
Output (Node 24)
The marker goes before seq 1 when nothing is read, and before seq 3 after reading up to 2. After reading up to 4, only the reader's own message, seq 5, follows, so there is no marker. A read position past the end and an empty list give none.
Announcing messages
A screen reader user needs to hear new messages without hearing the whole history again. MDN says elements with the log role have an implicit aria-live value of polite, so changes are announced when the user is idle, and an implicit aria-atomic of false, so only the changes are announced. A chat is one of the examples MDN gives for a log.
The trap is that any change inside the live region is a candidate for announcement. Prepending 30 old messages inside the log could cause them to be read out as if they were new. A safe structure keeps two things apart. The scrolling list holds the history and is not a live region. A small log region, hidden visually, receives one line for each message that arrives live from the server, such as "Meena: running late" and nothing for history loading or for the reader's own messages. No screen reader was run for this chapter, so the behaviour is described from MDN and the roles, and should be checked with one before shipping.
Why did adding 30 older messages above the reader move the top message from 101 to 71 in the first case?
At a scroll position of zero, Chrome did not anchor, and the specification lists a zero offset as a suppression condition, so the new content pushed the old messages down and the position stayed at zero.
The fix adds the change in height to the scroll position.
Why is it a mistake to use browser scroll anchoring and the code fix together?
Both correct the position, so the correction is applied twice and the reader is moved too far, from 103 to 133 in the run.
Turning off overflow-anchor and doing the correction in code does not depend on the browser's anchoring.
Why should the history list not be the live region?
Adding old messages would announce them as if they were new.
A separate small log gets one line for each live message.
Part 8 · Checks and trade-offs
Message text is data
The last step goes through the checks. Security comes first in a chat, because message text comes from other people and is shown to someone else. The rule from the security chapter applies: show text as text. The message list sets textContent and never innerHTML. The one thing readers expect is that web addresses become links, and a link is a place where text becomes behaviour. So the function that finds links accepts only http and https addresses that parse, rejects any with a user name or password, cuts the punctuation around a link, and builds the link with the DOM.
js
const TRAIL = /[.,;:!?>\]}'"]+$/
exportfunction parts(text) {
const out = []
let last = 0for (const m of text.matchAll(/\S+/g)) {
const lead = m[0].match(LEAD)?.[0].length ?? 0const word = trim(m[0].slice(lead))
const start = m.index + lead
let url = nulltry { url = new URL(word) } catch {}
const ok = url && /^https?:$/.test(url.protocol) &&
/^https?:\/\/[^/]/.test(word) && !url.username && !url.password
if (!ok) continueif (start > last) out.push({ text: text.slice(last, start) })
const shown = word.length > 60 ? word.slice(0, 57) + '...' : word
out.push({ text: shown, href: url.href })
last = start + word.length
}
if (last < text.length) out.push({ text: text.slice(last) })
return out
}
linkify.mjs: find web links in a message.
js
exportfunction renderText(parent, text) {
for (const p of parts(text)) {
if (!p.href) {
parent.append(document.createTextNode(p.text))
continue
}
const a = document.createElement('a')
a.href = p.href
a.textContent = p.text
a.target = '_blank'// keep the chat open
a.rel = 'noopener noreferrer'
parent.append(a)
}
}
linkify.mjs: build the DOM, with text nodes and anchors.
text
message links links found, hrefs shortened
"see https://example.com/a. t"1 https://example.com/a
"click javascript:alert(1) no"0 -
"data:text/html,<b>x</b>"0 -
"http//oops.example and https"0 -
"<script>window.hacked=1</scr"1 https://example.com/ok
"https://user:pass@example.co"0 -
"नमस्ते https://example.com/h"1 https://example.com/hindi
"(https://example.com/in) and"2 https://example.com/in
https://example.com/angle
"https://example.com/wiki/Foo"2
https://example.com/wiki/Foo_(bar) https://example.com/x_(y)
"https://example.com/aaaaaaaa"1
https://example.com/aaaaaaaaaaaaaaaaaaaa (cut)
hacked flag: not set
dir=auto: Arabic, English, Hindi -> rtl ltr ltr
Output (Chrome 157)
The first message got one link and kept the full stop outside it. A link in round brackets and one in angle brackets were both found, and an address ending in a bracket pair kept it, while the extra closing bracket after it was cut. A javascript: address, a data: address, an address missing its colon and a bare https:// got none, and stayed as plain text. A message with a script tag as text got one link and no script element, and the flag was not set. An address with a user name and password, a form that can mislead a reader about where a link leads, was refused. The link opens in a new tab with rel="noopener noreferrer", which MDN says drops the Referer header and cuts the new page's link back to this one. The Hindi message linked correctly, and a link of 5,000 characters was cut for display. The last line shows dir="auto": each message picks its own direction from its first strong character, so the Arabic line is right to left and the English and Hindi lines are not.
The checks, and the trade-offs
Check
For this chat
Performance
one socket; batched updates; history in pages; long lists use the techniques of the performance chapter
Accessibility
a live region for new messages only; names for receipts; focus kept in the composer after send
Internationalisation
direction for each message; limits by grapheme; times and day separators by locale
Security
text as text; links only for http and https; no credentials in links; byte cap enforced by the server
Observability
count reconnects and their reasons, failed sends, resync requests, and the time from send to ack
Choice
Alternative rejected
Reason
What it costs
Order by server seq
order by device time
every member sees one order
a sending message waits at the end
clientId on every message
let the server number them
a retry is recognised
the server must remember ids
Resume with since
reload the conversation
only the missing part moves
the client must track holes
Backoff with full jitter
fixed retry delay
spreads a crowd of clients
some clients wait longer
IndexedDB outbox
memory only
a reload loses nothing
storage code and cleanup
One socket, tabs by lock
a socket per tab
fewer connections and heartbeats
two APIs to coordinate
Order by server seq
Alternative rejectedorder by device time
Reasonevery member sees one order
What it costsa sending message waits at the end
clientId on every message
Alternative rejectedlet the server number them
Reasona retry is recognised
What it coststhe server must remember ids
Resume with since
Alternative rejectedreload the conversation
Reasononly the missing part moves
What it coststhe client must track holes
Backoff with full jitter
Alternative rejectedfixed retry delay
Reasonspreads a crowd of clients
What it costssome clients wait longer
IndexedDB outbox
Alternative rejectedmemory only
Reasona reload loses nothing
What it costsstorage code and cleanup
One socket, tabs by lock
Alternative rejecteda socket per tab
Reason
Extensions follow. Typing and presence signals use the same socket. A typing signal is sent at most once every few seconds while the person types, and the receiving side lets it expire on its own, so a lost stop signal cannot leave "typing" on the screen. These were not built or run here. Notifications for a closed browser need a service worker and a push service, with the user's permission. End-to-end encryption changes what the server can store and what the client must keep, and is its own design. And a very long history needs the list to release old messages, with the slots idea from the news feed chapter.
Why does the link finder refuse an address with a user name and password?
The part before the @ is a user name, so a link can look as if it leads to a trusted name while it leads elsewhere.
The run shows it left as plain text.
What does dir="auto" do for a mixed-language conversation?
Each message takes its direction from its first strong character, so Arabic is right to left and English or Hindi is left to right.
A single direction for the whole page would break one of them.
Why is "count reconnects and their reasons" part of the observability check?
Reconnect storms and bad networks show up there first.
Reasons such as "no pong" or "closed" say whether the cause is the network or the server.