Sub topic 6
Following a One-to-One Message End to End
This chapter traces a single message from Alice's phone to Bob's screen. It builds on the high-level architecture and the message data model from earlier chapters. It leaves ID generation, retry details, and group fan-out to later chapters, and only points at them where the flow touches them.
Prerequisites
You should know the following:
- How a WebSocket connection stays open between a client and a server.
- The difference between a stateless API server and a stateful chat server.
- The basic shape of a message record: conversation ID, sender, text, timestamp.
- Basic JavaScript and Python, enough to read short snippets.
The cast of components
Five components take part in a one-to-one send.
| Component | Role in the flow |
|---|---|
| Client | Opens a WebSocket, sends messages, shows incoming messages |
| Chat server | Holds WebSocket connections, accepts sends, pushes deliveries |
| Session registry | Maps each user (or device) to the chat server holding its connection |
| Message store | Durable log of messages, keyed by conversation |
| Push service | Notifies users who have no live connection |
The chat server is stateful because it owns open sockets. The session registry lets any chat server find the one that owns a given user. A fast key-value store with expiry usually serves as the registry.
The happy path
Alice and Bob are both online, but their sockets are on different chat servers.
The steps in order:
- Alice's client creates the message with a client-generated ID and sends it over her WebSocket.
- Chat server 1 validates it: Is Alice authenticated? Is she a participant in this conversation? Is the text within size limits?
- Chat server 1 writes the message to the store and gets back a per-conversation sequence number.
- Chat server 1 acknowledges to Alice. This ack means "the server has stored it", not "Bob saw it".
- Chat server 1 asks the session registry which server holds Bob's connection.
- It forwards the message to that server, which pushes it down Bob's socket.
- Bob's client replies that it received the message, and the state of the message advances.
Steps 3 and 4 come before steps 5 to 7. Storing first means a crash during delivery loses no data. Bob can fetch the message later even if the forward fails.
Client side: send and wait for the ack
The client treats a message as pending until the server acknowledges it. The following code keeps a map of pending messages and resends them periodically.
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 clientMsgId is the key to the whole design. The client can resend the same message many times, and the server can recognize it each time. The UI can show a clock icon while the ID is in pending and a single check mark after the ack.
Server side: store once, even if sent twice
The server writes the message and assigns the next sequence number for that conversation. It uses the sender's client message ID to detect repeats.
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 is an in-memory model. A real store needs the duplicate check and the sequence assignment to happen atomically, for example with a unique constraint on (chat_id, sender_id, client_msg_id). Later chapters cover that in detail. For this chapter, note the behavior: a retry returns the stored message, so the server can send the same ack again without creating a second copy.
Message states
A message moves through a small set of states. Each state is triggered by a specific event.
| State | Meaning | Who reports it |
|---|---|---|
| Pending | Created on the client, no server ack yet | Client, locally |
| Sent | Stored durably by the server | Server ack |
| Delivered | Reached at least one of the recipient's devices | Recipient client |
| Read | Recipient viewed the conversation | Recipient client |
Delivered and read are reported by the recipient and relayed back to the sender through the same path, reversed. These receipts are small messages with their own routing, but they do not need the same durability as text. Losing a read receipt is annoying. Losing a message is a bug.
When Bob is offline
The registry lookup at step 5 can return nothing. This happens when Bob has no live connection, or his registry entry has expired. In that case:
- The message is already in the store, so nothing is lost.
- The chat server hands a notification job to the push service so Bob's phone can show an alert.
- When Bob reconnects, his client tells the server the highest sequence number it has for each conversation. The server sends everything after that.
The third step makes the store the source of truth and the live push only a fast path. If a live delivery is dropped, the next sync picks the message up.
Edge cases
- Stale registry entry. The registry says Bob is on server 2, but the socket closed a moment ago. Server 2 finds no connection and reports failure. Server 1 treats Bob as offline. The message stays in the store, so this is safe.
- Ack lost on the way back. Alice's message was stored but the ack never arrived. Her client resends after the timer. The server finds the existing record and re-acks. Alice sees one message and Bob receives one.
- Server crashes after storing, before forwarding. The client got an ack, so it believes the send worked. Bob's next sync fetches the message from the store.
- Gap detection. Bob's client receives sequence 7 after sequence 5. It knows 6 is missing and fetches it, instead of showing an incomplete conversation.
- Out-of-order arrival. Two forwards can overtake each other. The client orders messages by sequence number, not by arrival time.
- Bob has several devices. The registry holds several entries for Bob. The server delivers to each one, and the message counts as delivered when the first confirms.
What this flow guarantees
At this point the flow gives you:
- A durable record before any acknowledgement.
- Retries from the client until the ack arrives.
- No duplicate records, because the server recognizes repeated client message IDs.
- Recovery of anything missed through sequence-based sync.
Later chapters refine the pieces: how to generate sequence numbers at scale, how acknowledgement semantics map to at-least-once delivery, and how the same path handles many recipients in a group.
Exercise
Alice sends a message, the server stores it as sequence 12, and the ack is lost because her connection drops. Her client reconnects and resends after five seconds. Describe what the server does, what Alice's client does when it receives the next ack, and how many copies of the message Bob ends up with.
Show answer
The server looks up the key (chat ID, Alice's ID, client message ID), finds the existing record with sequence 12, and returns it without creating a new one. It sends the ack again. Alice's client receives the ack, removes the message from its pending map, and stops resending. Bob ends up with exactly one copy, because only one record exists in the store and delivery is based on that record's sequence number.
Exercise
A chat server forwards a message to Bob's server, but Bob's socket closed one second earlier and the registry entry had not yet expired. The forward fails. Is the message lost? Explain how Bob eventually gets it.
Show answer
No. The message was stored before delivery was attempted. The failed forward means Bob's message is not pushed live, so the sender's server treats him as offline and can trigger a push notification. When Bob reconnects, his client reports the highest sequence number it has for the conversation, and the server sends all later messages, including this one.