← Back to Home

🕰️ Clocks and Ordering in Distributed Systems

How wrong a real clock is, why last-writer-wins silently drops writes, Lamport, vector and hybrid logical clocks on a space-time diagram, TrueTime, and fencing tokens against paused lease holders.

"Which happened first?" sounds like the easiest question in computing. On one machine it is. Across machines, each with its own clock drifting at its own rate, it's one of the hardest, and the wrong answer loses data quietly: a database keeps an older write instead of a newer one, a trace shows a reply before its request, a lock is held by two processes at once.

This article measures how wrong a real clock is, shows what "last writer wins" does under clock skew, and builds up the logical clocks distributed systems use instead: Lamport clocks, vector clocks and hybrid logical clocks. It ends with leases and fencing tokens, run against PostgreSQL, because pausing processes break locks in ways clocks can't fix.

It continues from CAP and consistency models and Raft, and explains the clock-related warnings in Replication and Sharding.

Two Clocks in Every Computer

Every operating system gives you two kinds of clock, for two different jobs:

Wall clock (CLOCK_REALTIME) Monotonic clock (CLOCK_MONOTONIC)
Answers "What time is it?" "How much time has passed?"
Can jump Yes: NTP corrections, manual changes, VM restores Never goes backwards
Comparable across machines Roughly, if synchronised No: it counts from an arbitrary point, such as boot
Python / Java / Go time.time() / System.currentTimeMillis() / time.Now() wall part time.monotonic() / System.nanoTime() / time.Now() monotonic part

The first rule of clocks: measure durations with the monotonic clock. Timeouts, latencies, rate limiters and lease expiry computed from the wall clock break when the wall clock is corrected: a step backwards makes an elapsed time negative, a step forward fires every timeout at once. Go has stored a monotonic reading inside time.Time since 1.9 for exactly this reason.

How Wrong Is a Clock?

A computer keeps time by counting the oscillations of a quartz crystal, and no two crystals run at exactly the stated frequency. Temperature makes it worse. NTP compares the local clock with time servers and corrects it, mostly by gently speeding up or slowing down ("slewing") rather than jumping.

Linux exposes its correction state through the adjtimex system call, which anyone can read. On the machine used for this article (a WSL2 virtual machine):

"""Read the kernel's clock discipline state with adjtimex(2) in read-only mode, and measure clock APIs."""
import ctypes, time

class Timeval(ctypes.Structure):
    _fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long)]

class Timex(ctypes.Structure):
    _fields_ = [("modes", ctypes.c_uint), ("offset", ctypes.c_long), ("freq", ctypes.c_long), ("maxerror", ctypes.c_long),
                ("esterror", ctypes.c_long), ("status", ctypes.c_int), ("constant", ctypes.c_long), ("precision", ctypes.c_long),
                ("tolerance", ctypes.c_long), ("time", Timeval), ("tick", ctypes.c_long), ("ppsfreq", ctypes.c_long),
                ("jitter", ctypes.c_long), ("shift", ctypes.c_int), ("stabil", ctypes.c_long), ("jitcnt", ctypes.c_long),
                ("calcnt", ctypes.c_long), ("errcnt", ctypes.c_long), ("stbcnt", ctypes.c_long), ("tai", ctypes.c_int),
                ("_pad", ctypes.c_int * 11)]

libc = ctypes.CDLL("libc.so.6", use_errno=True)
tx = Timex(); state = libc.adjtimex(ctypes.byref(tx))
clock state            : TIME_OK (synchronised)
frequency correction   : +29.828 ppm  (the oscillator's measured drift, corrected by the kernel)
  = +2577.1 ms per day if uncorrected
estimated error        : 84648 µs
maximum error          : 123584 µs
STA_UNSYNC flag set    : False
CLOCK_REALTIME  : resolution 1 ns, one read from Python ≈ 108 ns
CLOCK_MONOTONIC : resolution 1 ns, one read from Python ≈ 108 ns
2,000,000 consecutive time.time_ns() reads: 0 repeats, 0 went backwards

Typical accuracy in practice:

Setup Typical offset from true time
No synchronisation Seconds per day of drift, growing without limit
NTP over the internet Several milliseconds, worse with asymmetric routes
NTP inside a data centre Around a millisecond
PTP with hardware timestamping; cloud services such as AWS Time Sync on supported instances Microseconds
Spanner's TrueTime (GPS and atomic clocks in every data centre) Bounded uncertainty, typically a few milliseconds

Then there are the events that break synchronisation outright: a VM paused for live migration and resumed seconds later, a misconfigured NTP server, a leap second (most clouds now "smear" it across a day instead of repeating a second; leap seconds are due to be abolished by 2035), and a process paused for a long garbage collection, which doesn't change the clock but changes what "now" means to the paused code.

Last Writer Wins Loses Writes

Many replicated databases resolve conflicting writes with last-writer-wins (LWW): each write carries a timestamp, and the highest one wins. Cassandra does this per column; so do many multi-leader setups and "updated_at" conflict rules.

The problem: "highest timestamp" means "latest according to whichever clock stamped it". Two replicas each accept a write to the same key. Replica A's write comes first in real time, then replica B's, a short gap later. If B's clock is behind A's by more than the gap, B's write gets the smaller timestamp and LWW keeps A's older value. 10,000 trials per cell, with ±0.5 ms of jitter:

                       gap between the two writes:
replica B's clock     |    1 ms |   10 ms |  100 ms |     1 s
behind A by    0.0 ms |    0.0% |    0.0% |    0.0% |    0.0%
behind A by    0.5 ms |   12.6% |    0.0% |    0.0% |    0.0%
behind A by      5 ms |  100.0% |    0.0% |    0.0% |    0.0%
behind A by     50 ms |  100.0% |  100.0% |    0.0% |    0.0%
behind A by    500 ms |  100.0% |  100.0% |  100.0% |    0.0%

The rule is simple: when the skew is larger than the time between two conflicting writes, LWW keeps the wrong one, every time. And it does so silently. Both writes were acknowledged; one simply vanishes. A 50 ms skew is unremarkable for NTP over the internet, and two updates 10 ms apart is an ordinary race.

LWW is acceptable when losing a concurrent update doesn't matter (a "last seen" timestamp, a cache entry) or when each key has a single writer. For anything else, you need to know whether two writes were really ordered or genuinely concurrent, and that's what logical clocks are for.

Happened-Before

Leslie Lamport's 1978 paper "Time, Clocks, and the Ordering of Events in a Distributed System" replaced the question "which happened first in real time?", which can't be answered reliably, with one that can: could one event have influenced the other? Event a happened before event b (written a → b) if:

  1. a and b are on the same process and a came first, or
  2. a is sending a message and b is receiving that message, or
  3. there's a chain of such steps from a to b.

If neither a → b nor b → a, the events are concurrent: neither could have known about the other, whatever their wall-clock times say. This is the ordering that matters for correctness: a reply must come after its request; an update based on a read must come after that read.

Lamport Clocks

A Lamport clock is a counter on each process:

That guarantees: if a → b, then L(a) < L(b). A receive is always stamped later than its send, whatever the physical clocks say.

The reverse doesn't hold. L(a) < L(b) doesn't mean a happened before b; they might be concurrent. Lamport clocks give a total order consistent with causality (break ties by process ID), which is enough for things like a consistent order of operations in a replicated log, but they can't tell you that two writes conflicted.

Vector Clocks

A vector clock keeps one counter per process. Each process increments its own entry on every event, and on receive takes the element-wise maximum with the incoming vector before incrementing. Then:

That's what Amazon's Dynamo used for shopping carts. Here's the idea in a few lines: a phone and a laptop both read the cart, then both write, each with the version they read:

def merge(a, b): return {k: max(a.get(k, 0), b.get(k, 0)) for k in a.keys() | b.keys()}
def compare(a, b):
    ge = all(a.get(k, 0) >= b.get(k, 0) for k in a.keys() | b.keys()); le = all(a.get(k, 0) <= b.get(k, 0) for k in a.keys() | b.keys())
    return "equal" if ge and le else "after" if ge else "before" if le else "CONCURRENT"
start: [({'phone': 1}, ['milk'])]
phone adds eggs (read context {'phone': 1} ) -> [({'phone': 2}, ['milk', 'eggs'])]
laptop adds bread with the SAME old context -> [({'phone': 2}, ['milk', 'eggs']), ({'phone': 1, 'laptop': 1}, ['milk', 'bread'])]
compare {'phone': 2} vs {'phone': 1, 'laptop': 1} -> CONCURRENT
next read sees siblings, merges them -> [({'phone': 3, 'laptop': 1}, ['bread', 'eggs', 'milk'])]

The laptop's write didn't overwrite the phone's, and LWW would have dropped one of them. The store recognised the writes as concurrent and kept both as siblings. The next reader merged them (here by union), and the merged write's vector covers both, so the siblings are replaced. Nothing was lost.

The costs: vectors grow with the number of writers (systems prune them or use per-replica rather than per-client entries; Riak's "dotted version vectors" refine this), and the application must know how to merge siblings. A union is easy for a cart, but it's also why deleted items famously reappeared in Dynamo's carts: a deletion merged with a concurrent version that still had the item. CRDTs (#0029) are data types designed so that merging is always well defined.

See It on a Space-Time Diagram

Three processes, each with its own clock offset, exchange three messages. Switch between timestamp types and move the clock offsets; click an event to see which events are in its causal past, its causal future, or concurrent with it:

With the default offsets, P2's clock is 6 ms slow, so message m1 is "received" before it was "sent" by physical timestamps. Lamport and hybrid timestamps never do that, at any offset. Click event c: it's concurrent with a, b, f and i (nothing connects them), yet in the causal past of everything P2 did afterwards and everything that later heard from P2.

Hybrid Logical Clocks

Vector clocks are exact but big; Lamport clocks are small but unrelated to real time, so you can't ask "what was the state at 10:15?". A hybrid logical clock (HLC; Kulkarni and others, 2014) combines a physical timestamp with a small logical counter:

The result is never smaller than any timestamp it has seen, so it respects causality like a Lamport clock, and it stays within the clock skew of real time. A simulation of 40,000 messages between three services whose clocks are at −3 ms, 0 and +2 ms:

40,000 messages between three services with clocks at -3 ms, 0 ms and +2 ms
  physical  timestamps: receive stamped at or before send in 20,000 messages (50.0%)
  lamport   timestamps: receive stamped at or before send in 0 messages (0.0%)
  hlc       timestamps: receive stamped at or before send in 0 messages (0.0%)
  HLC physical part stayed within 2.2 ms of true time

With physical timestamps, every message sent into the slower clock (half of them in this call pattern) appears to arrive before it was sent. This is the same effect that makes child spans start before their parent in distributed traces when hosts' clocks disagree (#0033). Lamport and HLC timestamps had zero violations, and the HLC never strayed further from real time than the clock skew itself.

CockroachDB, YugabyteDB and MongoDB use hybrid logical clocks to timestamp transactions: close enough to real time for "read as of 10:15", and safe for causality.

When You Need Real Time: Uncertainty and Commit Wait

Causality isn't always enough. External consistency (strict serialisability) means that if transaction T1 commits before T2 starts, in real time, then T2 must see T1, even when no message connected them (one person commits, then phones a colleague who reads). Logical clocks can't capture a phone call.

Google's Spanner handles this with TrueTime: instead of a single "now", the clock API returns an interval [earliest, latest] guaranteed to contain the true time, backed by GPS receivers and atomic clocks in each data centre. The interval is usually a few milliseconds wide. When a transaction commits with timestamp s, Spanner waits until earliest > s before reporting the commit. After that wait, any transaction that starts anywhere will get a later timestamp. The cost is a few milliseconds per commit, and it's only affordable because the uncertainty is small and bounded.

CockroachDB, without special hardware, takes another route: it assumes clock offsets stay below a configured maximum (500 ms by default) and treats values written within that window as uncertain. A read that finds one may restart at a higher timestamp. Nodes that find their clock too far from the others' shut themselves down rather than risk inconsistency. AWS's ClockBound and Time Sync Service now offer TrueTime-style error bounds as well.

The lesson for everyone else: if correctness depends on real-time order across machines, you need a known bound on clock error, not just synchronised clocks, and a design that waits out the uncertainty.

Leases, Pauses and Fencing Tokens

Leases are locks with an expiry time: "you're the leader (or the only writer) for the next 10 seconds". They're everywhere: leader election, distributed locks in Redis, ZooKeeper or etcd, Kubernetes controller leader election. The expiry stops a crashed holder from blocking everyone forever.

But a lease holder can't reliably know that its lease is still valid. It checks the time, sees 2 seconds left, starts writing, and gets paused: a garbage-collection pause, a VM migration, a process swapped out under memory pressure. It wakes 1.5 seconds later and finishes the write, unaware that its lease expired and someone else now holds it. Checking the clock again doesn't help; the pause can happen between the check and the write.

Here it is with a lease table in PostgreSQL and a 1-second lease:

WITHOUT fencing tokens:
   0.01 s  client1 gets the lease, token 33
   0.01 s  client1 pauses (GC, VM migration, swapped out) for 1.5 s; its 1 s lease expires
   1.05 s  client2 gets the lease after it expires, token 34
   1.05 s  client2 writes with token 34: ACCEPTED
   1.52 s  client1 wakes, still thinks it holds the lease, writes with token 33: ACCEPTED
  final report: ('stale data from client1', 'client1')

Both clients held the lease, as far as each knew, and the stale write won. The fix doesn't involve clocks at all. Every time the lease changes hands, the lock service hands out a number that only increases: a fencing token. The storage remembers the highest token it has accepted and rejects writes carrying an older one:

cur.execute("UPDATE report SET body = %s, writer = %s, last_token = %s WHERE id = 1 AND last_token < %s", (body, who, token, token))
WITH fencing tokens:
   0.01 s  client1 gets the lease, token 33
   0.01 s  client1 pauses (GC, VM migration, swapped out) for 1.5 s; its 1 s lease expires
   1.04 s  client2 gets the lease after it expires, token 34
   1.05 s  client2 writes with token 34: ACCEPTED
   1.51 s  client1 wakes, still thinks it holds the lease, writes with token 33: REJECTED
  final report: ('fresh data from client2', 'client2')

The storage, not the lock holder, enforces the order. ZooKeeper's zxid, etcd's revision numbers and the Raft term (#0030) all work as fencing tokens. A lock service that doesn't give you one (a plain Redis SET NX lock, for example) is fine for efficiency, so that two workers rarely do the same job, but not for correctness, where two holders at once would corrupt data. For that, the resource itself must check a token or a version, which is the same conditional update from #0038.

Practical Rules

Key Takeaways

Copied to clipboard!