Wall Clocks, Monotonic Clocks, and Hybrid Logical Clocks: Why Distributed Time Is Hard

Ask two services what time it is and you will get two different answers. Not a few microseconds apart — sometimes tens of milliseconds, occasionally a full second. Yet we routinely build systems whose correctness depends on timestamps ordering events: conflict resolution in replicated databases, deduplication windows, cache TTLs, distributed tracing. The wall clock quietly betrays all of them. This post walks through why physical time cannot carry causal ordering on its own, what your language runtime already does to protect you, and how hybrid logical clocks combine both layers into a timestamp you can actually reason about.

Your Wall Clock Is a Rumor, Not a Clock

Server clocks are drifting oscillators, so an NTP daemon continuously pulls them back toward a reference. The mechanism of that correction is where the trouble starts. Small offsets are slewed — the daemon speeds the clock up or slows it down by up to 500 parts per million, so time flows slightly fast or slow but never jumps. Offsets beyond a threshold are stepped — the clock jumps to the correct time instantly, discontinuously, with no warning to your process. ntpd steps by default once the offset exceeds roughly 128 milliseconds.

A step can send your clock backward. Any duration you measured with the wall clock across a step can come out negative. Two events on the same machine can appear to happen before an event that preceded them. And it gets stranger: UTC technically includes leap seconds, POSIX time ignores them, and large operators smear the discontinuity across a 24-hour window so no single instant matches atomic time exactly. The takeaway is not that wall clocks are useless — they are wonderful for humans reading logs — but that a wall-clock comparison between events on different machines is a heuristic, not an ordering. NTP synchronizes clocks well enough that the error is usually small. “Usually” is not a correctness argument.

Go Smuggles a Second Clock Into Every time.Time

Since Go 1.9, the value returned by time.Now() carries two readings: the wall-clock time, and a monotonic clock reading captured from a source that never steps backward. The two clocks live in the same struct. Time-telling operations use the wall reading; time-measuring operations use the monotonic one when both operands have it:

start := time.Now()

doWork() // meanwhile, NTP steps the wall clock backward an hour

elapsed := time.Since(start) // still correct: measured on the monotonic clock

This is a genuinely good design — durations survive clock adjustments, and Sub, Before, After, and Equal all prefer the monotonic reading when both values carry one. The trap is that the monotonic reading is deliberately not portable. Serialize a time.Time through JSON, put it in a message, or convert it with Unix(), and the monotonic component is stripped. If your durations span a process boundary — a request timestamp sent from a gateway to a backend, a deadline propagated through a job queue — comparisons silently fall back to the wall clock, and every NTP hazard returns. The time package documentation spells this out, and t.Round(0) strips the monotonic reading explicitly when you want to compare pure wall time.

Monotonic clocks solve duration measurement on one machine. They do nothing for ordering events across machines: each node’s monotonic source is arbitrary and meaningless to anyone else, and dead once the timestamp leaves the process. For distributed ordering you need a different tool.

Hybrid Logical Clocks: Two Layers, One Timestamp

Logical clocks (Lamport’s scheme) order events correctly by counting, but their values have no relation to real time — you cannot debug with them or bound a timeout with them. Physical timestamps read well but cannot order causally. The compromise, described in detail in the technical report on hybrid logical clocks, is to make a timestamp a pair: a physical layer that tracks the wall clock, and a logical counter that breaks ties and absorbs causality. The invariant that makes it work: the logical layer never lets the reading go backward, even when the physical clock does.

The algorithm fits on one screen. On each event, read the physical clock and take the maximum of it, your last reading, and (if merging a remote message) the remote’s reading. If the maximum came from the physical clock, reset the counter. If the maximum came from an earlier reading — meaning the clock stepped backward, or a remote node ran ahead — keep the physical layer frozen at that maximum and increment the counter. Here is a compact Go implementation:

type Timestamp struct {
	Wall    time.Time // physical layer: tracks the wall clock
	Logical uint32    // causality layer: breaks ties, absorbs clock steps
}

func (a Timestamp) Before(b Timestamp) bool {
	if !a.Wall.Equal(b.Wall) {
		return a.Wall.Before(b.Wall)
	}
	return a.Logical < b.Logical
}

type HLCClock struct {
	mu sync.Mutex
	ts Timestamp
}

func NewHLCClock() *HLCClock {
	return &HLCClock{ts: Timestamp{Wall: time.Now()}}
}

// Now advances the clock for a local event.
func (c *HLCClock) Now() Timestamp {
	return c.observe(nil)
}

// Observe merges a remote timestamp when a message is received.
func (c *HLCClock) Observe(remote Timestamp) Timestamp {
	return c.observe(&remote)
}

func (c *HLCClock) observe(remote *Timestamp) Timestamp {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.step(time.Now(), remote)
}

// step is pure so the step-backward behavior is testable
// without patching time.Now.
func (c *HLCClock) step(pt time.Time, remote *Timestamp) Timestamp {
	maxWall := c.ts.Wall
	if remote != nil && remote.Wall.After(maxWall) {
		maxWall = remote.Wall
	}

	if pt.After(maxWall) {
		// Physical clock has caught up: new physical reading,
		// causality counter resets.
		c.ts = Timestamp{Wall: pt}
		return c.ts
	}

	// pt <= maxWall: the wall clock stepped backward, or a remote
	// event ran ahead of us. The logical layer preserves ordering.
	logical := c.ts.Logical
	if remote != nil && remote.Wall.Equal(maxWall) && remote.Logical > logical {
		logical = remote.Logical
	}
	c.ts = Timestamp{Wall: maxWall, Logical: logical + 1}
	return c.ts
}

Three properties fall out of that structure, and each one is the reason a naive design fails:

Monotonicity survives clock steps. When NTP yanks the wall clock backward, step keeps the frozen wall value and increments the counter. The property test is two lines:

func TestBackwardStepDoesNotRegress(t *testing.T) {
	c := NewHLCClock()
	t1 := c.Now()

	// The wall clock jumps backward one hour, as NTP stepping can.
	t2 := c.step(t1.Wall.Add(-time.Hour), nil)

	if !t1.Before(t2) {
		t.Fatalf("reading regressed: %v !< %v", t1, t2)
	}
}

Drift from the wall clock is bounded. The logical layer only runs ahead while the physical clock is behind; the moment pt overtakes maxWall, the counter resets to zero and the timestamp snaps back to physical time. The logical counter is a correction term, not a runaway Lamport count that drifts to absurd values after a busy hour. That boundedness is what makes HLC timestamps usable as ordinary-looking timestamps — you can index them, bucket them, and eyeball them in logs.

Merging remote readings preserves causality. When a message arrives carrying a timestamp ahead of yours, your next reading adopts its physical layer and runs its counter forward, so anything the receiver does afterward orders after everything the sender did before sending. Compare timestamps pairwise across nodes and you get a causally consistent ordering — the guarantee that consistent snapshots and conflict rules need.

Where This Lives in Production

The most prominent deployment is CockroachDB: every write in the system carries an HLC timestamp, and the transaction layer uses those values for ordering, snapshot isolation reads, and conflict detection between replicas. Timestamps that order causally but still look like wall time can drive lease expiration, GC thresholds, and human debugging with the same values.

You do not need a distributed database to want this. The pattern applies anywhere ordering decisions ride on timestamps that cross process boundaries: deduplicating retried webhook deliveries across replicas, ordering audit events from services with unsynchronized clocks, or versioning cache writes in an active-active setup. The fix is the same — stop comparing bare wall-clock readings, and carry a two-layer timestamp with the causality counter attached.

A Practical Checklist

Measure durations locally with monotonic clocks. On Go, time.Since already does this — just never round-trip the value through serialization first. In other runtimes, reach for the monotonic source explicitly (CLOCK_MONOTONIC, std::time::Instant, time.monotonic()).

Never use wall-clock comparison as a causal rule across machines. If correctness depends on “A happened before B,” a physical timestamp alone cannot deliver it. Either route through a coordination point that establishes order, or attach a logical layer.

Timestamp everything that crosses a boundary with enough structure for both jobs. Millisecond wall time for humans, plus a counter and node identity for the machine. The hybrid scheme above is about thirty lines and drops into any protocol as an opaque value.

Distributed time is not a problem NTP solves for you; it is a problem NTP hides well enough to become a production incident two years in. Thirty lines of hybrid clock make it boring instead. Boring is the goal.

Leave a Reply

Your email address will not be published. Required fields are marked *