A user presses Enter. The socket writes a frame. Somewhere between the browser and the database, the connection can drop, the process can be restarted, or the write can succeed while the reply is lost.
The interface has to say something. It can show a sending state, a delivered mark, or an error. Every one of those is a claim about what the system knows.
The interesting design question is not how to make the happy path fast. It is which order of operations lets the system keep its claims when the happy path is interrupted.
The acknowledgement is a promise
In WebChat, the server's acknowledgement means one specific thing: the canonical message has been written to MongoDB. It does not mean every recipient has seen it. It does not mean the message is indexed for search yet. It does not mean the file upload finished.
It means the sender can close the tab and the message will still exist.
That is a deliberately small promise, and it is the one the rest of the system can actually keep. Search indexing, read receipts, presence, and push notifications are downstream effects. They may lag. The message itself may not.
This distinction matters because chat clients are full of optimistic UI. A grey clock icon usually means "waiting for the server." A check mark usually means "the server has it." If the server acknowledges before the write commits, the check mark is a lie that only becomes visible during an incident.
Three ways a message disappears
The failure modes are easier to see if you draw the send path as a sequence rather than a box diagram.
1. Broadcast first, persist later
This is the fastest-looking design. The chat service receives a message, emits it to the room, and writes to the database in the background.
It works until the write fails. Recipients have already seen a message that does not exist in history. A reconnect makes it vanish. Worse, a second client may quote it, react to it, or reply to it. The system now has references to a message that the canonical store never accepted.
Broadcast is a side effect. It should not run before the condition that makes the message real.
2. Acknowledge before the write commits
A subtler version: the service writes to MongoDB with a fire-and-forget call, then immediately acks the sender. If the write fails, the sender has a delivered mark and no message. Retrying is now a user problem, and the client has no id to retry with.
The fix is not a longer timeout. It is waiting for the write result before making the promise.
3. Retry after a timeout
The sender writes a message, the request times out, and the client retries. From the server's perspective, this is a brand-new send. Without a shared identity, the database stores two messages.
Timeouts are not failures. They are an absence of information. The system needs a way to treat the retry as the same logical operation.
The order that works
The path that survived testing is:
- The client generates a
client_idbefore the first attempt. - The chat service validates the send and forwards it to the messages service.
- The messages service writes the canonical message to MongoDB.
- Only after the write returns does the chat service acknowledge the sender.
- The chat service broadcasts the stored message — with its server-assigned id and timestamp — to the room and to each participant's personal room.
- Background consumers update search, notifications, and other derived views.
Each step has a clear owner. MongoDB owns message history. PostgreSQL owns identity and room membership. Redis carries presence and the Socket.io adapter's fan-out. Elasticsearch owns the search index, which is explicitly allowed to be stale.
The important part is step 4. The acknowledgement is downstream of the durable write, not parallel to it.
Identity belongs to the client
The retry problem is solved by making the client responsible for the identity of the logical send. The server is responsible for deciding whether that identity has already been used.
A simplified version of the message document:
type MessageDocument = {
_id: string;
roomId: string;
senderId: string;
clientId: string;
body: string;
createdAt: Date;
};
A partial unique index enforces the rule at the storage layer:
db.messages.createIndex(
{ senderId: 1, clientId: 1 },
{
unique: true,
partialFilterExpression: { clientId: { $exists: true } },
}
);
The send handler does not check-then-insert. That pattern has a race between the check and the write. It inserts, and if MongoDB returns a duplicate-key error for the same (senderId, clientId) pair, it fetches and returns the existing message. The retry is successful and idempotent.
This also makes the client simpler. The outbox entry keeps the same client_id until the server confirms the write. A reconnect replays the outbox, and the server collapses duplicates rather than creating a second message.
Reconnect is not a special case
A reconnect is the same problem as a retry, with a different transport.
When a socket reconnects, the client asks for messages after its last known cursor. The server returns canonical history. Events that arrived while the client was offline are delivered through the participant's personal room, not just the active room socket. Multiple tabs and devices converge because delivery and read cursors are stored on room membership, not on a single connection.
This is also why the chat service cannot treat a socket id as a user identity. A socket is a temporary transport handle. A user can have several at once, and all of them should see the same canonical sequence.
What this contract does not promise
It is tempting to call this exactly-once. It is not.
The contract is at-least-once delivery with idempotent writes. A message may be sent to a room twice if a broadcast is retried after a partial failure. The client deduplicates by message id. The database prevents two canonical messages for the same client_id.
What the system does promise:
- A message that the sender saw acknowledged exists in MongoDB.
- A retry with the same
client_iddoes not create a second message. - A reconnect replays from a cursor rather than guessing.
- Search, notifications, and presence may lag, but they cannot change the canonical message.
What it does not promise:
- Every recipient sees the message exactly once.
- A push notification is delivered.
- A file upload and its message commit atomically.
- A third-party webhook runs exactly once.
Writing those limits down made the implementation smaller. It also made incidents easier to reason about: if a message is missing, the question is whether the canonical write happened, not whether some downstream consumer was feeling well that day.
The contract, written down
The final rule fits in one sentence: the canonical write completes before the sender is told the message exists.
Everything else follows from that ordering. The client_id makes retries safe. The personal rooms make multi-device delivery converge. The cursor makes reconnect ordinary. The database makes the promise durable.
The next time a send path looks simple, count the promises hidden in the spinner. A chat message is not hard because the text is long. It is hard because the interface is making claims about a distributed system in real time.