Clocks and ordering

Topic 2 of 9 in Week 5: Distributed systems and service communication10 min readAdvancedFree course

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.

Why wall clocks can’t order events. Server A writes x equals 1 at 10:00:05.300 by its clock, with Lamport counter 1, and replicates the write to server B, which receives it with Lamport counter 2. Afterwards, server B writes x equals 2 at 10:00:05.100 by its clock, with Lamport counter 3. B’s write happened after A’s, but B’s clock is 300 milliseconds behind, so last-write-wins by timestamp would keep x equals 1, which is wrong. A Lamport clock adds 1 per event and, on receiving a message, takes the maximum of local and received values plus 1. Vector clocks also detect concurrent writes, and Spanner-style TrueTime bounds clock error.

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:

  1. Each node keeps a counter and adds 1 for every event.
  2. Messages carry the sender’s counter.
  3. 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.

Exercise

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?

Text
(a)
(b)
(c)

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.