In this lesson, you will learn how Hybrid Logical Clocks (HLCs) bridge the gap between physical wall-clock time and logical ordering to achieve reliable causality in distributed databases.
The Problem: When Clocks Deceive
As we’ve discussed in our look at Lamport Timestamps, logical clocks are excellent for tracking causal order, but they don't give us a human-readable sense of "when" an event occurred. Conversely, physical clocks (NTP) are easy to read but suffer from drift, which can break causal relationships in a distributed system. If Server A has a clock slightly ahead of Server B, a causal event at Server B might receive a physical timestamp that looks "earlier" than an event at Server A, violating causality.
How HLCs Work
A Hybrid Logical Clock combines physical time (pt) with a logical counter (l) in a single timestamp: (pt, l).
The rules for maintaining the clock are simple yet robust:
- Update on Event: When an event occurs, if the current physical time is greater than the stored
pt, updateptto the current time and resetlto 0. If they are equal, incrementl. - Synchronize on Receipt: When a node receives a message with timestamp
(m.pt, m.l), it updates its own clock to themaxof its current time and the received time. This ensures that the local clock "catches up" to the future, effectively capturing causality across nodes.
-- Conceptual HLC update logic
-- Current state: (local_pt, local_l)
-- Incoming event: (msg_pt, msg_l)
new_pt = max(local_pt, msg_pt)
if (new_pt == local_pt && new_pt == msg_pt) then
new_l = max(local_l, msg_l) + 1
else if (new_pt == local_pt) then
new_l = local_l + 1
else if (new_pt == msg_pt) then
new_l = msg_l + 1
else
new_l = 0
Why it Matters
By favoring the physical clock when possible, HLCs ensure that timestamps remain close to real-world time (useful for debugging and TTLs). By utilizing the logical counter, they guarantee that if event A happens before event B, the HLC of A will always be strictly less than the HLC of B, even if the physical clocks are out of sync.
Key Takeaway: Hybrid Logical Clocks provide a monotonically increasing, causal-preserving timestamp that approximates physical time while guaranteeing strict ordering across distributed nodes.