Real-time Chat Application — Realtime

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…

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" }

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
  })
})

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)))
}

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

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')">:

⚠️ What gives a chat duplicates, a wrong order or XSS

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.

What you will learn