Time, Clocks & Ordering
- Explain clock skew, drift and NTP behavior, and why wall-clock timestamps cannot order events across machines
- Use monotonic clocks for durations and timeouts, and wall clocks only for human-facing time
- Apply Lamport clocks, vector clocks and hybrid logical clocks, and say what each can and cannot tell you
- Describe how Spanner's TrueTime and commit wait provide external consistency, and how fencing tokens make leases safe
- Design event ordering for a payment flow with out-of-order and duplicate events
TL;DR
- Every machine's clock is wrong by a different, changing amount. NTP keeps them roughly aligned (≈ milliseconds on a good network, worse over the internet) and can step them backwards.
- Use the monotonic clock for timeouts, durations and lease checks; use the wall clock only for display, logs and business dates — and never to decide which of two writes on different machines came first.
- Lamport clocks give a total order consistent with causality but cannot tell you whether two events were concurrent. Vector clocks can, at the cost of one counter per node.
- Hybrid logical clocks (HLC) combine physical time and a logical counter: close to wall time, yet causality-respecting. CockroachDB, YugabyteDB and MongoDB use variants.
- TrueTime exposes clock uncertainty as an interval; Spanner waits out that uncertainty before committing ("commit wait") to get real-time ordering without trusting any single clock.
- Fencing tokens — monotonically increasing numbers checked by the storage layer — are what make time-based leases safe against pauses and skew.
- In payments, order by per-entity sequence numbers and state machines, not timestamps.
Why it matters
Consider an account updated by two services on different hosts. Host A's clock is 80 ms fast. A customer changes their daily transfer limit from $5,000 to $1,000 on host B at 10:00:00.050 (true time). Host A processes a stale retry of the old setting at 10:00:00.020 true time but stamps it 10:00:00.100. A last-writer-wins store keeps the older write because it has the larger timestamp. The limit silently reverts to $5,000 — and the audit trail, sorted by timestamp, tells a misleading story.
Time also decides money directly: end-of-day cut-offs determine whether a transfer gets today's or tomorrow's value date, card authorizations expire after a window, interest accrues per day, and fraud rules count transactions per minute. And in incident reviews, you will correlate logs from twenty services by timestamp — and need to know how far apart their clocks may be. Regulated trading goes further: MiFID II, for instance, prescribes maximum clock divergence from UTC for trading venues and participants.
Core concepts
Physical clocks and their failure modes
- Drift: quartz oscillators run fast or slow by tens of parts per million, varying with temperature. Spanner's design assumed a worst-case drift bound of 200 µs per second between synchronizations.
- Synchronization: NTP (or chrony) polls time servers and corrects the clock. Typical accuracy is around a millisecond on a good LAN and tens of milliseconds over the internet (rough). PTP (IEEE 1588) with hardware timestamping gets to microseconds or better. Cloud providers offer local time services (e.g., AWS Time Sync Service) and some expose an error bound (AWS's open-source ClockBound).
- Steps and slews: small errors are corrected by slewing (running slightly fast/slow); large errors may be fixed by stepping, which can move the clock backwards.
- Leap seconds: historically inserted occasionally; big providers smear them over hours instead of stepping. Code that assumed "time never repeats" broke during the 2012 leap second.
- Pauses: a VM migration, a stop-the-world GC, or
SIGSTOPcan freeze a process for seconds. When it resumes, its notion of "now" is stale until it reads the clock again.
Wall clock vs monotonic clock
| Clock | Answers | Can jump backwards? | Comparable across machines? | Use for |
|---|---|---|---|---|
| Wall clock (time-of-day) | "What time is it?" | Yes (NTP step, manual change) | Only approximately | Display, logs, business dates, token exp with skew allowance |
| Monotonic clock | "How much time has passed?" | No | No — meaningless across processes | Timeouts, latency, rate limiting, lease expiry checks |
Go makes this easy to get right: time.Now() carries both a wall and a monotonic reading, and time.Since, t.Sub(u) and context.WithTimeout use the monotonic part. The monotonic reading is stripped when you serialize the time, call t.Round(0), or send it to another process — at which point you only have wall time.
start := time.Now()
resp, err := client.Do(req)
elapsed := time.Since(start) // monotonic: safe even if NTP steps the clock now
Happens-before
Lamport (1978) defined happens-before (→): a → b if a and b are on the same process and a came first, or a is sending a message and b is receiving it, or by transitivity. If neither a → b nor b → a, the events are concurrent — not "simultaneous", just causally unrelated. Distributed ordering is about this partial order, not wall time.
Lamport clocks
Each process keeps a counter:
- Increment before each local event or send; attach the counter to messages.
- On receive:
counter = max(local, received) + 1.
Guarantee: if a → b then L(a) < L(b). Tie-breaking by node ID gives a total order consistent with causality. Limitation: the converse does not hold — L(a) < L(b) does not mean a caused b. Above, the order-note update at A (L=3) and the ledger post at C (L=5) are concurrent, but their Lamport values suggest an order.
Vector clocks
Each process keeps a vector with one counter per process. Increment your own entry on each event; on receive, take the element-wise maximum, then increment your own. Compare two vectors:
V(a) ≤ V(b)element-wise (and not equal) →a → b.- Neither dominates → concurrent.
That ability to detect concurrency is why Dynamo-style stores use version vectors: when two replicas accepted concurrent writes to a cart, the store keeps both "siblings" and lets the application merge them instead of silently dropping one. Cost: the vector grows with the number of writers, so systems prune it or use variants such as dotted version vectors.
Hybrid logical clocks
HLC (Kulkarni et al., 2014) keeps a timestamp (wall, logical):
walltracks the largest physical time seen, either from the local clock or from received messages.logicalbreaks ties and preserves causality whenwalldoes not advance.
The result stays within the clock-skew bound of real time (so it is meaningful to humans and usable for "read as of 10:42"), fits in 64 bits in practice, and still guarantees a → b implies HLC(a) < HLC(b).
package hlc
import "sync"
type Timestamp struct {
Wall int64 // nanoseconds since epoch
Logical uint32
}
func (t Timestamp) Less(u Timestamp) bool {
return t.Wall < u.Wall || (t.Wall == u.Wall && t.Logical < u.Logical)
}
type Clock struct {
mu sync.Mutex
last Timestamp
physNow func() int64 // e.g. func() int64 { return time.Now().UnixNano() }
}
// Now is called for local events and before sending a message.
func (c *Clock) Now() Timestamp {
c.mu.Lock()
defer c.mu.Unlock()
if pt := c.physNow(); pt > c.last.Wall {
c.last = Timestamp{Wall: pt}
} else {
c.last.Logical++
}
return c.last
}
// Update is called when a message carrying remote is received.
func (c *Clock) Update(remote Timestamp) Timestamp {
c.mu.Lock()
defer c.mu.Unlock()
pt := c.physNow()
switch {
case pt > c.last.Wall && pt > remote.Wall:
c.last = Timestamp{Wall: pt}
case remote.Wall > c.last.Wall:
c.last = Timestamp{Wall: remote.Wall, Logical: remote.Logical + 1}
case c.last.Wall > remote.Wall:
c.last.Logical++
default: // equal wall components
c.last.Logical = max(c.last.Logical, remote.Logical) + 1
}
return c.last
}
Production implementations also reject remote timestamps too far in the future (a node with a broken clock should not drag everyone forward). CockroachDB, for example, enforces a configured maximum clock offset and shuts down a node whose clock drifts beyond it; reads that fall inside the uncertainty window may be restarted at a higher timestamp.
TrueTime and commit wait
Google's Spanner does not pretend clocks are exact. Its TrueTime API returns an interval [earliest, latest] guaranteed to contain true time, backed by GPS receivers and atomic clocks in each data center. The uncertainty ε was reported as typically a few milliseconds in the 2012 paper.
To commit a transaction, the leader picks timestamp s ≥ TT.now().latest, then waits until TT.now().earliest > s before making the commit visible. After the wait, s is definitely in the past on every clock, so any transaction that starts later — anywhere in the world — gets a larger timestamp. That gives external consistency (strict serializability) using timestamps, at the cost of roughly 2ε of extra latency per commit.
The lesson for non-Google systems: if you rely on time for correctness, you need a bound on clock error and you must wait it out or detect violations. That is what leases do implicitly.
Fencing tokens
A lease ("you hold the lock until 10:00:30") assumes the holder notices expiry in time. A GC pause or clock jump breaks that assumption: the old holder wakes up believing it still holds the lease and writes. The fix, popularized by Martin Kleppmann, is to make the storage layer enforce order:
The token must increase monotonically with each grant (etcd revisions and ZooKeeper zxids do). The storage keeps the highest token seen per resource and rejects anything lower — typically a conditional update WHERE fence_token < $new. Details in Distributed Locks & Leases.
Ordering events in payments
A card payment produces events from many sources: your checkout, the payment service, the PSP's webhooks, the ledger, the settlement file. They arrive late, duplicated and out of order. Practical rules:
- One authority per sequence. The ledger assigns a gapless, per-account sequence number to each entry (
UNIQUE (account_id, seq)); balances and statements are ordered by that, never by timestamps from different services. - Partition by entity. Publish payment events keyed by
payment_id(oraccount_id) so a single Kafka partition preserves their order — see Message Queues & Event Streaming. - State machines, not "last event wins". A payment moves
CREATED → AUTHORIZED → CAPTURED → REFUNDED. Ifcapturedarrives beforeauthorized, the state machine either accepts the forward jump (if it is valid) or parks the event; a lateauthorizedafterCAPTUREDis a no-op, not a regression. See Order Management & State Machines. - Version every aggregate. Store
versionon the payment row and apply updates withWHERE version = $expected, so concurrent handlers cannot overwrite each other. - Treat webhooks as hints. Many PSPs explicitly do not guarantee webhook ordering; on receipt, fetch the current state from the PSP API (or compare the event's own sequence/created field) rather than trusting arrival order.
- Separate business time from system time. Booking date, value date and event time are business facts recorded explicitly; ingestion time is metadata. Stream processing uses event time with watermarks for windows (see Batch & Stream Processing).
- One clock for cut-offs. Decide "is this transfer before the 17:00 cut-off" in one place (for example the ledger database's
now()), not in each service. - Never trust client device time for anything that affects money or limits.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Wall-clock timestamps | Human-readable, free | Skew, jumps, no causality; LWW loses writes | Logs, display, coarse business times with tolerance |
| Lamport clock | Tiny; total order consistent with causality | Can't detect concurrency | Ordering operations in a log, tie-breaking, simple replication |
| Vector / version vectors | Detect concurrency precisely | Size grows with writers; pruning complexity | Multi-writer replicas that must merge siblings (carts, CRDT stores) |
| Hybrid logical clock | Close to wall time, causal, compact | Still depends on bounded skew for real-time claims | Distributed databases, snapshot reads "as of time T" |
| TrueTime-style intervals | Real-time ordering across the globe | Needs specialized time infrastructure; commit wait latency | Global strict serializability (Spanner) |
| Per-entity sequence numbers | Simple, exact, auditable | Needs a single writer per entity | Ledgers, payment state, order lifecycle |
In practice
- Run a proper time daemon (chrony is the common default on modern Linux) against reliable sources, and alert on offset. Many teams page if offset exceeds a few tens of milliseconds, because leases and token expiries depend on it.
- Allow skew in token validation. JWT
exp/nbfchecks usually allow a small leeway (≈ 30–60 s is common) because issuer and verifier clocks differ. - Database time as the reference. For a single database, use its
now()/clock_timestamp()for business timestamps inside transactions so all rows written by different app hosts share one clock. - Snowflake-style IDs embed a millisecond timestamp, so they are roughly time-ordered, but IDs from different generators are not causally ordered and clock steps can produce out-of-order or (if unhandled) duplicate IDs — see Unique ID Generation.
- CockroachDB's max offset: nodes compare clocks and a node whose offset exceeds the configured limit (500 ms by default in many versions) removes itself rather than risk anomalies. Check your version's docs.
- Correlating logs: prefer trace IDs and causal links (see Observability & SLOs) over sorting by timestamp across hosts.
Common pitfalls
- Measuring timeouts with wall time.
deadline := time.Now().Unix() + 30then comparingUnix()later. An NTP step backward extends the timeout; forward expires it early. Symptom: leases or locks that occasionally last far too long or too short. - LWW across hosts for important data. Symptom: settings or limits "revert", with no error logged.
- Sorting a distributed audit trail by timestamp. Symptom: an approval appears after the action it approved. Record causal references (the event ID it responds to) and per-entity sequences.
- Assuming webhooks arrive in order. Symptom: payments stuck in
AUTHORIZEDalthough the PSP shows them captured, because a lateauthorizedoverwrotecaptured. - Leases without fencing. Symptom: rare double processing after long GC pauses, impossible to reproduce on a laptop.
- Generating IDs from time without handling clock regression. Symptom: duplicate key errors right after an NTP step.
Interview angle
- Prompts: "Can you use timestamps to order transactions across services?" "How does Spanner get global consistency?" "How do you make a lease safe?" "Webhooks from the PSP arrive out of order — how do you handle them?"
- Strong answer pattern: clocks have bounded but non-zero error; use monotonic time locally, logical/hybrid clocks or per-entity sequences for ordering, and fencing tokens at the storage layer; if real-time ordering is required, you need explicit uncertainty bounds and to wait them out (TrueTime) or detect and retry (HLC with uncertainty intervals).
- Follow-ups: "What does a vector clock give you that Lamport doesn't?" (concurrency detection). "Why does Spanner's commit wait work?" "What happens to your rate limiter if the clock jumps?"
- Red flags: "we use NTP so clocks are synchronized"; ordering payment events by
created_atfrom different services; leases checked with wall-clock time and no fencing.
Self-check
1. Why can an NTP-synchronized cluster still produce wrong last-writer-wins outcomes?
NTP only bounds skew approximately (milliseconds or more), and it can step clocks backwards. Two writes milliseconds apart on different hosts can therefore carry timestamps in the wrong order, and LWW silently keeps the causally older one. Without a bound and a mechanism to respect it, timestamps cannot order close events across machines.
2. What does a Lamport clock guarantee, and what can it not tell you?
If a happened before b, then L(a) < L(b), and with a node-ID tie-break you get a total order consistent with causality. It cannot tell you whether two events with different values were causally related or concurrent; for that you need vector clocks.
3. How does Spanner's commit wait guarantee that a later transaction gets a larger timestamp?
The leader picks a commit timestamp at or after TT.now().latest and waits until TT.now().earliest exceeds it before making the commit visible. At that point the timestamp is guaranteed to be in the past for every correct clock, so any transaction that starts afterwards, anywhere, picks a larger timestamp. The cost is roughly twice the clock uncertainty in commit latency.
4. Why is a hybrid logical clock preferable to a pure Lamport clock in a database?
HLC timestamps stay close to physical time, so they can serve "as of" reads, TTLs and human interpretation, while still guaranteeing that causally later events get larger timestamps. A Lamport counter has no relation to real time, so you could not ask for "the state at 10:42".
5. Scenario: a PSP sends payment.captured and then, 3 seconds later, a delayed payment.authorized for the same payment. Your handler sets status from the event type. What happens and how do you fix it?
The payment regresses from CAPTURED to AUTHORIZED, blocking fulfilment or triggering a second capture. Fix with a state machine that only allows forward transitions (a late authorized after CAPTURED is a no-op), deduplicate by event ID, apply updates with optimistic versioning, and on doubt fetch the payment's current state from the PSP API rather than trusting arrival order.
6. Why must fencing tokens be checked by the storage layer rather than by the lock holder?
The holder is exactly the component that may be wrong about whether it still holds the lease — it may have been paused or its clock may have jumped. Only the resource being protected sees the writes in their actual order, so it must remember the highest token and reject lower ones.
Exercise
Build a tiny event-ordering lab in Go:
- Implement the
hlc.Clockabove and a vector clock type withMerge,IncrementandCompare(returning before, after, equal, concurrent). - Simulate three services exchanging messages with random delays and per-service clock offsets (e.g., −50 ms, 0, +120 ms). Record every event with wall time, Lamport, vector and HLC values.
- Show at least one pair where wall-clock order contradicts causality, one pair Lamport orders but vector clocks mark concurrent, and verify HLC never contradicts causality.
- Write a payment-status state machine that consumes a shuffled, duplicated stream of PSP events and always ends in the correct final state.
Done when: your test suite fails if you replace the HLC with raw wall time, and the state machine passes 10,000 randomized shuffles.
Further reading
- Leslie Lamport, "Time, Clocks, and the Ordering of Events in a Distributed System" (CACM, 1978).
- Colin Fidge (1988) and Friedemann Mattern (1988) — independent introductions of vector clocks.
- Sandeep Kulkarni et al., "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases" (2014) — HLC.
- James Corbett et al., "Spanner: Google's Globally-Distributed Database" (OSDI 2012).
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 8 "The Trouble with Distributed Systems".
- Martin Kleppmann, "How to do distributed locking" (blog, 2016) — fencing tokens.
- Go documentation, package
time: "Monotonic Clocks".
Related
- Distributed Locks & Leases — leases and fencing in depth.
- Consistency Models — causal consistency builds on happens-before.
- Consensus & Raft — terms as logical time; lease reads.
- Idempotency & Exactly-Once — handling duplicate events.
- Unique ID Generation — time-based IDs and clock regression.
- Payments & Card Flows — the event sources you must order.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).