Clocks and Time in Distributed Systems

Why the clocks on different machines disagree, which clock to use for what, how last-write-wins silently loses data, and how Spanner and hybrid logical clocks work with uncertain time.

Overview

Every machine has a clock, and none of them agree exactly. On one machine that rarely matters. Across many machines, code that compares timestamps from different nodes can put events in the wrong order and quietly throw data away.

Two kinds of clock

A computer offers two different clocks, and they answer different questions. The Linux clock_gettime manual describes both.

The time-of-day clock answers 'what time is it?'. On Linux it is CLOCK_REALTIME, and its value is seconds since 1970-01-01 UTC. It can jump, when someone sets it by hand or when NTP sets it. You can compare its readings across machines only roughly, within the sync error. Use it for showing dates to people.

The monotonic clock answers 'how much time has passed?'. On Linux it is CLOCK_MONOTONIC, and its value is seconds since some unspecified point, on Linux since boot. It does not jump, though NTP may slow it or speed it slightly. You can never compare its readings across machines, because each machine counts from its own start. Use it for timeouts, durations and rate limits.

A time-of-day clock can jump backward, so an elapsed time measured with it can come out negative. Measure durations with the monotonic clock.

Key concepts

  • Time-of-day clock
  • Monotonic clock
  • Clock skew
  • NTP
  • Last write wins (LWW)
  • TrueTime
  • Commit wait
  • Hybrid logical clock (HLC)

Interview questions

  • Why is last write wins with wall-clock timestamps dangerous?
  • Which clock should you use to measure a timeout, and why?
  • How does Spanner use TrueTime to order transactions?
  • What is a hybrid logical clock, and what does it still need?
  • Why is a lease with an expiry time risky?

Sign up free to read the full topic

More DDIA topics

Start free on Cariara · Coding problems · System design studio