Sub topic 7
Ordering Messages and Generating IDs
This chapter assumes you know how a one-to-one message travels from sender to receiver (the previous chapter) and that you can read short Python and JavaScript snippets. It covers how a chat system decides the order of messages and how it creates the IDs that carry that order.
Why ordering is a design problem
Two people in a chat expect to see the same conversation in the same order. That sounds easy on one machine. In a distributed system, messages are sent from different devices, pass through different connection servers, and are written by different workers. Network delays vary, so arrival order does not match send order.
Clocks do not fix this. Device clocks are wrong by seconds or more, and users can change them. Even server clocks drift. If you sort by "time the sender's phone says it was sent", a phone with a clock five minutes behind will put its messages in the wrong place.
A chat system therefore needs two things:
- A rule that defines the official order of messages in one conversation.
- IDs that are unique and that carry enough information to apply that rule.
Per-chat order is enough
Users never compare the order of messages in chat A with messages in chat B. They only need a consistent order inside each conversation. This is called per-chat ordering, and it is much cheaper than a global order across the whole system.
Global ordering would force every message in the system through one point, which does not scale. Per-chat ordering lets you spread chats across many servers. All messages for one chat go to one place that decides their order. Different chats are independent.
Server-assigned sequence numbers
The simplest rule is: the server assigns each message a sequence number (seq) when it accepts it. The sequence starts at 1 for each chat and increases by 1. Clients sort by seq, and the order is the same for everyone.
The ChatLog class from the delivery guarantees chapter shows the idea. This version focuses on the sequence assignment:
from collections import defaultdict
class ChatLog:
def __init__(self):
self.messages = defaultdict(list)
def append(self, chat_id, sender_id, text):
seq = len(self.messages[chat_id]) + 1
msg = {
"chat_id": chat_id,
"seq": seq,
"sender_id": sender_id,
"text": text,
}
self.messages[chat_id].append(msg)
return msg
log = ChatLog()
first = log.append("c1", "alice", "hi")
second = log.append("c1", "bob", "hello")
other = log.append("c2", "alice", "separate chat")
assert first["seq"] == 1
assert second["seq"] == 2
assert other["seq"] == 1Chat c2 starts at 1 again. The pair (chat_id, seq) identifies a message.
This works only if one writer at a time assigns seq for a chat. In real systems that means one of these:
- Route every message for a chat to the same server or partition, so a single process assigns numbers.
- Use a database operation that increments a per-chat counter atomically, such as a transaction or a conditional write.
If two workers read the same "last seq" and both write last + 1, you get a duplicate sequence number. This is the most common ordering bug in chat designs.
Sequence numbers also make gaps visible. If a client has seq 41 and receives 43, it knows 42 is missing and can ask the server for it. Timestamps cannot tell you that.
What the order means
The server's order is the order in which it accepted messages, not the order in which users pressed send. If Alice and Bob both type at the same moment, either can come first. What matters is that everyone agrees.
Clients should show their own message immediately, in a "sending" state, and move it to its final position once the server returns the seq. This can cause a small visible jump if another message was accepted first. That is the correct behavior and is better than showing different orders on different devices.
Two kinds of IDs
A chat message needs two different identifiers. They solve different problems.
| ID | Created by | Purpose | Scope |
|---|---|---|---|
| `clientMsgId` | Sender's device | Deduplicate retries | Unique per sender |
| `seq` | Chat server | Order messages in one chat | Unique per chat |
| `messageId` | Server (ID generator) | Globally identify a message | Unique across the system |
The client ID lets the server recognize a retry. The seq gives order. The global messageId is useful for storage keys, replies ("this message replies to message X"), reactions, and deletes.
You can build the global ID from (chat_id, seq), which needs no extra generator. Many systems still keep a separate ID generator, because it lets other services refer to a message without knowing its chat.
Generating global IDs
Your choices for the global ID, with their trade-offs:
| Approach | Strength | Weakness |
|---|---|---|
| Auto-increment in one database | Simple, ordered | One machine is a bottleneck and a single point of failure |
| Random UUID (v4) | No coordination | 128 bits, not sortable by time, poor locality in indexes |
| UUID v7 or ULID | No coordination, roughly time-sorted | Larger than 64 bits, order depends on clock accuracy |
| Snowflake-style ID | 64 bits, time-sorted, no coordination between machines | Needs unique machine IDs and a sound clock |
Snowflake-style IDs
A Snowflake-style ID packs three fields into one 64-bit integer:
- A timestamp in milliseconds since a chosen start date (41 bits, about 69 years).
- A machine ID (10 bits, 1,024 machines).
- A sequence counter within the same millisecond (12 bits, 4,096 IDs per millisecond per machine).
Because the timestamp sits in the highest bits, sorting the IDs numerically sorts them by creation time. Each machine generates IDs alone, so there is no network call.
import time
EPOCH_MS = 1_700_000_000_000
MACHINE_BITS = 10
SEQUENCE_BITS = 12
MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1
class IdGenerator:
def __init__(self, machine_id):
assert 0 <= machine_id < (1 << MACHINE_BITS)
self.machine_id = machine_id
self.last_ms = -1
self.sequence = 0
def next_id(self, now_ms=None):
now = now_ms if now_ms is not None else int(time.time() * 1000)
if now < self.last_ms:
raise RuntimeError("clock moved backwards")
if now == self.last_ms:
self.sequence = (self.sequence + 1) & MAX_SEQUENCE
if self.sequence == 0:
raise RuntimeError("sequence exhausted for this millisecond")
else:
self.sequence = 0
self.last_ms = now
return (
((now - EPOCH_MS) << (MACHINE_BITS + SEQUENCE_BITS))
| (self.machine_id << SEQUENCE_BITS)
| self.sequence
)
gen = IdGenerator(machine_id=7)
t = EPOCH_MS + 5000
a = gen.next_id(now_ms=t)
b = gen.next_id(now_ms=t)
c = gen.next_id(now_ms=t + 1)
assert a < b < cThe code refuses to continue in two cases. If the clock moves backwards, new IDs could collide with earlier ones. If the 4,096 sequence values run out in one millisecond, it raises an error rather than reusing a value. A production generator would wait for the next millisecond in the second case.
Gotchas with generated IDs
- Time order is approximate across machines. Two machines with clocks 3 ms apart can create IDs whose order differs from real order. That is why a Snowflake ID is not a substitute for
seqwhen you need an exact order inside a chat. - Machine IDs must be unique. Two generators with the same machine ID can produce the same ID. Assign them from a coordination service or at deploy time, and never reuse one for two live processes.
- Clock rollback. NTP corrections can move a clock backwards. Reject or wait, as above.
- JavaScript numbers lose precision above 2^53. A 64-bit ID sent as a JSON number will be corrupted in a browser. Send it as a string.
Choosing a design
Use these criteria when you decide:
- If users need a strict, gap-detectable order inside a chat, assign
seqper chat at a single writer. - If other services need to refer to a message by one ID, add a global ID such as a Snowflake ID.
- If you only need IDs that are unique and roughly sortable, and each chat has low volume, a Snowflake ID alone can serve as the sort key. Accept that near-simultaneous messages from different machines may sort in a slightly different order than they arrived.
- Keep
clientMsgIdregardless. It solves retries, not ordering.
Failure modes
- Sequencer failover. If the server that owns a chat dies, a new owner must continue from the highest stored
seq, not from its own memory. Read the lastseqfrom storage before accepting new messages. - Hot chats. A chat with a very large audience concentrates writes on one sequencer. This is acceptable for ordinary groups. Very large broadcast channels need a different design, covered in the group chat chapter.
- Gaps from failed writes. If a number is assigned and the write then fails, the sequence has a hole. Clients should treat a gap as "ask the server" and not as proof of loss, since the number might never have been used.
Exercise
Two chat servers both handle messages for chat "c9". Each reads the current last seq (10), then writes a message with seq 11. What goes wrong, and give two ways to prevent it.
Show answer
Both messages get seq 11, so the order in the chat is ambiguous and one write may overwrite the other. Prevent it by routing all messages for a chat to a single sequencer (one owner per chat), or by using an atomic per-chat counter increment or conditional write in the database so the second writer fails and retries with seq 12.
Exercise
A Snowflake-style ID has 41 timestamp bits, 10 machine bits, and 12 sequence bits. How many IDs can one machine create per second at most, and why is a message's ID not enough to guarantee exact order inside a chat across several machines?
Show answer
One machine can create 4,096 IDs per millisecond, so 4,096,000 per second. Across machines the order is only as good as their clocks. Two machines whose clocks differ by a few milliseconds can produce IDs whose numeric order differs from the real arrival order. A per-chat seq from a single writer gives an exact order.