Order events within a stream
Messages or events arrive out of order across servers with skewed clocks.
Say it like this
Messages in a conversation need a total order and gap detection, so one shard owns each conversation and assigns a sequence number per message; I never order by client clocks.
Basic solution
Assign a per-stream sequence number from a single owner and let clients detect gaps.
One owner, one counter per conversation
Every message for conversation 42 goes to the shard that owns it. The shard assigns the next number, stores the row keyed by (conversation, seq), and the recipient detects the gap when 1043 arrives before 1042.
How it works
- All writes for one stream (a conversation, a device, a partition key) are routed to a single owner: the shard whose hash range contains that key. The owner is the only process allowed to assign numbers for that stream.
- The owner keeps the last sequence number for the stream in memory, backed by the store. When a new message arrives it assigns last + 1 to that message, in the order the messages reached the owner, and advances the counter.
- The message is stored keyed by (stream id, seq), so the store keeps messages for one stream physically adjacent and sorted, and a range read for seq 1000 to 1050 returns them in order without sorting.
- Clients remember the highest seq they have seen for each stream. When a new message arrives with seq greater than last + 1, the client knows exactly how many messages it has not received and fetches that range from the store.
- Across streams there is no order and none is promised; two conversations have independent counters. Conversation 42 reaching seq 1043 says nothing about conversation 43.
- If a global order across streams is truly needed, use a logical clock (a Lamport clock, where every message carries a counter that each node bumps past any counter it has seen) or a single sequencer process that every write passes through, and accept that the sequencer caps throughput.
Why not timestamps
- Two servers with 50 ms of skew will reorder messages sent 20 ms apart. Clients lie about time. Only a single owner can hand out a gap-free sequence.
Worked example
Chat app, one conversation
- 200 million messages per day across 50 million conversations; a busy group sends 10 messages per second.
- Messages for conversation 42 all land on shard hash(42) mod 256. That shard keeps last_seq for 42 in memory (backed by the store) and increments it: 1041, 1042, 1043. Two senders posting at the same instant are serialised by the shard, so they get 1042 and 1043 in whichever order the shard received them.
- Storage key is (conversation_id, seq). A client that last saw 1041 and receives 1043 fetches WHERE seq > 1041 AND seq < 1043 and gets exactly the one missing message, with no guesswork about what else might be missing.
- Counter cost: one atomic increment per message on one shard. At 10 messages per second for the busiest group that is nothing; the shard as a whole handles about 10,000 messages per second, so one shard serves roughly 200,000 conversations at average rates.
- Cross-conversation order is never needed: the inbox is sorted by each conversation's latest message time, which can be approximate because the user only needs rough recency there.
Variants and when each wins
Single owner counter (one shard per stream)
- The shard that owns the stream increments one counter per message. It wins for anything users read in order, because it is gap-free, cheap and gives a total order within the stream; the only care is moving the counter with ownership on failover.
Log partition offsets (Kafka)
- The broker assigns an offset to each message as it appends to a partition, so the log itself does the sequencing. It wins when the stream is already a Kafka topic, with the same limit that order holds only within one partition.
Lamport or hybrid logical clocks
- Each node keeps a counter that it advances past any counter it sees on an incoming message, so the counters respect cause and effect across nodes. It wins when events on different nodes must be related without a central sequencer, but it cannot tell you that a number is missing.
Server timestamp with a tiebreaker
- Order by the server's receive time, breaking ties by node id. It wins only as a sort key where small reorderings are harmless, such as an activity feed; it can never detect gaps.
Recommendation: a per-stream counter owned by one shard for anything users read in order; logical clocks when you must relate events across streams.
Failure modes
Duplicate sequence after failover
- You notice two different messages both stored with seq 1042. It happens because the shard that took over the conversation started from a stale copy of the counter and reissued a number the old owner had already used. Persist the counter with every write, or derive it from the store (the maximum stored seq) when ownership moves, and fence the old owner so it cannot assign numbers after the move.
Gap that never fills
- You notice a client waiting forever for seq 1042, showing a loading spinner between 1041 and 1043. It happens because the writer took number 1042, then crashed before storing the message, so nothing will ever arrive with that number. Assign the number and write the row in one atomic step, or have the recovery path write a tombstone for the abandoned number so clients can skip it.
Hot stream
- You notice one group with 100,000 members saturating its shard while the other shards idle. It happens because every write for that stream must pass through the single owner to get a number, so a hot stream cannot be spread out. That serialisation is inherent; keep the owner's work to the minimum (assign the number and append the row) and do the expensive fan-out to members elsewhere.
Ordering by client time
- You notice replies appearing above the message they answer. It happens because the client's clock was used as the sort key, and one phone's clock was a few seconds behind. Sort by the server-assigned sequence; use the client time only for display.
Cross-shard ordering expectations
- You notice a product requirement for a global order of all events across every conversation. It happens because the requirement was written without anyone pricing it: a global order means a single sequencer and a throughput ceiling. Push back with that cost, or introduce the single sequencer knowingly and accept its limit.
Interviewer follow-ups
Answer out loud before you open each one.
How does the client know it is missing a message?
It keeps the last sequence number per conversation. A message with seq greater than last plus one means at least one is missing, so it requests the range. Because the sequence is gap-free, there is no ambiguity about what to fetch.
How do you generate the per-conversation sequence at scale?
Route every message for a conversation to the shard that owns it and increment a counter there, either in memory with periodic persistence and recovery from max seq, or with an atomic increment in the store. Thousands of conversations per shard spread the load, and no coordination is needed across shards.
When would you use a Lamport clock instead?
When events on different nodes must be ordered relative to each other and there is no natural single owner, such as replicated edits to a shared document. It gives a consistent causal order but cannot detect gaps, so it does not replace a per-stream counter for chat.
What happens when the shard that owns a conversation moves?
The new owner must learn the current counter before accepting writes, either from the persisted value or from the maximum stored seq, and the old owner must be fenced so it cannot assign numbers after the move. A short unavailability for that conversation is acceptable; duplicate numbers are not.
Connections
- Built on
- Vector clock
- Pairs with
- Partition the data · Keep events as a replayable log · Deliver to users who are offline · Do not trust the client clock
- Pulls against
- Scale out, not up
- Used in
- Chat App (WhatsApp / Messenger)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Chat shard 17 | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Keyspaces | Message store | Bigtable | Managed Instance for Apache Cassandra | Apache Cassandra, ScyllaDB |