Systemsfor Aravinda
0 / 78 core
Week 4 · Distributed systemsAdvanced

Clocks and ordering

2 hours · optional track

Read first: Consistency models, Consensus and Raft

In one sitting

A Lamport clock preserves happened-before in one direction, and the converse is false. A vector clock can show that two writes were concurrent, and the client has to merge them. TrueTime is an interval you wait out, not a point and not a single epsilon.

A new-grad loop rarely requires them. The interviewer wants one order, from a leader or a quorum, and “we will timestamp it” is the answer they push back on rather than the answer they want first. The evening is worth it because that pushback has a shape. A Lamport integer does not run backwards into happened-before. A vector clock shows a conflict and then hands you the merge. TrueTime is an interval, and the commit waits until the interval has moved past the timestamp you chose. None of those is a wall clock you sort on and walk away from.

Core concepts

Machines do not share a now. A timestamp a replica reads from its own oscillator can be ahead of a peer, behind a peer, or stuck while the peer moves. If you order events by those readings, you are ordering the oscillators. Two updates to the same cart, one on each side of a partition, can receive timestamps that disagree with the order a person watching both sides would tell. The rest of this page is what you can use instead, and what each one refuses to promise.

A Lamport clock is one integer

A Lamport clock is a single integer on each process. The rule that makes it a clock, rather than a counter you happened to store, is the one Lamport stated and that you should be able to redraw. Before a local event, add one. When you send, attach the current value. When you receive, set your clock to the max of your value and the value in the message, then add one so the receive sits strictly after the send.

The theorem you get is one direction. If A happened before B, A’s clock is less than B’s. Happened-before here means the same process did A and then B, or A was a send and B was its receive, or a chain of those. The converse is not true. A smaller clock does not mean happened-before. Two events with no chain between them can still receive different numbers, because each process increments on its own. A tie does not mean “at the same time” either. It means the integers did not separate the events.

That one direction is still useful. Anything that must respect causality can stamp messages with the integer and refuse to deliver B before A when the stamps say A came first along a chain you actually observed. You cannot use the integer to detect that two writes were concurrent. If you break ties by replica id and keep one write, you have chosen a winner. You have not discovered an order that was already there.

Vector clocks, and the pain

A vector clock is one counter per replica. On a write, grow the local counter. On a merge, take the max of each component. Write X dominates write Y when every component of X is greater than or equal to Y’s and the vectors are not equal. X then happened after Y along the merges you recorded. If neither vector dominates, the writes are concurrent. You are allowed to show both to a client. You are not allowed to pretend one of them is the later one.

This is the form Dynamo used so a client could reconcile concurrent cart writes. The paper is Amazon Dynamo. It is not DynamoDB, which came later, put a primary on each partition, and used conditional writes. The pain the Dynamo authors wrote down is the part to remember: the clocks grow, and the client has to merge. Every replica you have ever written through can add a component. Concurrent versions are not collapsed by the clock. Someone who understands the cart has to decide whether two adds of the same item are a set-union or a sum. The clock only said “neither happened before the other.”

CRDTs are what you get if you refuse to leave that decision to an ad hoc client and you design the merge so it always converges. A vector clock is not yet that merge. It is the detector.

A hybrid logical clock stays near the wall

A hybrid logical clock combines a physical clock with a logical counter. The value you store is mostly the physical time, so it stays close to wall time in a way a bare Lamport integer never will. The counter is there so two events in the same physical tick, or a wall clock that stalls or steps backward, still produce a strictly increasing stamp. When a message arrives, you advance far enough to be after both your local stamp and the sender’s, which keeps the Lamport direction: happened-before still implies a smaller stamp.

The idea is the combination. There is no bit layout on this page, and there does not need to be. What you should not claim is a bound. A hybrid stamp will happily track a wall clock that is minutes off, as long as those readings are what you feed it. Causality is preserved relative to the messages you saw. Distance from true time is not. A hybrid logical clock is not TrueTime.

TrueTime is an interval

TrueTime is not a logical clock. It is an interval API. You ask for the time and you get a range, earliest and latest, and the true time is inside that range. You do not get a point. You do not get to pick the midpoint and call it the time.

Spanner’s commit wait uses the interval. The coordinator chooses a timestamp for the commit and holds the commit until that interval is past the chosen timestamp, which means the timestamp is definitely in the past. Only then is the commit released. The result is external consistency: if one transaction commits before another starts, the first has the smaller timestamp. That is the real-time order from consistency models, applied to transactions, and it is why the wait exists. If you released the commit while the true time might still be before your timestamp, a transaction that starts after you could receive an earlier timestamp. The wait closes that hole.

The Spanner paper treats the uncertainty as milliseconds, kept small with GPS and atomic clocks. There is no single epsilon to memorize, and quoting one is how this topic goes wrong. The wait is however long it takes for the interval to move past the timestamp you chose. On a bad minute the interval is wider and the wait is longer. The cost of the design is that pause, tied to clock uncertainty, plus the operational cost of the clocks. The Google Spanner page is the rest of the system: Paxos groups, and two-phase commit on top when a transaction touches more than one group. A commit wait is not a substitute for those rounds. It is an extra pause on top of them.

Clocks alone are a poor way to elect a leader. Consensus and Raft gives you a term, and a lease is only safe when the storage checks a fencing token. Two nodes with skewed oscillators can both believe they are inside their lease. TrueTime’s interval is a statement about uncertainty. It is not a license to compare two ordinary wall clocks and call the larger one the leader.

A worked example

Two replicas, A and B, and a shopping cart. You are going to apply one add on each side of a partition and read the clocks. Assumptions:

  • The cart starts empty. Both vector clocks start at zero. Components are written in the order A, then B.
  • The partition drops messages in both directions before B has seen A’s add. That is the assumption that makes the writes concurrent. If B had received the milk first, the second half of the walk is a different history.
  • No third replica is writing. The pain of a wider vector is real, and it is not required to see the conflict.
  • For the Lamport half, there are no messages at all during the short counterexample. Each process only has local events.
vectors written as A, B

start
  both replicas at 0, 0
  cart empty

A adds milk
  A increments its own component
  A is at 1, 0
  cart on A is milk

partition
  B never saw the milk write
  B is still at 0, 0

B adds bread
  B increments its own component
  B is at 0, 1
  cart on B is bread

compare 1, 0 with 0, 1
  neither vector is greater than or equal on every component
  the writes are concurrent

the clock does not decide the cart
a client that wants both items merges to milk and bread
a client that keeps one item has dropped an add

if B had received milk first
  B takes the max per component and gets 1, 0
  B increments its own component and gets 1, 1
  1, 1 dominates 1, 0
  bread happened after milk
  there is one history, not a conflict

Read the comparison slowly, because this is the whole trick. 1, 0 against 0, 1: the first component says A is ahead, the second says B is ahead. Domination needs every component. One win out of two is concurrency. The versions both survive. Dynamo’s client is now holding two carts. If milk and bread are different lines, a set union is a sane merge, and you should say you assumed the cart is a set. If both clients had set the quantity of milk, the clock still only says concurrent. It does not know whether the quantities add or whether the last human should win. That decision is the application. Leaving it to whatever request arrives next is how a cart loses a line the shopper watched you accept.

The same two adds, stamped with Lamport clocks, do not even tell you they conflict.

no messages between A and B

A adds milk
  Lamport clock on A becomes 1

B adds bread
  Lamport clock on B becomes 1

the clocks are equal
equality is not concurrency and it is not simultaneity

a second local event on A, still with no messages
  A's clock becomes 2
  B's clock is still 1
  2 is greater than 1
  A did not happen before B
  the converse of the Lamport rule is false

If you sort those stamps and keep the greater one, bread disappears behind a local event on A that bread never heard about. The theorem did not say you could do that. It said the opposite direction fails.

A wall-clock last-writer-wins register fails the same cart under a weaker excuse. Assume A’s oscillator is ahead of B’s, and assume B’s add is the one a human would call later. You do not need a measured skew, and you should not invent one. Whatever reading A has, if it is larger, A’s milk wins and B’s bread is discarded even though no message ever carried milk to B. Last writer wins is a total order you imposed. It is not happened-before, and it is not real time unless the timestamps came from something with a known uncertainty, which ordinary oscillators do not give you.

Hybrid stamps would sit near each replica’s wall clock and would still order a later message after an earlier one. They would not, by themselves, declare the two cart writes concurrent. If the replicas never exchanged a message, each hybrid clock follows its own oscillator plus a counter. You are back to comparing two physical clocks. The hybrid part saved causality along messages you actually sent. It did not detect the partition.

TrueTime is the other bill, and it belongs next to a round trip so you do not treat milliseconds as a vibe.

Dean's same-datacenter round trip = 0.5 ms
TrueTime uncertainty in the Spanner paper = milliseconds
not a single epsilon

a commit wait on the order of that uncertainty
is longer than one 0.5 ms local round trip
it is not a number you may pin to one constant

California to the Netherlands = 150 ms
a 4,000 km fiber path is about 20 ms one way
round-trip floor about 40 ms before routers

distance still dominates a global commit
commit wait is the extra pause on top of distance
the pause is what makes the timestamp definitely past

The comparison uses published bands. It is not a measured Spanner latency, and it refuses a single epsilon on purpose. If someone writes “epsilon is 7 ms” on the board, they invented it. The paper’s claim you are allowed to repeat is milliseconds, kept small with GPS and atomic clocks, and a wait until the chosen timestamp is in the past.

flowchart TB
  milk[Replica A adds milk]
  bread[Replica B adds bread]
  split[Partition between the replicas]
  client[Client holds both versions]
  milk --> split
  bread --> split
  split --> client

The client box is the pain. The partition created two versions the clock will not rank. Someone merges, or someone drops a line and calls it a timestamp.

Tradeoffs

Clock What a smaller stamp means What it does not mean
Wall clock The oscillator returned a smaller reading Happened-before, or real time, once skew exists
Lamport clock Nothing by itself The converse of happened-before; concurrency
Vector clock If one dominates, that write is after the other Which cart merge a human wanted; a bound on metadata
Hybrid logical clock Causality along messages, near wall time How far the wall clock is from true time
TrueTime interval You waited, and the timestamp is definitely past A single point, or a single epsilon you can quote
Leader term This writer was elected, and older terms lose A cross-region commit that skips the round trip

Picking the leader’s order avoids this table. The leader appends, the term fences the old leader, and two cart updates become two log entries. You pay an election and a majority round trip. You do not pay a client merge. That is the right trade until a partition must accept both writes. If it must, you are in vector clocks or a CRDT, and you should say the client, or the merge function, now owns the conflict.

Pitfalls

  • Sorting by wall-clock timestamps and calling the result causality. Skew invents winners. The cart loses the update that lost the oscillator race.
  • Reading a Lamport clock backwards. A larger integer does not mean happened-before. The milk-and-a-local-event example is the counterexample.
  • Treating equal Lamport clocks as proof the events were simultaneous. Equality means the integers did not separate them.
  • Keeping every vector version and never merging. The pain Dynamo wrote down is unbounded versions and a client that has to adjudicate them.
  • Calling TrueTime a logical clock, or quoting one epsilon for commit wait. It is an interval. The wait is however long that interval still covers the timestamp.
  • Electing a leader by whoever has the higher clock. Clocks alone do not fence the old leader. A term does.
  • Using a hybrid stamp as if it were a bound on true time. It follows the oscillator you gave it, including a wrong one.

In the interview

In a new-grad loop, do not open with a clock. Say the primary’s log is the order, or the quorum is the overlap, and move to the product. If they ask about the cart that was updated on both sides of a partition, draw the two vectors, 1, 0 and 0, 1, and say neither dominates. The number they want next is not a skew. It is the cost of refusing the conflict: a commit that waits for a majority, 0.5 ms in one building, tens of milliseconds across a continent, or Spanner’s extra pause on the order of milliseconds of uncertainty with no single epsilon attached.

Skip a derivation of the Lamport proof. Skip a bit diagram of a hybrid clock. You are not being graded on either. Name the one-direction rule, name the converse as false, and stop.

The question that usually follows is commit wait. What are you waiting for? Until TrueTime’s interval is past the timestamp you chose, so the timestamp is definitely in the past, so a transaction that starts later receives a later timestamp. What does it cost? A pause on the order of the uncertainty, which the paper keeps in the milliseconds with GPS and atomic clocks, on top of whatever round trip the replicas already cost you.

Check yourself

Vectors 1, 0 and 0, 1 come back from the two sides of a cart partition. Are the updates ordered?

They are concurrent. Domination needs every component greater than or equal, and the vectors differ. The first component says the milk side is ahead. The second says the bread side is ahead. Neither happened before the other. The clock does not merge the cart. A client that wants both items has to decide that, and a client that keeps the greater replica id has dropped an add rather than discovered an order.

Two events have Lamport clocks 1 and 2, and no message connects them. Did the smaller one happen first?

You cannot tell. If A happened before B then A’s clock is less than B’s. The converse is not a theorem. A process can increment twice with no messages while another increments once. The clocks read 2 and 1, and neither event happened before the other. Sorting by the integer invents an order the system did not observe.

What does commit wait actually wait for, and why is there no epsilon to quote?

TrueTime returns an interval that contains the true time, not a point. Commit wait holds the commit until that interval is past the chosen timestamp, so the timestamp is definitely in the past. That is what makes a transaction that commits before another starts receive the smaller timestamp. The paper treats the uncertainty as milliseconds, kept small with GPS and atomic clocks. The width moves. A single epsilon is a number you would be inventing.

Why can last-writer-wins on wall clocks drop a cart update the shopper still wants?

The winner is the larger oscillator reading, not the later causal update and not the later real-time update. If one replica’s clock is ahead, its write wins even when the other replica never saw it and a human would call the losing write later. You do not need a measured skew to know the rule allows that. A vector clock would have shown the two writes concurrent. The wall clock hid the conflict inside a total order.

A hybrid logical clock stays close to wall time. What failure does that closeness not fix?

Distance from true time. The counter keeps causality when the physical clock stalls, repeats a tick, or steps backward, and messages still move the stamp forward. A wall clock that is simply wrong produces hybrid stamps that are wrong by the same amount. The hybrid clock is not an interval around true time. Commit wait does not apply to it. Comparing two of them across a partition is still comparing two oscillators.

Based on: Lamport clocks; Amazon Dynamo, SOSP 2007, DeCandia and others; Spanner, OSDI 2012, Corbett and others; Designing Data-Intensive Applications, Kleppmann and Riccomini.