Mr. Darto types "Mrs. Rini, when will my laundry be ready?" on a phone whose signal keeps dropping. The message has to appear on Mrs. Rini's counter within seconds, exactly once, in the right order, complete with sent, delivered and read marks. That is the job of a realtime chat.
It works much like sending a letter by courier. Mr. Darto gives the letter a number himself and writes it on the envelope. So if the courier is unsure and delivers it twice, Mrs. Rini knows it is the same letter. The post office gives it an archive number, so every letter can be put in order. The courier brings back a receipt. In the chat for order #12, Mr. Darto's number is the cid, the archive number is the server's id, and the receipt is a Socket.IO acknowledgement.
What one message looks like
This is one chat message, as the server stores it:
{ "cid": "3f6c1e9a-8b2d-4c41-9f0e-5a7d2b1c8e44", "id": 58, "order": 12, "from": "darto",
"text": "Mrs. Rini, when will my laundry be ready?", "at": "2026-10-11T09:20:05+07:00" }
cid: made by the sender's phone withcrypto.randomUUID()(a function built into the browser that makes a unique random text, like the one above) before it is sent. It is there to recognise a resend.id: the sequence number from the server's database. It is there for order and history (older messages that are loaded again).fromandat: filled in by the server from the login and the server's clock, not from what was sent.
Mr. Darto's phone and Mrs. Rini's counter are both in the room chat:12. To keep this example short, every chat screen is on the namespace /.
Server: save first, then broadcast
Before you read the code, guess: the server has saved Mr. Darto's message, but the receipt never reaches his phone because of a bad signal. So the phone sends the message again, with the same cid. How many times does the message appear on Mrs. Rini's counter?
io.on('connection', (socket) => {
socket.on('chat:send', async (m, ack) => {
let message = await db.messages.findByCid(m.cid) // a resend?
if (!message) {
message = await db.messages.save({ cid: m.cid, order: m.order, from: socket.data.user, text: m.text })
io.to(`chat:${m.order}`).emit('chat:message', message) // broadcast only once saved
}
ack({ id: message.id, at: message.at }) // a resend gets the same answer
})
})
- The message is saved to the database before it is broadcast, so it is not lost if a connection drops. Anything that ever appeared on a screen is in the database and can be loaded again. The database becomes the source of truth.
- The message appears once on Mrs. Rini's screen. A resend with the same
cidis found in the database, so it is neither saved nor broadcast again, only answered. Without thecidcheck, the database saves it twice (id58 and 59) and the server broadcasts it twice. The history loaded from the database shows two messages too. - In the database, give
cida unique index: a rule that refuses two rows with the samecid. Then even two sends arriving at the same moment cannot both be saved.
Client: show it first, confirm it later
This is the chat code on Mr. Darto's phone. store(m) keeps the message in a Map, then draws the message list again with render:
const messages = new Map() // cid -> message: one cid, one row
async function send(text) {
const m = { cid: crypto.randomUUID(), order: 12, text, status: 'sending' }
store(m) // optimistic: shown right away with a grey clock
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const { id, at } = await socket.timeout(5000).emitWithAck('chat:send', m)
return store({ ...m, id, at, status: 'sent' })
} catch {
// no answer: try again with the SAME cid
}
}
store({ ...m, status: 'failed' }) // show a "Send again" button
}
socket.on('chat:message', (m) => store({ ...m, status: 'sent' }))
function store(m) {
messages.set(m.cid, { ...messages.get(m.cid), ...m })
render([...messages.values()].sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity)))
}
- Optimistic send: the message appears right away, before the server answers. The ack (the receipt) from the server changes its status to sent.
io.to('chat:12')also sends to Mr. Darto's own phone. Because theMapuses thecidas its key, the server's copy replaces the optimistic copy instead of adding a row.- Order uses the server's
id, not the phone's clock. Messages without anidyet sit at the bottom. - Tried with socket.io 4.8.4: if the connection drops before the ack arrives,
emitWithAckfails right away withsocket has been disconnected. The next attempt waits in the queue, is sent after reconnecting, and the server answers with the sameid(58).
Ticks: sent, delivered, read
| Mark | Meaning | Comes from |
|---|---|---|
| ✓ sent | the server has saved it | the chat:send ack |
| ✓✓ delivered | Mrs. Rini's screen has received it | the counter emits chat:delivered { order: 12, upTo: 58 } |
| ✓✓ read | Mrs. Rini opened the chat | the counter emits chat:read { order: 12, upTo: 58 } |
Store one number per person per chat ("Mrs. Rini has read up to id 58"), not a mark on every message. Every message with an id up to 58 counts as read.
The typing indicator
- Mr. Darto's phone sends
typingwhile he types, at most once every 2 seconds (a throttle), andstop-typingwhen the message is sent or the field is cleared. Typing 40 letters over 8 seconds makes 4 events, not 40. - Mrs. Rini's counter shows "Mr. Darto is typing...". The counter hides it when
stop-typingarrives, when his message arrives, or 3 seconds after the lasttyping. The 3 seconds are chosen to be longer than the 2-second gap, so the indicator does not flicker. The 3-second limit also makes the indicator go away ifstop-typingnever arrives (for example, Mr. Darto's phone dropped). - The server passes the event on with
socket.to('chat:12').emit('typing', ...), so the sender does not receive it. The server does not savetypingevents.
History after reconnecting
Events broadcast while Mrs. Rini's counter is disconnected never reach it (at-most-once, from the Event-Based Architecture lesson). So every time it connects, the counter asks for the messages it missed:
socket.on('connect', async () => {
socket.emit('follow-chat', 12)
const fresh = await fetch(`/chat/12/messages?after=${lastId()}`).then((r) => r.json())
fresh.forEach((m) => store({ ...m, status: 'sent' }))
})
lastId() is the largest id already on screen. Socket.IO's connectionStateRecovery option helps with short drops (up to 2 minutes), but it does not replace this step: the counter might be off for 10 minutes.
Showing other people's text
A chat's content is written by customers, so treat it as dangerous. For example, Mr. Darto (or a prankster) sends <img src=x onerror="alert('hi')">:
liis a message's row on the screen.li.innerHTML = m.textruns theonerroron Mrs. Rini's counter: the imagexfails to load, so the code inonerrorruns. That is XSS: code sent by someone else runs on your page.li.textContent = m.textshows it as plain text. React's{m.text}is safe too, because it is escaped (signs like<are changed so they show as text).
⚠️ What gives a chat duplicates, a wrong order or XSS
- Resending with a new
cid. The server cannot recognise it, and the message appears twice. Make thecidonce, before the first attempt. - Ordering by the phone's clock. A customer's phone clock can be minutes off. Order by the server's
id. crypto.randomUUID()on a tablet opened athttp://192.168.x.x. That is a computer's address on the local network. Tried in Chromium and WebKit: on a page that is not HTTPS or localhost, the function does not exist (TypeError: crypto.randomUUID is not a function). Use HTTPS, or build thecidfromcrypto.getRandomValues.innerHTMLfor chat text. UsetextContent.
TL;DR: Each message has a cid made by the sender's phone (to recognise resends) and an id from the server (for order and history). The server saves to the database first, then broadcasts to the room chat:12. A resend is answered with the same id, without broadcasting again. The client shows the message right away (optimistic), waits for the ack (the receipt) with socket.timeout(5000).emitWithAck, resends with the same cid, and keeps messages in a Map by cid. The sent tick comes from the ack. The delivered and read ticks come from one upTo number per person (up to which id messages have been received or read). Send typing at most every 2 seconds and stop-typing when done. The receiver hides the typing indicator after 3 seconds without news. On every connect, fetch the messages after the last id. Show text with textContent, not innerHTML, to avoid XSS (code sent by someone else running on your page).
⚡ cid from the phone, id from the server
Meaning: Each chat message has two numbers. The cid is made by the sender's phone with crypto.randomUUID() (a unique random text) before it is sent. It lets the server recognise a resend as the same message. The id is the sequence number from the server's database. It is there for order and history (older messages).
⚡ Save first, then broadcast
Guess first: the server has saved Mr. Darto's message, but the receipt never reaches his phone, so the phone sends the message again with the same cid. How many times does the message appear on Mrs. Rini's counter?
Once. A resend with the same cid is found in the database. So it is neither saved nor broadcast again, only answered with the same id.
Meaning: The server saves to the database first, then broadcasts to the room chat:12, the chat room for order #12. The database becomes the source of truth: anything that ever appeared on a screen is in the database.
⚡ The typing indicator
Meaning: While Mr. Darto types, his phone sends the event typing at most once every 2 seconds, then stop-typing when the message is sent. The counter shows "typing...". The counter hides it when stop-typing arrives, or 3 seconds after the last typing if stop-typing never arrives.
⚡ Other people's text goes in textContent
Write:
li.textContent = m.text
Meaning: li is a message's row on the screen, and m.text is the message's text. A chat's content is written by customers, so treat it as dangerous. textContent shows it as plain text. li.innerHTML = m.text can run an onerror (code inside an image tag someone sent) on Mrs. Rini's counter. That is XSS: code sent by someone else runs on your page.