Clocks and ordering
Overview
“Which happened first?” sounds trivial. On one machine, it is. Across several machines it isn’t, because each has its own clock and none of them is exactly right. Many subtle bugs in distributed systems, from lost updates to messages shown out of order, come from trusting timestamps. This lesson explains why and what to use instead.
Physical clocks drift
Every server’s clock is a quartz oscillator that runs slightly fast or slow. NTP (Network Time Protocol) corrects it periodically, but:
- typical error between servers is milliseconds, sometimes far more on a bad network,
- NTP corrections can make a clock jump backwards,
- leap seconds, virtual machine pauses and misconfiguration add surprises.
So a timestamp from server A and one from server B can be in the wrong order, even when the events were hundreds of milliseconds apart in reality.
Use the monotonic clock of a single machine for measuring durations (timeouts, latency); it never goes backwards. Use wall-clock time for showing dates to humans, not for ordering events across machines.
Last write wins
Many replicated stores resolve conflicting writes with last write wins (LWW): keep the value with the highest timestamp. It’s simple and often acceptable (for example, a “last seen” field). But with skewed clocks, LWW can silently discard the write that really came last, and it always discards one of two concurrent writes. Don’t use it for data where losing an update matters.
Logical clocks
A Lamport clock gives every event a number that respects cause and effect:
- Each node keeps a counter and adds 1 for every event.
- Messages carry the sender’s counter.
- On receiving a message, a node sets its counter to
max(local, received) + 1.
If event A could have influenced event B, A’s number is smaller. Ties are broken by node ID to get a total order. The catch: a smaller number doesn’t prove A came before B; the two may be unrelated (concurrent).
Vector clocks (or version vectors) fix that by keeping one counter per node. Comparing two vectors tells you whether one update happened before the other or whether they’re concurrent. Dynamo-style databases and sync systems use them to detect conflicts instead of silently overwriting.
Practical ordering tools
Most systems avoid the problem by giving one component the job of ordering:
- A single leader or database assigns sequence numbers or commit order (all writes for a record go through one primary).
- A partitioned log orders messages within a partition by offset; key by the entity whose order matters (week 4).
- Version numbers on records: an update states the version it’s based on and is rejected if someone else updated first (optimistic concurrency).
- Hybrid logical clocks combine wall-clock time with a logical counter: close to real time, but never going backwards and respecting causality. Used by CockroachDB and others.
- Bounded clock uncertainty: Google Spanner’s TrueTime uses GPS and atomic clocks to know the maximum clock error and waits it out before committing, so timestamps can be trusted for ordering.
Handling concurrent updates
When two updates are truly concurrent (neither saw the other), you need a policy:
- reject one and ask the user to retry (optimistic concurrency),
- merge them field by field,
- use CRDTs (conflict-free replicated data types), data structures such as counters, sets and text sequences designed to merge automatically; collaborative editors use these,
- keep both versions and let the user choose.
In an interview
If your design replicates writable data or orders events from several sources, say how ordering works: “Messages in a chat are ordered by a per-conversation sequence number assigned by the conversation’s partition leader, not by client timestamps, which can be wrong.” That single sentence avoids a classic trap.
Recap
Physical clocks on different machines disagree and can jump, so cross-machine timestamps aren’t a safe way to order events, and last-write-wins can lose data. Lamport clocks capture cause and effect; vector clocks also detect concurrency. In practice, let one leader, sequence or partition assign order, use version numbers for updates, and choose an explicit policy for truly concurrent changes.
Order the edits
A shared notes app lets users edit the same note from a phone and a laptop. Each device syncs to one of several servers, and servers replicate to each other. Today each save is stored with the server's wall-clock time, and the newest timestamp wins. (a) Describe a scenario where a user's latest edit is lost. (b) Suggest a better way to decide which version is newer. (c) What should happen when two edits are truly concurrent?
(a)
(b)
(c)(a) The user edits on the laptop (saved via server 1 at 10:00:05.300) and, a moment
later, edits on the phone (saved via server 2, whose clock is 400 ms behind, at
10:00:05.100). When the servers replicate, "last write wins" keeps the laptop
version because it has the bigger timestamp - the phone edit, which was really
later, is silently lost.
(b) Use versions instead of wall clocks: each note has a version number; an edit says
"based on version 7", and the server accepts it as version 8 only if the current
version is still 7 (optimistic concurrency). Across replicas, version vectors
record which updates each copy has seen, so a newer version can be recognised
regardless of clocks.
(c) If neither version has seen the other (concurrent), don't silently pick one: keep
both and merge (field-level merge, or text merging/CRDTs for collaborative
editing), or show a conflict copy for the user to resolve.Summary
- Wall clocks on different machines drift and jump, so timestamps from different nodes can't reliably order events.
- 'Last write wins' by timestamp can silently discard newer writes.
- Logical clocks (Lamport clocks) order events by cause and effect without real time.
- Version vectors detect whether two updates are ordered or concurrent, so conflicts can be resolved deliberately.
- In practice, use a single sequencer (a leader, a database sequence, a partition offset) or version numbers wherever order matters.