Summary#
Every machine has its own clock, and no two clocks agree. Quartz crystals drift by tens of microseconds per second. Synchronisation over a network with NTP (Network Time Protocol) usually keeps servers within a few milliseconds of true time, sometimes much worse, and clocks can jump forwards or backwards when they are corrected. Leap seconds add a 61st second to some minutes, and most large companies hide them by smearing, running their clocks very slightly slow for a day. So a wall-clock timestamp from one machine cannot be compared safely with a timestamp from another. Using timestamps to decide which write wins (last-writer-wins, or LWW) silently throws away data whenever clocks are skewed. What we usually need is not the exact time but the order of events, and specifically causality: did event A possibly influence event B? Leslie Lamport's happens-before relation defines this. Lamport clocks are single counters that respect causality but cannot detect concurrency. Vector clocks keep one counter per node and can tell exactly whether two events are ordered or concurrent, at a cost that grows with the number of nodes. Hybrid logical clocks (HLC) combine a physical timestamp with a logical counter, so timestamps stay close to real time and still respect causality. Databases such as CockroachDB and YugabyteDB use them. Google's TrueTime goes further: it gives an explicit uncertainty interval, backed by GPS and atomic clocks, and Spanner waits out that uncertainty to give globally ordered transactions. The practical rule: use monotonic clocks for durations, sequence numbers or logical clocks for ordering, and wall-clock time only for display and rough expiry.
Why It Exists#
On one machine, ordering is free. There is one clock, one memory, and usually one log. If a program writes A and then writes B, every later reader sees A before B. Timestamps from that machine can be compared directly, because they come from the same counter.
Spread the work over many machines and this disappears.
- Each machine has its own clock, and the clocks disagree. Two servers in the same rack can easily differ by a few milliseconds, and in a badly configured fleet, by seconds or minutes. A database row stamped
10:00:00.120on server A may really have been written after a row stamped10:00:00.150on server B. - Clocks jump. When NTP decides a clock is too far off, it may step it, so time on one machine can suddenly move backwards. A duration computed as "end time minus start time" can come out negative.
- Messages take variable time. A message sent at 10:00:00.000 may arrive after 1 ms or after 2 seconds. The receiver cannot tell exactly when it was sent.
- There is no global "now". Even in principle, two events far apart cannot be ordered by observation alone, unless one could have influenced the other.
Yet systems constantly need answers that depend on order. Which of two conflicting writes to a user's profile should win? Did the "unfriend" happen before the photo was posted? Is this replica's data newer than that one? Is this lock still valid, or did it expire? In a chat app, should message 41 be shown above or below message 42? In a ride-sharing app, is a driver's last location update fresh enough to use for matching, or is the driver offline?
This page explains what clocks can and cannot tell you, and the tools that distributed systems use instead: logical clocks that capture causality, hybrid clocks that combine logical order with physical time, and clocks with explicit error bounds.
How It Works#
There are two fundamentally different notions of time in a distributed system:
- Physical time: what a clock on the wall says, ideally Coordinated Universal Time (UTC). Useful for humans, for expiry ("delete after 30 days"), for rough freshness ("last seen 5 minutes ago"), and for correlating logs. Every machine estimates it independently, with some error.
- Logical time: a counter that captures the order of events, specifically which events could have influenced which, without claiming to know the real time at which anything happened.
Most production designs use both: physical time where approximate answers are fine, and logical ordering, sequence numbers, or consensus logs where correctness depends on order.
Physical clocks and NTP skew#
A computer keeps time with a quartz crystal oscillator, a small crystal that vibrates at a nominal frequency, commonly 32,768 Hz for real-time clock chips, while the CPU's timestamp counters run much faster. The operating system counts oscillations to advance its clock. No two crystals vibrate at exactly the same rate, and the rate changes with temperature, age and supply voltage. The difference between a clock's rate and true time is called drift, measured in parts per million (ppm). Ordinary server crystals drift by roughly 10 to 100 ppm. At 50 ppm, a clock gains or loses 50 microseconds every second, which is 4.3 seconds per day, or about two minutes per month. Left alone, a fleet of servers would drift apart by seconds within days.
The difference between two clocks at a given moment is called skew (or offset, when measured against a reference). To keep skew small, machines periodically synchronise with a more accurate source. The standard protocol is NTP, the Network Time Protocol, designed by David Mills in the 1980s. Version 4 is specified in RFC 5905 (2010). NTP servers are arranged in strata:
- Stratum 0: reference clocks, such as GPS receivers, atomic clocks and radio clocks. They are not on the network themselves.
- Stratum 1: servers directly attached to a stratum 0 source.
- Stratum 2: servers that synchronise with stratum 1 servers, and so on, down to stratum 15.
A typical company runs a few internal time servers, synchronised with stratum 1 sources or cloud time services, and every other machine synchronises with those.
How NTP measures the offset. The client records four timestamps: when it sent the request (t1, by its clock), when the server received it (t2, by the server's clock), when the server sent the reply (t3) and when the client received it (t4). The round-trip delay is the total time minus the server's processing time: delay = (t4 - t1) - (t3 - t2). Assuming the outbound and return trips take equal time, the client's offset from the server is offset = ((t2 - t1) + (t3 - t4)) / 2.
A worked example. The client sends at t1 = 100.000 s by its clock. The server receives at t2 = 100.020 s and replies at t3 = 100.021 s by its clock. The client receives at t4 = 100.011 s. The delay is (100.011 - 100.000) - (100.021 - 100.020) = 0.010 s, so 10 ms round trip. The offset is ((0.020) + (100.021 - 100.011)) / 2 = (0.020 + 0.010) / 2 = 0.015 s. The client's clock is 15 ms behind the server.
The error is bounded by half the round trip. The equal-paths assumption is the weak point. If the outbound trip took 9 ms and the return took 1 ms, the true offset differs from the estimate. The worst-case error is half the round-trip delay. Over a data centre network with sub-millisecond round trips, NTP can keep clocks within tens to hundreds of microseconds of each other. Over the public internet, with round trips of 20 to 100 ms and asymmetric routes, a few milliseconds to tens of milliseconds is more typical. NTP improves on single measurements by querying several servers, filtering samples with low delay (which have less room for asymmetry), and discarding servers that disagree with the majority.
Physical clocks, in depth#
Correcting a clock: slewing versus stepping. Once NTP knows the offset, it has two choices. It can slew the clock, making it run slightly fast or slow until the offset disappears. The classic ntpd daemon slews at up to 500 ppm, so correcting a 100 ms offset takes at least 200 seconds. Slewing keeps time monotonic, which is good for software. Or it can step the clock, jumping straight to the right time. ntpd's default is to step when the offset exceeds 128 ms. Stepping corrects large errors at once, but time can move backwards, and anything that compared two wall-clock readings across the step sees nonsense. Most systems step only at boot, before applications start, and slew afterwards. chrony, the default on many modern Linux distributions, converges faster than ntpd and handles intermittent connectivity and virtual machines better.
Time-of-day clocks versus monotonic clocks. Operating systems expose two kinds of clock, and confusing them is one of the most common time bugs.
- A time-of-day clock, also called a wall clock or real-time clock, returns the current date and time, for example as milliseconds since the Unix epoch (1 January 1970, UTC). On Linux it is
CLOCK_REALTIME; in Java,System.currentTimeMillis(); in JavaScript,Date.now(). It can jump backwards or forwards when NTP steps it, when an administrator changes it, or around leap seconds. - A monotonic clock only moves forwards, at a rate NTP may adjust slightly, but never jumps. Its absolute value is meaningless (often the time since boot), but the difference between two readings on the same machine is a reliable elapsed duration. On Linux it is
CLOCK_MONOTONIC; in Java,System.nanoTime(); in JavaScript,performance.now().
The rule: measure durations, timeouts and rate limits with the monotonic clock; use the time-of-day clock only to record when something happened, for humans and for coarse expiry. Monotonic readings from two different machines cannot be compared at all.
Better than NTP. When milliseconds are not enough:
- PTP, the Precision Time Protocol (IEEE 1588), uses hardware timestamping in network cards and switches, so the moment a packet leaves or arrives is recorded by the hardware rather than by software, removing most variable delay. With PTP-aware switches, clocks can agree within well under a microsecond. Financial exchanges and telecom networks use it, and Meta has written publicly about deploying PTP in its data centres.
- Cloud time services. AWS offers the Amazon Time Sync Service at the link-local address 169.254.169.123, backed by satellite-synchronised and atomic reference clocks in each region, and on supported instance types advertises microsecond-level accuracy. AWS also open-sourced ClockBound, a daemon that reports not just the time but an error bound around it, an idea borrowed from TrueTime. Google Cloud's metadata server provides NTP with leap-second smearing.
- GPS receivers in each data centre provide stratum 0 time directly, with typical accuracy better than a microsecond, though antennas, cables and receivers can fail, and GPS signals can be jammed or spoofed. This is why Google's TrueTime combines GPS with atomic clocks, which fail differently.
How clocks go wrong in practice. Drift and network asymmetry are the gentle cases. The ones that cause outages:
- Unsynchronised machines. UDP port 123 is blocked by a firewall, the NTP daemon is not running, or a container image has no time configuration. The clock drifts silently for weeks.
- Bad upstream servers. A misconfigured or faulty time server can tell a whole fleet that it is a different year. NTP's majority voting across several servers defends against one bad source, but not if all machines use the same single server.
- Virtual machine pauses. A VM can be paused for live migration or by an overloaded hypervisor. When it resumes, its clock is behind, and it either jumps or slews to catch up. A process inside the VM may not notice that seconds passed.
- Process pauses. A garbage-collection pause of several seconds is not a clock error, but it has the same effect on any logic like "I checked the time, and my lease is still valid, so now I will write". By the time the write happens, the check is stale. See Distributed Locks.
- Device clocks. Phones, laptops and IoT devices have clocks controlled by their users. A phone's clock can be wrong by hours, and users deliberately change it, for example to cheat in games with time-based rewards.
Mobile and client timestamps. That last point shapes many designs. A fitness tracker recording a run collects a GPS point every few seconds and stamps each one with the device's clock. Within one recording session the device clock is fine for computing pace and ordering points, since all the points come from the same clock, and the app can use the phone's monotonic clock for elapsed time. But the server should not trust the device's wall clock as the absolute truth: it records its own receive time as well, and uses that for anything that compares data from different devices, such as leaderboards, fraud checks and "activity started at" displays that must agree with friends' devices. When a device records offline and uploads later, the server keeps both timestamps, and the difference between them reveals both the upload delay and a badly set clock.
Freshness checks use one clock. A ride-sharing service that keeps each driver's latest position in an in-memory geospatial index, for example Redis with GEOADD, which overwrites the previous position of the same driver ID, also needs to remove drivers who went offline. A clean way is a companion sorted set where each driver's score is the server's time of the last update, and a periodic job that removes drivers whose score is older than a threshold, such as 30 seconds, from both sets. Using the server's clock, not the phone's, means all comparisons happen on one clock, with no skew between the timestamp and the "now" it is compared against. The threshold of 30 seconds, against updates every few seconds, gives plenty of margin for small skew between the application servers that write the scores and the one that runs the cleanup.
Expiry inside a data store. Time-to-live features rely on the store's own clock. Redis, for example, stores a key's expiry as an absolute Unix time. If the server's clock jumps forward, keys expire early. If it jumps back, they live too long. That is usually acceptable for caches and short locks, but it is one more reason not to treat a TTL as a safety mechanism. An in-memory timer in an application process is worse: if the process crashes, the timer is lost, and whatever it was meant to release stays locked forever. A ride dispatch design that marks a driver as "request outstanding" in the database and relies on an in-process 10-second timer to clear it will leave drivers stuck when that service restarts. Storing the expiry in shared storage, such as a Redis key with a 10-second TTL, survives the crash. The Distributed Locks page covers how to make such locks safe.
Why wall-clock timestamps are dangerous#
The most damaging misuse of clocks is deciding which write wins by comparing timestamps from different machines. The strategy is called last-writer-wins (LWW): every write carries a timestamp, and when two replicas hold different values for the same key, the value with the larger timestamp is kept and the other is discarded. It is simple, needs no coordination, and always converges: every replica eventually keeps the same value. Apache Cassandra resolves conflicting cell values this way, and many caches, sync engines and home-grown replication schemes do too.
The problem is that "larger timestamp" means "later" only if the clocks agree. When they do not, LWW silently throws away the write that really happened last.
Walk through it. Server A's clock runs 100 ms fast. At true time 12:00:00.000, A writes "shipped" and stamps it 12:00:00.100. Fifty milliseconds later, the customer cancels, and server B, whose clock is correct, writes "cancelled" with timestamp 12:00:00.050. The cancellation really happened later, but its timestamp is smaller, so every replica keeps "shipped". Both writes were acknowledged to their clients. No error is reported anywhere. The order ships.
A skew of 100 ms is not exotic. It is a mildly misbehaving NTP setup. Any two writes to the same key closer together than the skew between their servers can be reordered, and with thousands of writes per second, that happens constantly.
What makes LWW especially dangerous:
- The loss is silent. No conflict is reported. The losing write simply disappears, and the client was told it succeeded. Nothing in the logs says data was lost.
- Future timestamps poison a key. If one server's clock runs an hour fast, every write it makes wins over every correct write for the next hour. In Cassandra, a delete is also a timestamped write (a tombstone), so a delete from a fast clock can make a key impossible to write again until real time catches up, and a delete from a slow clock may be ignored, resurrecting data the user deleted.
- Concurrent writes are also lost. Even with perfect clocks, LWW keeps one of two concurrent writes and discards the other. If two users add different items to the same shopping cart at the same moment, one item vanishes. Perfect clocks only make the choice of loser fair, not the loss avoidable.
Why wall-clock timestamps are dangerous, in depth#
When LWW is acceptable. LWW is fine when losing one of two near-simultaneous writes does not matter, and writes to a key are usually far apart compared with clock skew. Examples: a user's "last seen" time, a cached rendering, the latest sensor reading, a driver's most recent location, or immutable data written once under a unique key, where there is never a conflict. Cassandra's own guidance is effectively this: design tables so that the same cell is rarely written concurrently, for example by appending new rows with unique keys rather than updating one row in place.
Safer alternatives, in rough order of preference:
- Avoid concurrent updates to one value. Model changes as new immutable records (append an event, insert a row with a unique ID) and compute the current state from them. Conflicts cannot occur if nothing is overwritten.
- Conditional writes. Read a version number with the data, and write with "only if the version is still 7". If someone else wrote first, the write fails, and the application re-reads and retries. This is optimistic concurrency control, and it works on a single primary database or any store that offers compare-and-set (DynamoDB condition expressions, etcd transactions, Redis
WATCHor a Lua script, SQLUPDATE ... WHERE version = 7). See Concurrency Control and Locking. - Single owner per key. Route all writes for one key through one leader, which applies them in the order it receives them, and stamps each with a sequence number. Kafka partitions, a primary database, or a consensus group all work this way. Order is then a property of the log, not of clocks.
- Detect concurrency and merge. Use version vectors (described below) to detect that two writes were concurrent, keep both versions (called siblings), and merge them with application logic, or use data types that merge automatically, called CRDTs. See Collaborative Editing and CRDTs.
- Hybrid logical clocks or TrueTime when you need timestamps that both respect causality and stay close to real time.
Order derived replicas by log position, not by time. A common case is a search index or cache kept in sync with a primary database through change data capture. A dating app, for instance, might keep profiles in PostgreSQL and mirror them into Elasticsearch for geospatial and preference queries, applying changes from the database's write-ahead log. If two updates to one profile are processed by different workers, or a retry delivers an older change after a newer one, applying them by arrival order can overwrite new data with old. The fix is to use the source database's log position, such as the PostgreSQL log sequence number (LSN) or MySQL binlog position, as the version of each document. Elasticsearch supports this directly with external versioning: an index request with version_type=external is accepted only if its version is greater than the stored one, so a late, older change is rejected. The order comes from the single primary's log, which is authoritative, rather than from timestamps on the workers. See Change Data Capture.
Durations, timeouts and ordering within one process. Inside a single process, time bugs are usually monotonic-clock bugs:
- A timeout computed as
Date.now() + 5000and checked againstDate.now()can fire early or never if the clock steps. Use the monotonic clock. - A latency metric computed from two wall-clock readings can be negative after a step backwards, and negative values have crashed real services that assumed they were impossible.
- A rate limiter keyed on wall-clock seconds can allow a double burst if time moves back by one second.
Timestamps from clients are input, not truth. A client-supplied timestamp is useful as a hint, for example to order a user's own offline edits made on one device, but any server-side decision that compares timestamps from different clients, such as an auction closing time, a contest deadline, or which of two editors saved last, should use a time or a sequence assigned by the server.
Leap seconds and smearing#
Atomic clocks define the second precisely, and International Atomic Time (TAI) counts those seconds steadily. But the Earth's rotation is slightly irregular and, over the long term, slowing, so a day measured by the sun is not exactly 86,400 atomic seconds. UTC is atomic time adjusted to stay within 0.9 seconds of solar time. Whenever the gap grows too large, the International Earth Rotation and Reference Systems Service announces a leap second: an extra second, written 23:59:60, inserted at the end of 30 June or 31 December. Twenty-seven positive leap seconds were inserted between 1972 and the end of 2016, and as a result UTC is 37 seconds behind TAI. No leap second has been inserted since 31 December 2016.
The leap second is a problem for computers because Unix time pretends it does not exist. Unix time counts every day as exactly 86,400 seconds. When a leap second occurs, the clock has nowhere to put 23:59:60, so the kernel typically repeats the last second: the timestamp 23:59:59 happens twice, and a reading taken during the leap second can be smaller than one taken just before it. Time goes backwards by a second, on every machine that follows UTC strictly, all at once.
Leap seconds have caused real, widespread outages, because code that assumes time never goes backwards is everywhere:
- 30 June 2012. A bug in the Linux kernel's handling of the leap second caused high-resolution timers to fire immediately and repeatedly, leaving many machines spinning at 100% CPU. Sites including Reddit and Mozilla had outages, and Java applications, which used the affected timer paths heavily, were hit especially hard. Rebooting, or simply setting the date again, fixed the affected machines.
- 31 December 2016. Cloudflare's DNS service failed for some customers because a piece of its Go code computed a duration from two time readings, got a negative result during the leap second, and passed it to a random-number function that panicked on negative input. Cloudflare published a detailed post-mortem, and Go later changed its standard library so that elapsed-time measurements use the monotonic clock.
Smearing. The alternative most large operators adopted is to smear the leap second: instead of inserting one extra second, their time servers run very slightly slow for many hours, so that by the end of the window, their clocks have absorbed the extra second without ever jumping or repeating. Google described smearing in 2011, and since 2016 its public NTP service has used a linear smear over 24 hours, from noon to noon UTC around the leap second, which slows clocks by about 11.6 ppm (one second divided by 86,400 seconds). That rate is well within the range NTP clients already tolerate. AWS's time service smears too, and Meta has described its own smearing approach.
The catch: smeared and unsmeared clocks disagree. During the smear window, a smearing server and a strict-UTC server differ by up to half a second, or a full second at the end of a window that is not centred on the leap second. Mixing time sources from both kinds in one fleet, or on one machine, gives you that much skew, plus confused NTP clients that see their sources disagree. Pick one approach for the whole fleet, and know which one your cloud provider uses.
Leap seconds and smearing, in depth#
Which way to handle a leap second:
| Approach | How it works | Effect on software | Who uses it |
|---|---|---|---|
| Insert 23:59:60 (strict UTC) | The kernel repeats or holds a second | Time goes backwards or stalls for one second; bugs in code that assumes monotonic time | Default NTP and kernel behaviour |
| Smear | Time servers slow clocks by about 11.6 ppm over 24 hours | No jumps, but clocks differ from UTC by up to 1 second for a day | Google, AWS, Meta and others |
| Use TAI or GPS time internally | Count atomic seconds, convert to UTC only for display | No leap problems internally; needs care at every boundary | Some scientific and financial systems |
| Stop the clock for one second | The clock holds at 23:59:59 | Durations measured across it are short by a second | Some older systems |
Leap seconds are going away. In November 2022, the General Conference on Weights and Measures resolved to stop inserting leap seconds by or before 2035, letting UTC and solar time drift further apart, with the details of any future correction left for later. Leap seconds are therefore rare and will stop, but the lessons are permanent: time can jump, two clocks can disagree by a large amount for hours, and code should never assume that a later reading of the time-of-day clock is larger. Discussions of a possible first negative leap second, prompted by the Earth's rotation speeding up slightly in recent years, are a reminder that the assumption could break in the other direction too.
Testing for time jumps. Teams that operate large fleets test time handling deliberately: run services under a fake clock, step the clock backwards and forwards in staging with tools such as libfaketime, and assert that durations are never negative, timeouts still fire, and logs remain sortable. A one-line review rule catches most bugs: any subtraction of two time-of-day readings should be questioned, and almost always replaced with a monotonic clock reading.
Happens-before and causality#
Physical clocks try to answer "when did this happen?". Usually a distributed system needs a different answer: "could this event have influenced that one?". Leslie Lamport framed this question in "Time, Clocks, and the Ordering of Events in a Distributed System" (Communications of the ACM, 1978), one of the most cited papers in computer science. He defined the happens-before relation, written a → b, using only things a system can actually observe:
- Same process. If a and b happen in the same process, and a comes before b in that process's execution, then a → b.
- Messages. If a is the sending of a message, and b is the receipt of that same message by another process, then a → b.
- Transitivity. If a → b and b → c, then a → c.
If neither a → b nor b → a, the two events are concurrent, written a ∥ b. "Concurrent" here does not mean "at the same moment". It means that neither event could have known about the other: no chain of messages connects them. Two events a second apart on different continents are concurrent if no message linked them.
Happens-before is exactly the relation of potential causality. If a → b, information from a could have reached b, so a might have caused b: a question and its answer, a write and a read that observed it, a "remove the boss from the album's audience" and the photo posted afterwards. If a ∥ b, neither could have affected the other, and any order between them is equally valid. This is why happens-before is a partial order: some pairs of events are ordered, and some are not.
Why causality is the order that matters. Users notice causal violations, and almost never notice anything else.
- In a comment thread, seeing a reply before the comment it answers is confusing. Two unrelated comments posted a second apart in either order are not.
- On a social network, a user removes a colleague from the audience of a photo album, then uploads a private photo. If a replica applies the upload before the permission change, the colleague can briefly see the photo. The two writes were causally ordered by one user's actions, and a system that does not preserve that order has a privacy bug.
- In a bank, a transfer's debit and credit are ordered by the transfer. Two different customers' unrelated deposits are not, and processing them in either order is fine.
A system provides causal consistency if every reader sees causally related writes in their causal order, while concurrent writes may be seen in different orders by different readers. It is the strongest consistency model that can stay available during network partitions, which is why it gets so much attention in geo-replicated systems.
In this space-time picture, a → b → d → e → g → i → j, by the process and message rules. So a → j: the first event on P1 could have influenced the last one, through a chain that passes through all three processes. But h, a local event on P1 after it sent m1, is concurrent with d, e and g. Nothing that happened at h was ever communicated to P2 or P3 before they acted. Similarly, c is concurrent with a and b, and f is concurrent with everything on P1 and P2 before m2 arrived.
Lamport clocks#
Lamport's paper also showed how to assign numbers to events so that the order of the numbers respects happens-before. A Lamport clock is a single integer counter per process, with three rules:
- Before each local event, increment the counter.
- When sending a message, increment the counter and attach its value to the message.
- When receiving a message carrying timestamp t, set the counter to max(counter, t) and then increment it. The receive event gets that value.
The result is the clock condition: if a → b, then L(a) is less than L(b). Each step along a causal chain either increments the counter within a process, or jumps it past the sender's value when a message arrives.
A worked example. The table applies the rules to the ten events in the diagram above, with all counters starting at 0.
| Event | Process | What happens | Lamport clock | Why |
|---|---|---|---|---|
| a | P1 | Local event | 1 | 0 + 1 |
| b | P1 | Sends m1 to P2 | 2 | 1 + 1, m1 carries 2 |
| c | P2 | Local event | 1 | 0 + 1 |
| d | P2 | Receives m1 | 3 | max(1, 2) + 1 |
| e | P2 | Sends m2 to P3 | 4 | 3 + 1, m2 carries 4 |
| f | P3 | Local event | 1 | 0 + 1 |
| g | P3 | Receives m2 | 5 | max(1, 4) + 1 |
| h | P1 | Local event | 3 | 2 + 1 |
| i | P3 | Sends m3 to P1 | 6 | 5 + 1, m3 carries 6 |
| j | P1 | Receives m3 | 7 | max(3, 6) + 1 |
Every causal chain has increasing numbers: a (1), b (2), d (3), e (4), g (5), i (6), j (7). That is the clock condition at work.
The limitation: the converse does not hold. L(a) less than L(b) does not imply a → b. Look at h and g: L(h) = 3 and L(g) = 5, but h and g are concurrent, since nothing from h ever reached P3. Worse, h and d both have the value 3 and are concurrent, and h (3) is less than e (4) even though h did not happen before e. A Lamport timestamp can tell you "b definitely did not happen before a" (if L(a) is less than L(b)), but it cannot tell you whether two events were causally related or concurrent. For conflict detection, where the whole question is "were these two writes concurrent?", Lamport clocks are not enough.
A total order from Lamport clocks. Lamport clocks give only a partial order, with ties such as h and d at 3. Breaking ties with the process ID, so that events are ordered by the pair (clock, process ID), produces a total order that every process can compute independently and that is consistent with causality. Lamport used exactly this to build a distributed mutual exclusion algorithm in the same paper: each process broadcasts its timestamped request to enter a critical section, every process keeps the requests in a queue sorted by (timestamp, process ID), and a process enters when its own request is at the head of its queue and it has heard a later-timestamped message from every other process. Every process sees the same order, so they agree on who goes next without a central coordinator. The algorithm is mainly of historical and teaching interest, because it needs every process to be alive and every message to be delivered, but the idea of state machine replication, where every replica applies the same commands in the same total order and therefore reaches the same state, comes from this paper and underlies every consensus system. See Consensus.
Lamport clocks, in depth#
Lamport clocks are everywhere, under other names. Any counter that a node raises to the highest value it has seen, and then increments, is a Lamport clock.
- Raft terms and Paxos ballot numbers. Each election increments the term, and every node that hears a message with a higher term adopts it immediately, stepping down if it was leader. A message with a stale term is rejected. This is a Lamport clock over election events, and it is what lets nodes recognise and ignore a deposed leader. See Consensus.
- Fencing tokens. A lock service that hands out an increasing number on every grant lets storage reject writes with a smaller number. See Distributed Locks.
- Operation IDs in CRDT libraries. Collaborative-editing libraries such as Automerge identify each operation by a pair of a counter and a replica ID, where the counter is a Lamport clock. Sorting by this pair gives every replica the same deterministic order for concurrent inserts, without trusting any device's wall clock. See Collaborative Editing and CRDTs.
- Last-writer-wins with logical timestamps. An LWW register that uses (Lamport counter, replica ID) instead of a wall-clock timestamp still discards one of two concurrent writes, but it never lets a write that causally followed another lose to it, which is precisely the failure that skewed wall clocks cause.
Size and cost. A Lamport clock is one integer, typically 64 bits, attached to each message and stored with each record. It costs almost nothing. Its weakness is information, not size: it squashes the partial order of causality into a single line, and in doing so forgets which events were concurrent.
A useful property for debugging. In logs from many services, sorting by wall-clock timestamp can place a request's effects before its cause when the servers' clocks disagree. Propagating a Lamport counter, or simply a trace ID with a per-hop sequence number, lets tools reconstruct the causal order of a request across services. Distributed tracing systems take this approach, recording parent and child relationships between spans explicitly instead of relying on timestamps alone. See Observability.
Vector clocks#
Vector clocks, introduced independently by Colin Fidge and Friedemann Mattern in 1988, fix the Lamport clock's blind spot. Instead of one counter, each process keeps a vector of counters, one entry per process. Entry i of process P's vector means "the number of events at process i that P knows about".
The rules, for a system of N processes, each starting with a vector of N zeros:
- Before each local event, process i increments its own entry, V[i].
- When sending a message, process i increments V[i] and attaches the whole vector.
- When receiving a message carrying vector W, process i sets each entry V[k] to max(V[k], W[k]), then increments V[i].
To compare two vector timestamps V and W:
- V ≤ W if every entry of V is less than or equal to the matching entry of W.
- V happened before W (V → W) if V ≤ W and V is not equal to W.
- V and W are concurrent if neither V ≤ W nor W ≤ V, meaning each has at least one entry larger than the other's.
The key property is that this comparison is exact: a → b if and only if V(a) → V(b). Vector clocks characterise causality completely. Given the timestamps of two events, you can always tell whether one happened before the other, or whether they were concurrent.
The same worked example, with vector clocks. Vectors are written [P1, P2, P3].
| Event | Process | What happens | Vector clock | Why |
|---|---|---|---|---|
| a | P1 | Local event | [1, 0, 0] | Increment P1 |
| b | P1 | Sends m1 to P2 | [2, 0, 0] | Increment P1, m1 carries [2, 0, 0] |
| c | P2 | Local event | [0, 1, 0] | Increment P2 |
| d | P2 | Receives m1 | [2, 2, 0] | Merge [0, 1, 0] with [2, 0, 0], then increment P2 |
| e | P2 | Sends m2 to P3 | [2, 3, 0] | Increment P2, m2 carries [2, 3, 0] |
| f | P3 | Local event | [0, 0, 1] | Increment P3 |
| g | P3 | Receives m2 | [2, 3, 2] | Merge [0, 0, 1] with [2, 3, 0], then increment P3 |
| h | P1 | Local event | [3, 0, 0] | Increment P1 |
| i | P3 | Sends m3 to P1 | [2, 3, 3] | Increment P3, m3 carries [2, 3, 3] |
| j | P1 | Receives m3 | [4, 3, 3] | Merge [3, 0, 0] with [2, 3, 3], then increment P1 |
Now the questions that Lamport clocks could not answer have exact answers.
| Pair | Lamport clocks | Vector clocks | True relation |
|---|---|---|---|
| a and g | 1 and 5 | [1, 0, 0] ≤ [2, 3, 2] | a → g |
| h and g | 3 and 5, looks ordered | [3, 0, 0] vs [2, 3, 2]: P1 entry larger in h, P2 entry larger in g | Concurrent |
| h and d | 3 and 3, a tie | [3, 0, 0] vs [2, 2, 0]: mixed | Concurrent |
| c and b | 1 and 2, looks ordered | [0, 1, 0] vs [2, 0, 0]: mixed | Concurrent |
| h and j | 3 and 7 | [3, 0, 0] ≤ [4, 3, 3] | h → j |
Why the vector captures causality. Entry k of an event's vector counts exactly the events at process k that are in its causal past, because the only way to learn about an event at k is through a chain of messages from k, and each message carries the sender's full knowledge, which the receiver merges. If a → b, everything in a's past is in b's past, so V(a) ≤ V(b). If a and b are concurrent, a's own process has an entry that a counts but b does not (b never heard of a), and b's process has an entry that b counts but a does not, so the vectors are incomparable.
Vector clocks, in depth#
Version vectors: the form used by databases. Databases rarely need to timestamp every event. They need to know, for two versions of the same key, whether one supersedes the other or whether they conflict. A version vector is a vector clock attached to a data item, with one entry per replica that has written it, and incremented only on writes. When a client reads a key, it receives the value with its version vector. When it writes back, it sends that vector as the context of its write. The replica that coordinates the write increments its own entry. Now any replica can compare two versions:
- If one version's vector dominates the other's, the older version is obsolete and can be discarded.
- If the vectors are concurrent, the versions are genuine conflicts. Both are kept, as siblings, until someone resolves them.
This is how Amazon's original Dynamo handled shopping carts ("Dynamo: Amazon's Highly Available Key-value Store", Giuseppe DeCandia and colleagues, SOSP 2007). During a partition, two clients could update the same cart through different replicas. Dynamo kept both versions, detected with vector clocks that they were concurrent, and returned both on the next read. The cart application merged them by taking the union of items. The paper also notes the known weakness of that merge: an item deleted in one branch can reappear after a union, which Amazon accepted because losing an "add to cart" was worse for the business than an occasional resurrected item. Riak, an open-source Dynamo-style database, exposed siblings directly to applications in the same way.
The size problem. A vector clock needs one entry per process that has ever written, and that number can grow without bound: replicas come and go, and if clients act as their own writers, there can be millions of them. Three common answers:
- Use replica IDs, not client IDs. Entries are created only for the small set of servers that coordinate writes (for example, three replicas of a key), keeping vectors short. The catch is that two clients writing through the same replica concurrently must be handled specially, or one write can silently overwrite the other.
- Dotted version vectors. Riak adopted dotted version vectors (Nuno Preguiça, Carlos Baquero and colleagues) to solve exactly that catch. Each write is tagged with a single "dot", the replica ID and counter of the write itself, alongside the vector of what the client had seen, which lets a server detect concurrent writes from clients that went through the same replica, without adding client entries.
- Pruning. Dynamo truncated a vector clock once it held more than a threshold of entries (the paper mentions 10), removing the oldest entry by a stored timestamp. Pruning can make two versions look concurrent when one actually descended from the other, which causes a spurious conflict, never silent data loss. Dynamo's authors reported that it did not cause significant problems in production.
A lower bound on size. Bernadette Charron-Bost proved in 1991 that any timestamping scheme that characterises causality exactly, as vector clocks do, needs timestamps of at least N entries in the worst case for N processes. You cannot compress vector clocks into something smaller in general and keep the exact concurrency test. Systems that need small timestamps give up exactness, as Lamport clocks and hybrid logical clocks do, or restrict the pattern of communication.
Causal delivery with vector clocks. A message-passing layer can guarantee that messages are delivered in causal order using vector clocks. A receiver holds back a message from process j with vector W until it has delivered every message W depends on: W[j] must be exactly one more than the number of messages it has delivered from j, and for every other process k, W[k] must be no more than the number it has delivered from k. Messages that arrive early wait in a buffer. Group communication systems in the 1980s and 1990s, notably the ISIS toolkit by Kenneth Birman and colleagues, built causal and totally ordered multicast this way.
Where vector clocks are not the right tool. They answer "were these concurrent?" but not "which one should win?". Detecting a conflict is only half the job: the application must still merge siblings. For many data types that merge has to be written by hand, which is error prone, and this is part of why later systems moved to data types with built-in merges (CRDTs) or to strongly consistent designs where conflicts cannot arise. Cassandra, for instance, chose LWW over vector clocks to keep reads simple and fast.
Hybrid logical clocks#
Logical clocks respect causality but have nothing to do with real time. A Lamport timestamp of 4,812 says nothing about whether the event happened a second ago or last week, so you cannot ask "give me the state of the database as of 10:00". Physical clocks are close to real time but do not respect causality under skew. Hybrid logical clocks (HLC), proposed by Sandeep Kulkarni, Murat Demirbas and colleagues in "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases" (2014), combine the two.
An HLC timestamp is a pair (l, c):
- l is the largest physical time this node has seen, either from its own clock or from any message it received. It always stays close to real time.
- c is a small logical counter that breaks ties when l does not change, for example when several events happen within one clock tick, or when a message arrives from a node whose clock is ahead.
The rules, where pt is the node's current physical clock reading:
- Local event or send. Set the new l to max(old l, pt). If l did not change, increment c. If l moved forward, reset c to 0. Attach (l, c) to any message sent.
- Receive a message with (lm, cm). Set the new l to max(old l, lm, pt). Then set c according to which value won: if l equals both the old l and lm, c becomes max(old c, cm) + 1; if l equals only the old l, c becomes old c + 1; if l equals only lm, c becomes cm + 1; if pt won outright, c becomes 0.
Comparing HLC timestamps is simple: compare l first, then c. The properties:
- Causality. If a → b, then HLC(a) is less than HLC(b), just as with Lamport clocks.
- Close to physical time. l is never behind the node's own physical clock, and is never ahead of the true time by more than the maximum clock skew in the cluster. So an HLC timestamp can be read as a wall-clock time, accurate to within the clock synchronisation error.
- Small and bounded. c stays small in practice. The pair fits in 64 bits, for example 48 bits of milliseconds and 16 bits of counter, so HLC timestamps can replace ordinary timestamps in existing formats.
A worked example. Node B's clock is 5 ms behind node A's.
| Step | Node | Physical clock | Event | HLC after | Explanation |
|---|---|---|---|---|---|
| 1 | A | 100 | Sends message | (100, 0) | pt moved l forward, c reset |
| 2 | B | 96 | Receives A's message | (100, 1) | The message's l of 100 wins over pt 96, so c = 0 + 1 |
| 3 | B | 97 | Local write | (100, 2) | l stays at 100, ahead of pt, so c increments |
| 4 | B | 101 | Local write | (101, 0) | pt has passed l, so l moves forward and c resets |
| 5 | A | 101 | Local write | (101, 0) | Concurrent with B's step 4, same timestamp, tie broken by node ID |
B's write at step 3 is ordered after A's message, even though B's physical clock reads 97, which is earlier than A's 100. With plain physical timestamps, B's causally later write would have looked older. With HLC, it does not.
Hybrid logical clocks, in depth#
Who uses HLC. CockroachDB and YugabyteDB assign transaction timestamps from HLCs. MongoDB uses a hybrid logical clock for its cluster time, which drives causally consistent sessions: a client passes back the latest cluster time it has seen, and a secondary will not answer the client's read until it has caught up to that time, so the client always reads its own writes, even from a replica.
What HLC does not give you: uncertainty. HLC respects causality between events that communicate. It cannot order two events that never communicated, such as two clients writing to two different nodes, beyond the accuracy of the physical clocks. If node A's clock runs 50 ms ahead of node B's, a transaction that commits on B 20 ms after a transaction on A, in real time, can receive a smaller timestamp. HLC alone leaves a window of ambiguity the size of the clock skew.
CockroachDB's answer: a maximum offset and uncertainty intervals. CockroachDB requires every node's clock to be within a configured maximum offset of the others, 500 ms by default. Nodes continuously measure their clock offsets against peers, and a node that detects its own clock is too far out of line shuts itself down rather than risk violating consistency. Given that bound, when a transaction reading at timestamp t finds a value written with a timestamp between t and t plus the maximum offset, it cannot tell whether that write happened before or after the read in real time. It must not ignore the value, which could be a stale read, so it restarts the read at a timestamp above the conflicting write. This is the uncertainty interval. Most reads never meet a write in their uncertainty interval, and a node can shrink the interval once it has observed the clock of the node holding the data, so the cost is occasional read restarts rather than a wait on every transaction. The trade-off is in guarantees: CockroachDB's engineers have explained that this design gives serializable transactions and no stale reads on a single key, but not Spanner's stronger guarantee of a real-time order across all transactions, which would require waiting out clock uncertainty on every commit.
Why bounded skew becomes a correctness assumption. In a system like this, keeping clocks within the maximum offset is not just good hygiene. It is part of the correctness argument. If clocks drift beyond the bound without detection, stale reads become possible. That is why such databases check offsets themselves and refuse to run with bad clocks, and why their operations guides insist on reliable NTP or chrony, with a smearing approach consistent across the cluster.
HLC for snapshots and debugging. Because HLC timestamps are close to physical time and respect causality, taking every node's state "as of HLC time T" gives a consistent snapshot: no event in the snapshot depends on an event left out of it. The original paper emphasised this use: backups, point-in-time queries and debugging, where you want to see the whole system as it was at roughly 10:00, without violating causality. Logs stamped with HLC sort into an order that is both readable as wall-clock time and causally correct.
TrueTime#
Google's Spanner ("Spanner: Google's Globally-Distributed Database", James Corbett and colleagues, OSDI 2012) took a different path. Instead of hiding clock uncertainty, it measures and exposes it. Its TrueTime API does not return a single time. It returns an interval:
TT.now()returns an interval [earliest, latest] that is guaranteed to contain the true absolute time at the moment of the call.TT.after(t)is true if t has definitely passed, meaning t is less than earliest.TT.before(t)is true if t has definitely not arrived yet, meaning t is greater than latest.
The half-width of the interval is called ε (epsilon). TrueTime makes it small with dedicated hardware. Each data centre has a set of time master servers. Most have GPS receivers. The others, which the paper calls "Armageddon masters", have atomic clocks, because GPS and atomic clocks fail in different ways: GPS can lose signal or suffer antenna and interference problems, while atomic clocks drift slowly but independently of anything outside. Every machine runs a time daemon that polls several masters in its own and other data centres, rejects outliers, and synchronises. Between polls, the daemon assumes a worst-case local drift of 200 microseconds per second. Since it polls every 30 seconds, uncertainty grows from about 1 ms just after a poll to about 7 ms just before the next one, the paper's reported sawtooth of roughly 1 to 7 ms, averaging about 4 ms.
Commit wait. Spanner uses TrueTime to give transactions external consistency: if transaction T1 commits before transaction T2 starts, in real time, then T1's commit timestamp is smaller than T2's, whichever machines they run on. It does this with a rule called commit wait:
- When a read-write transaction is ready to commit, its coordinator picks a commit timestamp s that is at least
TT.now().latest, so s is not earlier than the true time. - It replicates the commit through Paxos as usual.
- Before making the commit visible, and before replying to the client, it waits until
TT.after(s)is true, meaning the true time has definitely passed s.
The wait is about 2ε on average, a few milliseconds, and much of it overlaps with the Paxos replication round trip, which takes that long anyway.
Why commit wait works. Suppose T1 commits with timestamp s1, and the client sees the reply. Because of commit wait, the true time at the reply is later than s1. Now T2 starts afterwards. When T2's coordinator picks s2, it chooses at least TT.now().latest, which is no earlier than the true time at that moment, which is later than T1's reply, which is later than s1. So s2 is greater than s1. The argument needs nothing except that TrueTime's interval really contains the true time. If the hardware or the daemons ever violated that bound, the guarantee would break, which is why Google invested in redundant GPS and atomic references and in daemons that evict machines whose clocks look unreliable.
TrueTime, in depth#
What external consistency buys. With timestamps that respect real-time order globally, Spanner can offer:
- Lock-free snapshot reads. A read-only transaction picks a timestamp, for example
TT.now().latest, and reads every shard as of that timestamp. It needs no locks and cannot block writers, yet it sees a consistent snapshot of the whole database. Each replica tracks a "safe time" up to which it knows it has applied every write, and serves the read once safe time passes the read timestamp. - Consistent backups and schema changes at a chosen timestamp, across thousands of machines.
- Intuitive behaviour for applications: if a user saves something, then a different service reads it after hearing about the save, the read sees the save. Without external consistency, a read routed to another region could miss it.
The cost of uncertainty is latency. Commit wait turns clock uncertainty directly into write latency. With ε of 4 ms, each read-write transaction waits about 8 ms. If ε were 100 ms, as it might be with ordinary NTP over a WAN, every commit would wait about 200 ms, which is why TrueTime needs special hardware and why systems on ordinary clocks, such as CockroachDB, chose uncertainty intervals and read restarts instead. The general principle is worth remembering: any system that wants real-time ordering across machines must pay for clock uncertainty somewhere, in hardware, in waiting, in retries, or by routing everything through one sequencer.
Bounded clocks outside Google. The idea has spread. AWS's ClockBound exposes an earliest and latest bound in the same spirit, using the precise Amazon Time Sync Service, and clocks with explicit error bounds let databases built on them use commit-wait-style reasoning with waits measured in microseconds rather than milliseconds. The lesson from TrueTime is that the uncertainty, not the time, is the useful quantity: a clock that says "between 10.000 and 10.008" is safer than one that says "10.004" and hides its error.
Spanner's timestamps in a worked example. A transfer transaction commits in the US with s1 = 10.008 after its commit wait, and its reply reaches the client at true time 10.009. The client then tells a service in Europe, which starts a read-write transaction at true time 10.050. The European leader's TrueTime returns [10.046, 10.054], so it picks s2 of at least 10.054. Since 10.054 is greater than 10.008, the European transaction is ordered after the transfer, even though it ran on a different continent, with a clock that may be several milliseconds off.
Ordering without clocks: sequence numbers and logs#
Often the simplest and strongest way to order events is to avoid comparing clocks entirely, and let one authority assign the order.
- A single sequencer per key or partition. Route all events for one entity, such as a chat conversation, a bank account or an order, through one owner, which assigns increasing sequence numbers. A Kafka partition does this with offsets, a database does it with its write-ahead log, and a consensus group does it with log indexes. Order is then exact and gap-free, with no clock involved. The cost is that the owner is a bottleneck for that key, which is why the scope is one key or partition, not the whole system.
- Gap detection. With sequence numbers, receivers can detect missing events. A chat client that has message 40 and receives 42 knows 41 is missing, and fetches it, instead of showing messages out of order. Timestamps cannot do this, because there is no "next" timestamp. See Realtime Updates.
- Consensus logs. When the authority must survive failures, the sequencer itself is replicated with consensus, and the log index is the order. This is what etcd, ZooKeeper, Kafka's controller and Raft-based databases do. See Consensus.
- Time-ordered IDs. Snowflake-style IDs combine a millisecond timestamp, a machine ID and a per-millisecond sequence. They are roughly sorted by creation time, which is convenient for indexes and pagination, but only as accurate as the clocks of the generating machines, so two IDs from different machines within the skew window may be out of real-time order. Generators must also refuse to issue IDs, or wait, if their clock moves backwards, or they can create duplicates. See Unique ID Generation.
When to Use It#
Every distributed system uses time, so the real question is which tool to use for which job.
- Physical time (NTP-synchronised wall clocks): for showing times to people, for coarse expiry such as "delete sessions older than 30 days" or "remove drivers not seen for 30 seconds", for log timestamps and metrics, and for any decision where an error of a few milliseconds, or occasionally seconds, is harmless.
- Monotonic clocks: for every duration, timeout, retry backoff, latency measurement and rate limit within one process.
- Sequence numbers from a single owner: whenever events for one entity must be applied in exact order, such as messages in a conversation, operations on an account, or changes to a row propagated through CDC.
- Lamport clocks: when you need a cheap total order consistent with causality, such as terms, epochs, fencing tokens and operation IDs in replicated data types.
- Vector clocks or version vectors: when replicas accept writes independently (multi-leader or leaderless replication, offline-first apps) and you must detect concurrent updates rather than silently discard one.
- Hybrid logical clocks: when a database or log needs timestamps that are causally correct and also meaningful as wall-clock time, for MVCC, snapshots, point-in-time reads and change feeds.
- TrueTime or bounded-error clocks: when you need globally linearizable transactions across regions and can afford the infrastructure, or are using a managed database that provides it.
When NOT to Use It#
- Do not use wall-clock timestamps to resolve conflicting writes to the same data from different machines, unless losing one of two close writes is acceptable.
- Do not compute durations or timeouts from time-of-day readings. Use the monotonic clock.
- Do not trust client device clocks for anything compared across users, such as deadlines, auctions, rankings and fraud checks.
- Do not reach for vector clocks when a single leader would do. If all writes for a key already go through one primary, its log order is exact and free. Vector clocks add size and require merge logic.
- Do not build TrueTime-style commit wait on ordinary NTP. With uncertainty of tens of milliseconds, the wait becomes a large latency tax, and if the error bound is not truly guaranteed, the correctness argument fails.
- Do not seek a global order of all events when per-key order is enough. A global sequencer is a bottleneck and a single point of failure.
How to Implement It#
- Synchronise every machine's clock. Run chrony or ntpd against several internal or cloud time sources (at least three, so a bad one can be outvoted), step only at boot, and slew afterwards. Use the same leap-second policy, smeared or not, for the whole fleet.
- Monitor clock offset. Export each host's estimated offset and alert well before it reaches any bound your software assumes, for example at 50 ms when a database's maximum offset is 500 ms. Treat a host with an unknown offset as unhealthy.
- Separate the two kinds of clocks in code. Wrap time access in a small module, with one function for wall-clock "now" and one for monotonic elapsed time, so reviewers can see which is used, and tests can fake both.
- Assign order at a single owner for per-entity events: partition by entity ID, and use the partition offset or a per-entity sequence number stored with the data.
- Version every mutable record, and use conditional writes ("update where version = 7") instead of blind overwrites.
- Where replicas write independently, attach version vectors and keep siblings on conflict, or use CRDTs with well-defined merges.
- Where you need causally correct timestamps, use a database that provides HLC or TrueTime, rather than building your own. If you must build one, use a tested HLC implementation, enforce a maximum offset, and reject messages whose timestamps are too far in the future.
- Record both timestamps for client data: the device time, as a hint and for ordering within one device, and the server receive time, as the authority.
// Hybrid logical clock: 48-bit milliseconds plus 16-bit counter
const MAX_OFFSET_MS = 500;
export class HLC {
private l = 0; // highest physical time seen, in ms
private c = 0; // logical counter
constructor(private physicalNow: () => number = Date.now) {}
now(): [number, number] { // local event or send
const pt = this.physicalNow();
if (pt > this.l) { this.l = pt; this.c = 0; }
else { this.c += 1; }
return [this.l, this.c];
}
update(lm: number, cm: number): [number, number] { // on receive
const pt = this.physicalNow();
if (lm - pt > MAX_OFFSET_MS) throw new Error("remote clock too far ahead");
const prevL = this.l;
this.l = Math.max(prevL, lm, pt);
if (this.l === prevL && this.l === lm) this.c = Math.max(this.c, cm) + 1;
else if (this.l === prevL) this.c += 1;
else if (this.l === lm) this.c = cm + 1;
else this.c = 0;
return [this.l, this.c];
}
}
export const compareHLC = (a: [number, number], b: [number, number]) =>
a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1];The guard in update matters. Without it, one node with a clock set a year ahead would drag every node's HLC a year into the future, and they could never recover, because HLC never moves backwards. Real implementations also check that the counter does not overflow its 16 bits.
| Technology | Fits when |
|---|---|
| chrony | Default choice for synchronising Linux servers and VMs with NTP; fast convergence, good with intermittent connectivity |
| ntpd | Older deployments; same protocol, slower convergence |
| PTP (IEEE 1588) with hardware timestamping | Sub-microsecond agreement for trading, telecom and large data centres with PTP-capable network hardware |
| Amazon Time Sync Service and ClockBound | Instances on AWS needing accurate time, and an explicit error bound for ordering decisions |
| Google public NTP or GCE metadata NTP | Smeared leap seconds; consistent with other Google-smeared sources |
| Google Spanner (TrueTime) | Globally consistent, externally consistent transactions as a managed service |
| CockroachDB, YugabyteDB | Distributed SQL with HLC timestamps on commodity clocks, within a bounded offset |
| Kafka partitions | Exact order per key through partition offsets |
| Riak, Dynamo-style stores | Version vectors and siblings for concurrent writes |
| Automerge, Yjs | Logical clocks and CRDTs for collaborative and offline-first apps |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Wall-clock timestamps (LWW) | Trivial; no coordination; readable | Silent data loss under skew and concurrency; future timestamps poison keys | Writes to a key are rare and losing one is harmless |
| Single-owner sequence numbers | Exact order; gap detection; no clocks | Owner is a bottleneck and must fail over | Per-entity ordering, such as conversations, accounts and CDC |
| Lamport clocks | One integer; respects causality; total order with tie-break | Cannot detect concurrency; unrelated to real time | Terms, epochs, fencing tokens, CRDT operation IDs |
| Vector clocks and version vectors | Exact causality; detect conflicts | Size grows with writers; siblings need merge logic | Multi-leader or leaderless replication, offline sync |
| Hybrid logical clocks | Causal and close to real time; 64 bits | Needs a skew bound; uncertainty between unrelated events | MVCC timestamps, snapshots, change feeds in distributed databases |
| TrueTime with commit wait | Global real-time order; lock-free snapshot reads | Special hardware; commit latency of about 2ε | Global transactional systems needing external consistency |
Common Pitfalls#
- Sorting events from different servers by timestamp and assuming the order is real. A reply can sort before its question.
- LWW on a frequently updated field, such as a counter, a status or a cart, silently losing updates whenever writers are close together.
- Measuring timeouts with the wall clock, so they fire early, late, or never after a clock step.
- A single NTP source, or none: one bad server, or a blocked UDP port, lets clocks drift without anyone noticing.
- Mixing smeared and unsmeared time sources, creating up to a second of skew during leap events.
- Trusting device clocks for deadlines, leaderboards or fraud checks.
- Unbounded vector clocks that grow with every client that ever wrote.
- Snowflake-style generators that ignore backward clock jumps, issuing duplicate or out-of-order IDs.
- Accepting remote timestamps far in the future into an HLC, or a TTL, without a sanity bound.
- Treating leases and TTLs as exact. Expiry depends on the clocks of the store and the holder, and a paused process can act after its lease ended. Back leases with fencing.
Real-World Examples#
- Google Spanner uses TrueTime, with GPS and atomic-clock time masters and ε of a few milliseconds, to provide externally consistent transactions and lock-free snapshot reads worldwide (Corbett and colleagues, OSDI 2012).
- CockroachDB uses hybrid logical clocks, a default maximum clock offset of 500 ms, uncertainty intervals with read restarts, and self-termination of nodes whose clocks drift too far.
- MongoDB uses a hybrid logical cluster time to implement causally consistent client sessions, so a client can read its own writes from secondaries.
- Amazon Dynamo used vector clocks to detect concurrent shopping cart updates and returned siblings for the application to merge, truncating clocks beyond about 10 entries (DeCandia and colleagues, SOSP 2007).
- Apache Cassandra resolves conflicting cell values by write timestamp (LWW), which is why its operators insist on tight clock synchronisation, and why its data models favour inserting new rows over updating cells in place.
- Cloudflare suffered a DNS outage at the leap second on 31 December 2016, when a negative time difference reached code that assumed time never goes backwards. Linux servers at many companies spun at full CPU after the June 2012 leap second.
- Google smears leap seconds over 24 hours in its public NTP service. AWS and Meta smear too.
- Raft and Paxos use terms and ballot numbers, which are Lamport clocks, to ignore stale leaders.
In the Interview#
Deep Dive: Consistent cuts and distributed snapshotsShow
The question. Suppose you want to record the global state of a running distributed system: every process's state and every message in flight. It is needed for checkpoints, for detecting deadlock or termination, and for debugging. You cannot stop the world, and you cannot ask every process to record its state "at 10:00:00.000", because their clocks disagree and messages are in flight.
Cuts. A cut picks one point in each process's history: everything before it is in the snapshot, everything after is not. A cut is consistent if, whenever it includes an event, it also includes every event that happened before it. Equivalently, no message is recorded as received but not sent. An inconsistent cut shows effects without causes, such as money that arrived in account B without leaving account A, so the snapshot's total is wrong.
Vector clocks make consistency easy to check. If the cut's last event at each process i has vector Vi, the cut is consistent exactly when, for all i and j, Vi[i] is at least Vj[i]: no process has seen more of process i's events than process i itself has recorded.
The Chandy-Lamport algorithm. K. Mani Chandy and Leslie Lamport gave an algorithm for recording a consistent snapshot without pausing the system, in "Distributed Snapshots: Determining Global States of Distributed Systems" (ACM Transactions on Computer Systems, 1985). It assumes reliable FIFO channels between processes.
- The initiator records its own state, then sends a special marker message on every outgoing channel.
- When a process receives a marker for the first time, it records its own state, records the channel the marker came on as empty, and sends markers on all its outgoing channels.
- After recording its state, a process records every message that arrives on each other incoming channel until a marker arrives on that channel. Those messages are the channel's in-flight state.
- The snapshot is complete when every process has recorded its state and received a marker on every incoming channel.
Because channels are FIFO, any message sent before the marker arrives before it, and is either reflected in the receiver's recorded state or captured as in-flight. Any message sent after the marker arrives after the receiver has recorded its state, so it is excluded from both. The recorded cut is consistent. In the example, the initial total is A 100 plus B 50, so 150, and the snapshot also totals 150, even though no process paused.
Modern descendants. Apache Flink's checkpoints are a variant designed for dataflow graphs, described as asynchronous barrier snapshotting by Paris Carbone and colleagues in 2015: sources inject barriers into their streams, each operator snapshots its state when barriers have arrived from all inputs, and the barriers flow downstream like markers. This is how Flink gives exactly-once state in stream processing. See Batch and Stream Processing. Databases with HLC or TrueTime take the other route: a snapshot is simply "every shard as of timestamp T", which is consistent because the timestamps respect causality.
Deep Dive: Leases, clock drift and the limits of time-based safetyShow
Leases depend on two clocks agreeing about duration, not about the time. A lease says "you hold this right for 10 seconds". The grantor starts its timer when it grants. The holder starts its timer when it receives the grant, slightly later. As long as the holder stops acting before the grantor considers the lease expired, there is never a moment when two holders act at once. That needs only that both clocks measure 10 seconds approximately equally, which monotonic clocks can do: rate drift is small, and absolute offset does not matter.
The drift margin. If clocks may run at rates differing by at most ρ (rho), the holder should treat a lease of duration D as ending after D × (1 - ρ) of its own time, minus a margin for message delay. With D = 10 seconds and ρ = 200 ppm, the drift margin is 2 ms, which is tiny. Leases with time-based safety are sound in principle on ordinary hardware, provided monotonic clocks are used, not wall clocks that can be stepped.
What actually breaks leases: pauses. The real danger is not drift but a process that checks its lease, sees 3 seconds left, then pauses for 15 seconds before acting. Garbage collection, VM migration, swapping, a blocked disk write or a stalled network can all do this. When it resumes, it acts on a check that is long stale, and another holder may now exist. No amount of clock accuracy fixes this, because the check and the action are separated by an unbounded gap. Defences:
- Fencing tokens: the grantor gives each lease an increasing number, and the resource rejects requests with an old number. Safety then comes from the resource's check, not from timing. See Distributed Locks.
- Check close to the action, and have the resource re-verify where possible, such as a conditional write on a version column.
- Bound the pause: tune garbage collection, avoid swap, and use a separate heartbeat thread. This reduces how often pauses happen, but cannot prove they will not.
Leader leases for reads. Consensus systems sometimes let the leader answer reads locally, without contacting a majority, while it holds a lease that followers promise not to break by electing another leader. This saves a round trip per read, but its safety depends on bounded clock drift and on the leader not pausing past its lease. The alternative, confirming leadership with a quorum round trip per read batch (the read index approach in Raft), depends on no clocks at all. Systems that offer both, such as etcd and TiKV, describe the lease-based path as relying on timing assumptions.
Time-based expiry in practice. Ride dispatch shows the right shape. When a request is offered to a driver, the service sets a Redis key for that driver with a 10-second TTL, so no other matcher offers them a ride. If the matching service crashes, the TTL still expires, unlike an in-process timer. But the authoritative step, assigning the ride, happens in the database with a conditional update ("set driver on ride where ride status is requested"), so even if the TTL expired early because of a clock jump and two drivers accepted, only one assignment succeeds. The time-based mechanism provides efficiency and liveness. The conditional write provides safety.
Deep Dive: Causal consistency in practiceShow
Session guarantees. Douglas Terry and colleagues defined four guarantees a client session can have over weakly consistent replicas, in "Session Guarantees for Weakly Consistent Replicated Data" (1994):
- Read your writes: a client always sees its own earlier writes.
- Monotonic reads: a client never sees data go back in time, for example by reading from a fresh replica and then a stale one.
- Writes follow reads: a write is ordered after any write the client read before making it.
- Monotonic writes: a client's writes are applied in the order it issued them.
Together they give causal consistency from one client's point of view. They are implemented by having the client carry a token, a version vector, a log position or an HLC time, that records what it has seen. A replica serves the request only if it has caught up to the token, otherwise it waits, or forwards the request elsewhere. MongoDB's causally consistent sessions pass cluster time this way, and Azure Cosmos DB's session consistency level uses session tokens on the same principle.
Causal consistency across clients. Sessions handle one client's view. Ensuring that a third party sees causally related writes in order requires tracking dependencies between writes. "Don't Settle for Eventual: Scalable Causal Consistency for Wide-Area Storage with COPS" (Wyatt Lloyd, Michael Freedman, Michael Kaminsky and David Andersen, SOSP 2011) showed how: each write carries the list of writes it depends on, as observed by the client, and a remote data centre does not make a replicated write visible until all its dependencies are visible there. A photo posted after a permission change cannot appear in a remote region before the permission change. "Bolt-on Causal Consistency" (Peter Bailis and colleagues, SIGMOD 2013) showed that the same dependency checks can be added as a layer on top of an eventually consistent store such as Cassandra.
The cost. Dependency metadata grows with how much a client has read, and remote writes wait for their dependencies, which adds visibility delay during slow replication. Systems keep the metadata small by tracking only the nearest dependencies, since older ones are implied transitively, and by using per-data-centre vectors rather than per-client ones.
Why it matters for design. Many applications that think they need strong consistency only need causal consistency plus read-your-writes. A social feed, comments, collaborative documents and chat all work well with it, and it remains available during partitions. Strong consistency, with consensus and its cross-region latency, is needed only where invariants span users, such as unique usernames, balances and inventory. See CAP Theorem and PACELC and Multi-Region Data.
Key Takeaways#
- Every machine's clock drifts by tens of ppm, and NTP keeps fleets within milliseconds, not exactly in step. Clocks can also jump, especially when stepped or at leap seconds.
- Use monotonic clocks for durations and timeouts, and wall clocks only for display, logging and coarse expiry.
- Last-writer-wins on wall-clock timestamps silently loses writes whenever writes are closer together than the skew. Prefer immutable records, conditional writes, single-owner sequence numbers or mergeable types.
- Leap seconds can make time repeat. Smear consistently across the fleet, never mix smeared and unsmeared sources, and never assume a later reading is larger.
- Happens-before captures potential causality. Concurrent means "neither knew of the other", not "at the same instant".
- Lamport clocks respect causality in one integer but cannot detect concurrency. Vector clocks detect it exactly, at the cost of one entry per writer.
- Hybrid logical clocks are causal and stay close to real time, within the clock skew bound, which is why distributed SQL databases use them.
- TrueTime exposes clock uncertainty as an interval, and Spanner waits it out with commit wait to give global real-time ordering. Whoever wants real-time order across machines pays for uncertainty somewhere.