Video in progress

How do you guarantee message ordering and idempotency in a multi-device chat system?

Ordering isn't global; it's needed within each conversation: the server assigns a single sequence number per conversation, and that number is the source of truth. Idempotency is handled by the client-generated clientMsgId and a unique constraint.

📖 Answer

The requirement "messages should arrive in order" has to be narrowed first. Global ordering, across all conversations, isn't needed and is expensive. What is needed is that all participants in one conversation see the messages in the same order.

In practice:

  1. The client sends a message: {clientMsgId: uuid, convId, text}. The UI immediately shows it in a "sending" state.
  2. The server assigns a seq at a point that is serialized per conversation. Options: the conversation goes to one Kafka partition by convId and a single consumer assigns seq; or in the DB, UPDATE conversation SET last_seq = last_seq + 1 ... RETURNING last_seq in one transaction.
  3. A unique index on (convId, clientMsgId). If the client resends without receiving an ack, the server doesn't create a new row; it returns the earlier seq.
  4. It's distributed to all devices with the seq. The client places messages by seq, not by arrival order.

Ordering by client time (timestamp) is a classic mistake. Phone clocks differ, and users change them by hand.

Detecting a gap on the client: seq 104 arrives, the last one seen was 101, so 102 and 103 are missing. The client asks for them over REST or waits.

Trade-offs:

  • serializing per conversation means one conversation's throughput is limited by one partition or one DB row. For ordinary chats that's no problem, but a channel with 100,000 members needs a separate design;
  • the last_seq row in the DB becomes a hot spot. For very active groups the Kafka partition model is better.

Edits and deletes don't change message order: they are also events with a new seq, just of a different type. That way a device gets every change from the same stream.