Lesson 04

Clocks and Ordering

Building block

Two writes land on two machines, each stamped with its own machine's time, and the design has to say which came last. The wall clocks cannot settle it, and a store that trusts them drops the later write without an error.

Interviewers ask about clocks to hear whether you know this, and then which answer you reach for: a logical clock, a hybrid clock, or paying for a bound on the uncertainty. Often the best answer is a fourth: one owner that numbers the events.

Wall Clocks Drift and Jump

Every machine's oscillator runs a little fast or a little slow. NTP pulls the clock back toward its reference, either by slewing it, running it slightly faster or slower for a while, or by stepping it, forward or backward, in one jump. Leap seconds are either smeared out the same way or stepped.

Two rules follow. Time every duration, a timeout or a lease, on the monotonic clock, which never runs backward. And never decide which of two writes on two machines came last by their wall-clock stamps. Last writer wins by timestamp keeps the write from the clock that runs ahead, even when that write happened first. What last writer wins loses in general is Chapter 4's last lesson; this one owns the clock.

Last writer wins under clock skew
Server A runs aheadits clock is fast
→
A stamps write 1a time slightly in the future
→
B stamps write 2later in real time, earlier on the clock
→
The store keeps write 1write 2 is dropped, no error

Happened-Before and Lamport Clocks

Leslie Lamport's 1978 idea was to order only what could be cause and effect. Each node keeps a counter and adds one for every event. It sends the counter with every message. On receipt, it takes the larger of its own value and the one received, and adds one.

The promise runs one way. If one event could have caused another, its number is smaller. The reverse does not hold: two concurrent events still get an order, consistent but arbitrary, with ties broken by node ID. Telling that two writes were concurrent takes version vectors, which Chapter 4 covers with conflicts.

Hybrid Logical Clocks

A hybrid logical clock gives a timestamp that stays close to the wall clock and still respects cause and effect. Each node takes the larger of its local wall clock and the largest timestamp it has seen, and breaks ties with a small counter.

The stamp reads as a time, so a snapshot as of two in the afternoon, or an expiry time, means roughly what it says, and no effect is stamped before a cause that reached it by a message. The limit: two writes with no message between them are still ordered only as well as the clocks agree.

TrueTime: Paying for Bounded Uncertainty

Spanner's clock does not answer with a time. It answers with an interval, an earliest and a latest, guaranteed to contain the true time, and kept narrow by GPS receivers and atomic clocks in its data centres.

Commit wait puts the interval to work. The coordinator lets nobody see a commit until the commit's timestamp has definitely passed, so the order of the timestamps matches the order in real time everywhere, with no extra round of messages. The cost is that every write waits out the uncertainty, and the uncertainty stays small only because of the hardware. Spanner did not escape the clock problem. It bought a bound on it, and it pays for that bound on every write.

Three clocks: what each promises, needs and costs
Lamport clocka counter
Promises: a cause gets a smaller number than its effect.
Needs: a counter sent with every message.
Per write: nothing extra; no tie to real time.
Hybrid logical clockwall time plus a counter
Promises: causal order, in stamps that read as times.
Needs: clocks that stay roughly in step.
Per write: nothing extra; unrelated writes ordered only as well as the clocks agree.
TrueTimean interval, bounded
Promises: timestamp order matches real-time order.
Needs: GPS and atomic clock references.
Per write: a commit wait for the uncertainty to pass.

Ordering Without Clocks

Where one owner sees every event in a scope, let it number them. The server that owns a chat conversation numbers its messages, the design of Chapter 18. A partition of a log numbers its records by offset, as the message queue of Chapter 14 does. And the consensus log of the lesson on elections numbers every command it commits.

The condition is that one owner keeps up with the scope's write rate. The cost is that order exists only inside the scope. The trigger: when one owner cannot keep up, split the scope, and say out loud that order now holds only inside each piece. Event time against arrival time in a stream of events is the deep dive of Chapter 21, ad-click aggregation.

Lamport Clock vs Hybrid Logical Clock

A Lamport clock is a counter with no tie to real time, and it gives an order consistent with cause and effect. Use it when the design needs one agreed order and never asks "as of when".

A hybrid logical clock stays close to wall time and is still causal. Use it when snapshots, expiry times or audits must line up with real time, and accept that it leans on the clocks staying roughly in step.

How Interviewers Probe This

Clock probes turn on what the clocks cannot promise, the scope that needs an order, and the cheapest tool that orders it. The first probe is "Two users update the same profile through two servers a few milliseconds apart. Which update wins?" A good answer refuses to let the wall clocks decide alone, says what last writer wins loses, and either routes the key to one owner or versions it with the tools of Chapter 4, saying which loss the product can live with.

The second is "In a group chat, two phones show the same two messages in different orders. Why, and what do you change?" A good answer blames the senders' clocks or the order of arrival, has the server that owns the conversation assign a sequence number, and has every client sort by it. You might say: "The conversation's owner stamps each message with the next number, and every phone sorts by that number, never by its own clock."

The third is "Why does Spanner need atomic clocks?" A good answer explains bounded uncertainty and commit wait, and names the cost: a wait on every write, in exchange for real-time order with no extra messages.

Misconceptions
  • "NTP keeps the clocks in sync, so timestamps order the writes." NTP keeps them close, not equal, and corrects by stepping; two writes a moment apart on two machines can carry stamps in the wrong order.
  • "A clock never goes backward." The wall clock can be stepped back by NTP or by an operator. Only the monotonic clock promises not to, and its value means nothing on another machine.
  • "A Lamport timestamp says which write happened first." It says a cause has a smaller number than its effect; two unrelated writes get an order that is consistent and arbitrary.
  • "Spanner solved time." It bounded the uncertainty with GPS and atomic clocks and waits it out on every write. A design without that hardware has no such bound to wait out.
  • "A global order is the safe default." It needs one sequencer or one consensus log for every write, which is the throughput of one owner. Most products need order only inside a conversation, an account or a key.
Why It Matters
  • Time every timeout and lease on a monotonic clock, and use wall time only for display and rough stamps.
  • Name the scope that needs an order, and give it one owner that numbers its events.
  • Use a hybrid logical clock when versions must compare across nodes and still read as times.
  • Say what last writer wins by timestamp loses before you accept it for a field.
RelatedConcurrent Writes and Conflicts last writer wins and version vectorsLeases, Locks and Fencing leases on a monotonic clockIDs Without Coordination a clock that steps backConsistency Models That Come Up what readers are promised

Knowledge Check

A service times its leases with the wall clock. What can go wrong that the monotonic clock prevents?

  • The lease lasts longer on a machine with a slower processor
  • NTP steps the clock, and the lease looks expired or extended
  • The lease ends at a different time zone's midnight on each machine
  • The lease cannot be compared with another machine's lease at all

Event A has Lamport timestamp 7 and event B, on another node, has 9. What can you conclude?

  • That A happened before B in real time, by a couple of ticks
  • That B was caused by A, since its number is the larger one
  • That B did not cause A; A may have caused B, or they were concurrent
  • That the two nodes exchanged a message between the two events

Server A's clock runs 50 ms ahead. A writes a value; 20 ms later, B writes a new value for the same key. The store uses last writer wins by timestamp. What happens?

  • B's write wins, because it happened 20 ms after A's write did
  • A's write wins and B's newer value is dropped without an error
  • The store detects the conflict and keeps both values for the reader
  • Both are rejected, because their stamps fall within the skew bound

What does Spanner's commit wait buy, and what does it cost?

  • Real-time order without GPS hardware, at the cost of a slower reader
  • Faster commits than two-phase commit, at the cost of weaker isolation
  • Lamport order across data centres, at the cost of one extra message
  • Timestamp order that matches real time, at the cost of a wait per write

A chat app must show each conversation's messages in one order on every phone, with every reply below the message it answers. What is the cheapest correct design?

  • Sort by the sender's phone clock, kept in sync by the phone's own NTP
  • Run every message in every chat through one global consensus log
  • The server that owns the conversation numbers each of its messages
  • Sort on each phone by the order in which that phone received them

You got correct