Sub topic 2
Following a One-to-One Message End to End
Assume you know basic HTTP, persistent connections, databases, and short JavaScript or Python programs. The goal is to deliver a message between two users, preserve chat order, and avoid duplicates when the network fails.
Message flow
Alice's client sends a message through a WebSocket connection. The client creates a unique clientMsgId before sending. The server authenticates Alice, validates the chat, assigns the next sequence number for that chat, stores the message, and forwards it to Bob's connected devices.
The server's write must happen before it reports success. Otherwise, a server crash can make the sender think a message was saved when it was not.
Ordering and IDs
A per-chat sequence number gives a stable display order. The server should assign it when the message is accepted. A client-generated ID identifies the send attempt, even before the server assigns a sequence number.
Do not use a timestamp as the only ordering key. Clocks can differ, and two messages can have the same timestamp.
| Identifier | Created by | Main purpose |
|---|---|---|
| `clientMsgId` | Sender client | Detect retried sends |
| `seq` | Chat service | Order messages within one chat |
| `messageId` | Service or database | Globally identify the stored message |
Acknowledgements, retries, and deduplication
An acknowledgement, or ack, confirms that the server accepted and stored a message. If Alice loses the connection before receiving the ack, she resends the same clientMsgId. The server looks up that ID and returns the existing message instead of appending another one.
This provides at-least-once delivery: the system may transmit a message more than once, but idempotent writes make the stored result appear once.
class ChatLog:
def __init__(self):
self.messages = []
self.seen = {}
def append(self, client_msg_id, text):
if client_msg_id in self.seen:
return self.seen[client_msg_id]
message = {"seq": len(self.messages) + 1,
"client_msg_id": client_msg_id, "text": text}
self.messages.append(message)
self.seen[client_msg_id] = message
return message
log = ChatLog()
assert log.append("m-1", "hello") is log.append("m-1", "hello")Choosing storage for chat history
A database with partitioning by chatId fits the common access pattern: fetch recent messages for one conversation in sequence order. Store message text and metadata there. Store large attachments in object storage and keep only their URLs and metadata in the message record.
Use a durable event or queue between acceptance and fan-out when delivery work must survive connection-server failures. Keep the deduplication key long enough to cover the retry window.
Exercise
Why must a retry reuse the original clientMsgId?
Show answer
The server uses it to recognize the retry and return the existing message instead of creating a duplicate.