Working with Time and Ordering

1. Understanding Physical Clocks

SourceAccuracyNotes
NTP1-50 ms over WANStratum hierarchy; can jump backward
PTP (IEEE 1588)sub-µs LANHardware timestamping
GPS / AtomicnsRequired for Spanner TrueTime
System.currentTimeMillis()Wall clock; NOT monotonicUse for display only
System.nanoTime() / CLOCK_MONOTONICMonotonicUse for elapsed time
Warning: Never use wall-clock time to enforce ordering or correctness — clocks drift, jump, and lie.

2. Understanding Logical Clocks (Lamport timestamps)

RuleAction
Local eventL = L + 1
Send msgL = L + 1; attach L
Recv msg(L_msg)L = max(L, L_msg) + 1
Propertya → b ⟹ L(a) < L(b) (one direction only)

Example: Lamport clock

public class LamportClock {
    private long counter = 0;

    public synchronized long tick() { return ++counter; }

    public synchronized long onReceive(long msgTs) {
        counter = Math.max(counter, msgTs) + 1;
        return counter;
    }
}

3. Understanding Vector Clocks

AspectDetail
StructureVC = [c₁, c₂, …, cₙ] one entry per node
CompareVC₁ < VC₂ iff ∀i VC₁[i] ≤ VC₂[i] and ∃j VC₁[j] < VC₂[j]
ConcurrentNeither VC₁ < VC₂ nor VC₂ < VC₁
CostO(n) per message
Used ByDynamo, Riak, Voldemort

4. Understanding Hybrid Logical Clocks (HLC)

PropertyDetail
CombinesPhysical (NTP) + logical counter
Format(pt, l) — wall-clock + logical tick
BoundDrift-bounded, monotonic
Used ByCockroachDB, YugabyteDB, MongoDB

5. Implementing Happened-Before Relationship

RuleDefinition
Same processa before b in program order ⟹ a → b
Send/receivesend(m) → recv(m)
Transitivea → b ∧ b → c ⟹ a → c
Concurrent¬(a → b) ∧ ¬(b → a) ⟹ a ∥ b

6. Handling Clock Skew and Drift

IssueMitigation
SkewPeriodic NTP sync; slewing (gradual adjust)
DriftRate-adjusted clocks (chronyd)
Backward jumpsUse CLOCK_MONOTONIC
Leap secondsSmear (Google) or step
Bounded uncertaintySpanner TrueTime returns interval [earliest, latest]

7. Using Time for Event Ordering

ApproachOrder Strength
Wall clockApproximate; unsafe for correctness
LamportTotal order extending happened-before
Vector clockDetects concurrency
HLCCausally consistent + close to wall time
TrueTimeExternal consistency (Spanner)

8. Implementing Causal Ordering

StepAction
1Tag each message with sender's vector clock
2Receiver buffers msg until VC dependencies satisfied
3Deliver in causal order; merge VCs

9. Understanding Total vs Partial Ordering

TypePropertyMechanism
Partial OrderSome events comparable, others concurrentVector clocks
Total OrderEvery pair comparableLamport (with tie-break by node id), consensus log
Total Order BroadcastAll nodes deliver msgs in same orderAtomic broadcast (Paxos/Raft log)

10. Working with Timestamps in Distributed Transactions

ApproachSystem
TrueTime (commit wait)Spanner — wait out uncertainty before commit
HLCCockroachDB, YugabyteDB
Centralized timestamp oracleTiDB (TSO), Percolator
MVCC snapshotPostgreSQL, MySQL InnoDB