Sub topic 8
Acknowledgements, retries, and deduplication
This chapter assumes you know how a one-to-one message travels from sender to chat server to recipient, and that each chat has an ordered sequence of messages. Here we cover how to make sure a message arrives at least once without showing up twice.
Why networks force a choice
A connection can drop at any moment. If a client sends a message and hears nothing back, it cannot tell whether the server never received it or whether the server stored it and the reply was lost. The client has two options:
- Give up, which risks losing the message (at-most-once delivery).
- Retry, which risks creating a duplicate (at-least-once delivery).
Chat systems choose at-least-once delivery and then remove duplicates on the server. The combined effect is that each message appears exactly once to the user.
Acknowledgements and retries on the client
The client gives every message a unique clientMsgId before sending. It keeps the message in a pending map until the server sends an ack with the same ID. A timer resends anything still pending.
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 ID is generated on the client, so every retry carries the same ID. That is what lets the server recognize a repeat.
Idempotent writes on the server
An operation is idempotent if doing it twice has the same effect as doing it once. The server makes append idempotent by remembering the key (chat_id, sender_id, client_msg_id). On a repeat, it returns the stored message and does not create a new one. The server assigns the per-chat sequence number only for new messages.
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"] == 1The server should send an ack on every attempt, including repeats. If the first ack was lost, the repeat's ack is what finally clears the client's pending entry.
Common errors
- Generating the ID inside the retry loop. Each retry then looks like a new message.
- Deduplicating on
client_msg_idalone. Two users can produce the same ID, so include the sender and chat in the key. - Keeping the
seenmap only in memory. After a restart, retries create duplicates. Store the key with the message in the database, protected by a unique constraint. - Retrying forever at a fixed interval. Add a retry limit or exponential backoff, and show the user a "failed" state.
- Skipping the ack on a duplicate.
Exercise
A client sends message m-7 and the server stores it, but the ack never arrives. The client retries. What should the server do, and why does the user see only one message?
Show answer
The server finds the key (chatid, senderid, m-7) already recorded, does not append a new message, and returns the stored message with its original sequence number. It sends the ack again, so the client clears m-7 from its pending map. Only one message exists in the log, so the user sees one.
Exercise
Why is it a problem to keep the deduplication keys only in the memory of one chat server?
Show answer
If the server restarts or the client reconnects to a different server, the keys are lost. A retry is then treated as a new message and creates a duplicate. Persisting the key with the message, with a unique constraint, makes deduplication survive restarts and work across servers.