Sub topic 7
Ordering messages and generating IDs
This chapter assumes you know how a one-to-one message travels from sender to recipient (the previous chapter) and are comfortable with key-value stores and short Python snippets. Here you will see how a chat system keeps messages in a consistent order and gives each one a unique ID.
What "order" means in chat
Users do not need one global order across all chats. They need every participant of a single conversation to see the same sequence. So ordering only has to hold per chat. This is much cheaper than global ordering, because each chat can be handled independently, and different chats can live on different servers.
Wall-clock timestamps are a poor basis for ordering. Client clocks drift and can be set to any value. Server clocks differ by milliseconds, and two messages can share the same timestamp. Network delay also means arrival order is not the order in which users typed.
Two kinds of IDs
A message needs two identifiers, and they solve different problems.
- Client message ID. The client generates it, for example with
crypto.randomUUID(). It stays the same across retries, so the server can recognize a resend. It is for deduplication, not ordering. - Per-chat sequence number. The server assigns it when it stores the message. It defines the order inside one chat.
The pair (chat_id, seq) identifies a message within the system, and seq is what clients sort by.
Assigning sequence numbers
The simplest approach is to let one component own each chat's counter. The chat's write path increments the counter and stores the message together with the new number. Because only one writer handles a given chat at a time, there are no gaps from races and no two messages share a number.
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 returns the stored message instead of creating a new one. Deduplication and sequencing work together here: the duplicate check runs first, so a retry never consumes a sequence number.
In production the counter lives in a database or a key-value store, for example an atomic increment on a per-chat key, or a row updated inside a transaction. To keep a single writer per chat, route all writes for a chat to the same server, usually by hashing chat_id.
Why not one global ID generator?
A single global counter is a bottleneck and a single point of failure. If you need IDs that are unique across the whole system and roughly time-sortable, use a distributed scheme such as a Snowflake-style ID. It packs a timestamp, a machine ID, and a local counter into 64 bits, so each machine generates IDs without coordination.
| Approach | Ordering | Coordination | Typical use |
|---|---|---|---|
| Per-chat counter | Exact within a chat | One writer per chat | Display order |
| Snowflake-style ID | Roughly by time | None between machines | Globally unique message ID |
| Random UUID | None | None | Client message ID |
Many systems use both: a Snowflake-style ID as the unique message key, and the per-chat seq for display order and for syncing ("give me everything after seq 120").
Common errors
- Sorting by client timestamp. Two users see different orders.
- Assigning
seqbefore the duplicate check. Retries create gaps and extra messages. - Letting two servers write the same chat. Both read the counter as 41 and both write 42.
- Treating a Snowflake ID as strictly ordered. Clock skew between machines can reorder IDs created within the same millisecond range.
Exercise
Alice's phone loses signal after sending message "m-7" and resends it twice. The chat's last sequence number was 9. What seq does "m-7" get, and what does the next new message from Bob get?
Show answer
"m-7" gets seq 10 the first time it is stored. The two resends hit the duplicate check and return the stored message with seq 10, so no numbers are used. Bob's next message gets seq 11.