Sub topic 6
Following a one-to-one message end to end
This chapter assumes you know the basics of HTTP and WebSocket, and that you have read the architecture chapter. It follows one message from Alice's phone to Bob's phone. You should be able to explain each hop and say what fails at each one.
The path of a message
Alice and Bob each hold a WebSocket connection to a chat server. The two connections are usually on different servers. A session service records which server holds each user's connection.
Step by step
- Send. Alice's client creates a
clientMsgId, keeps the message in a pending map, and sends it over the WebSocket. - Assign order. The server gives the message a per-chat sequence number. Ordering is covered in the next chapter.
- Persist. The server writes the message to the store before doing anything else. If the write fails, Alice gets no acknowledgement and her client retries.
- Acknowledge. The server tells Alice the message is stored. Alice's client removes it from the pending map.
- Route. The server asks the session service where Bob is connected and forwards the message to that server.
- Deliver. Bob's server pushes the message down his WebSocket. Bob's client acknowledges it.
- Fall back. If Bob has no live connection, the message stays in the store. A push notification tells him to reconnect.
The client side
The client sends with a client-generated ID and resends anything that has not been acknowledged.
const ws = new WebSocket("wss://chat.example.com/ws");
const pending = new Map();
function sendMessage(chatId, text) {
const clientMsgId = crypto.randomUUID();
const msg = { type: "send", clientMsgId, chatId, text };
pending.set(clientMsgId, msg);
ws.send(JSON.stringify(msg));
}
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
if (data.type === "ack") {
pending.delete(data.clientMsgId);
}
});
setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) return;
for (const msg of pending.values()) {
ws.send(JSON.stringify(msg));
}
}, 5000);The server side
Because the client resends, the server will sometimes see the same message twice. It uses the sender and the client ID to detect this and returns the stored message instead of creating a second one.
from collections import defaultdict
class ChatLog:
def __init__(self):
self.messages = defaultdict(list)
self.seen = {}
def append(self, chat_id, sender_id, client_msg_id, text):
key = (chat_id, sender_id, client_msg_id)
if key in self.seen:
return self.seen[key]
seq = len(self.messages[chat_id]) + 1
msg = {
"chat_id": chat_id,
"seq": seq,
"sender_id": sender_id,
"client_msg_id": client_msg_id,
"text": text,
}
self.messages[chat_id].append(msg)
self.seen[key] = msg
return msg
log = ChatLog()
a = log.append("c1", "alice", "m-1", "hello")
b = log.append("c1", "alice", "m-1", "hello")
assert a is b and a["seq"] == 1This in-memory version shows the logic only. A real system needs the sequence assignment and the duplicate check to happen atomically in the store.
Common errors
- Acknowledging before persisting. If the server crashes after the ack but before the write, the message is lost and Alice believes it was sent.
- Forwarding before persisting. Bob may see a message that later disappears from history.
- Treating the session lookup as always correct. The record can be stale if Bob's connection dropped. Delivery to a dead server must fall back to the store and push path.
- Skipping the deduplication key. Retries then produce duplicate messages.
Exercise
The server crashes right after storing a message but before sending the ack to Alice. What happens next, and why is there no duplicate?
Show answer
Alice's client still has the message in its pending map, so it resends after the interval. The server finds the same (chatid, senderid, clientmsgid) key, returns the stored message with its original sequence number, and sends the ack. No second copy is created.
Exercise
Why is the message written to the store before it is forwarded to Bob's server?
Show answer
The stored copy is the source of truth. If forwarding or delivery fails, Bob can still fetch the message later. If the server forwarded first and then failed to store it, Bob could see a message that is missing from history.