Sub topic 8
Acknowledgements, retries, and deduplication
This chapter covers how a chat system gets at-least-once delivery without showing duplicates to users. It assumes you know how a one-to-one message travels from sender to recipient, how a WebSocket connection works, and how per-chat sequence numbers order messages. You should also be able to read short JavaScript and Python snippets.
Why networks force a choice
A message crosses several hops: sender to chat server, chat server to the message store, chat server to the recipient's connection. Any hop can fail. A connection can drop after the server has stored a message but before the sender hears about it. The sender cannot tell that case apart from the case where the server never received the message.
A sender facing that uncertainty has two options:
- At-most-once: send once and never retry. Messages can be lost.
- At-least-once: retry until the sender gets confirmation. Messages are never lost, but the server may receive the same message more than once.
Exactly-once delivery over an unreliable network is not achievable as a transport guarantee. Chat systems get the same user-visible result by combining at-least-once delivery with idempotent writes. An operation is idempotent if doing it twice has the same effect as doing it once.
Acknowledgements
An acknowledgement (ack) is a small message that says "I received and handled your message." A chat system uses acks at several points, and each one answers a different question.
| Ack | From → to | Meaning |
|---|---|---|
| Server ack | Chat server → sender | The message is durably stored and has a sequence number. |
| Delivery ack | Recipient device → server | The recipient's device received the message. |
| Read receipt | Recipient device → server | The user has seen the message. |
This chapter focuses on the server ack, because it controls retries. Delivery acks and read receipts are status updates that flow back to the sender. They use the same idempotent handling, but they do not drive resending of the original message.
The server should send the ack only after the message is durably written. If it acks first and crashes before the write, the sender discards its copy and the message is lost. The ack carries the client's message ID so the sender knows which pending message it covers. It should also carry the assigned sequence number, so the client can place the message in order.
The client side: pending map and retries
The client generates a unique ID for each message before sending. It keeps the message in a pending map until the matching ack arrives. A timer resends everything 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);Three details matter here:
- The ID is created once, when the user taps send. A retry reuses the same
clientMsgId. If the client generated a new ID per attempt, the server could not recognize a retry. - The retry loop skips work when the socket is not open. After a reconnect, the same loop resends what is still pending.
- The code shows the idea, not a production client. A real client would persist the pending map (for example in local storage or a database) so that an app restart does not drop unsent messages.
Retry timing
A fixed 5-second interval is easy to read but can cause trouble. If a server recovers after an outage, every client resends at once. Production clients usually use exponential backoff with jitter: the wait doubles after each failed attempt (1 s, 2 s, 4 s, up to a cap), and a random amount is added so clients do not retry in lockstep. They also cap the number of attempts or the age of a message, then mark it as failed in the UI so the user can retry by hand.
The server side: idempotent writes
The server must treat a repeated send as the same message. It does this by using the client message ID as a deduplication key. The key must include the chat and the sender, because two different users can produce the same client ID by chance or by bug, and the server must not merge their 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 second call finds the key in seen and returns the stored message, including its original sequence number. The sender gets an ack for the same message either way, so the retry is harmless.
Making this safe in a real system
The in-memory class has a gap that a distributed system cannot ignore. The check (key in self.seen) and the write happen as two steps. Two retries arriving at the same moment, perhaps on different servers, could both pass the check and both insert.
The fix is to let the database enforce uniqueness:
- Put a unique constraint on
(chat_id, sender_id, client_msg_id), or use it as part of the primary key. - Insert with a conditional write, such as
INSERT ... ON CONFLICT DO NOTHINGin SQL or a "put if absent" condition in a key-value store. - If the insert reports a conflict, read the existing row and return it.
The sequence number must be assigned in the same atomic step, or from a per-chat counter that only one writer advances. Otherwise a duplicate attempt could consume a number and leave a gap.
A deduplication record also costs storage. If the message row itself carries the client ID, the constraint covers deduplication with no extra table. If you keep a separate dedup table, give its entries a time to live (TTL) longer than the client's maximum retry window, for example 24 hours.
Duplicates beyond the send path
Retries also happen on the way to the recipient. The server pushes a message and waits for a delivery ack. If none arrives, it may push again, or the recipient may reconnect and ask for everything after its last known sequence number. In both cases the recipient can see the same message twice.
The recipient's client handles this with the per-chat sequence number:
- Keep the highest sequence number applied per chat.
- Ignore any message whose
seqis at or below that value. - If
seqjumps ahead (for example from 7 to 9), request the missing range before showing the later message.
This gives the same protection as the server's dedup key, and it also detects gaps.
Common errors
- Acking before the write is durable. A crash between ack and write loses the message with no retry.
- New ID on each retry. The server sees every attempt as a new message, so duplicates appear.
- Dedup key without sender or chat. Messages from different users collide, or the key space is wider than needed.
- Check-then-insert without a constraint. Concurrent retries race and create two rows.
- Pending map held only in memory. Closing the app loses unsent messages.
- Unbounded retries at a fixed interval. A server outage turns into a synchronized burst when it recovers.
- Dedup records that expire too soon. A late retry after the TTL creates a duplicate.
Exercises
Exercise
A client sends message m-5 and the server stores it, but the ack is lost. The client resends m-5 after a timeout. What must the server return, and why must it not assign a new sequence number?
Show answer
It must return the already stored message with its original sequence number, and ack it. A new sequence number would create a second copy of the message in the chat order, so the recipient would see the same text twice.
Exercise
Two chat servers receive the same retried send at the same moment. Both check the dedup table and find nothing. How do you prevent two rows from being stored?
Show answer
Enforce uniqueness in the database with a unique constraint on (chatid, senderid, clientmsgid) and a conditional insert such as ON CONFLICT DO NOTHING. One insert succeeds. The other reports a conflict, reads the existing row, and returns it. The check and the write must be one atomic operation, not two steps.
Exercise
A recipient's client has applied seq 12 in a chat and then receives seq 12 again, followed by seq 15. What should it do with each?
Show answer
Ignore seq 12 because it is at or below the highest applied sequence number. For seq 15, do not show it yet. Request seq 13 and 14 from the server, then apply 13, 14, and 15 in order.