DS·75
Time and Ordering
Clocks and order in distributed systems: how physical clocks drift, NTP and PTP synchronisation, leap seconds and smearing, wall-clock versus monotonic time in C, C++, Java, Go, Rust, Zig and Python, clock skew and its consequences, Lamport clocks, vector clocks, hybrid logical clocks, TrueTime and commit-wait, bounded-uncertainty clocks, time-ordered IDs (Snowflake, UUIDv7, ULID), and event time versus processing time with watermarks and late data in stream processing.
Start here: why "what time is it?" is a hard question
Every machine has its own clock, and it's wrong
A server's clock is a quartz oscillator that drifts (typically tens of microseconds per second) and is corrected by NTP or PTP. Over the internet NTP usually keeps clocks within a few milliseconds; a misconfigured or overloaded machine can be off by seconds, and corrections can step the clock backwards or forwards. So two timestamps taken on two machines can't reliably tell you which event came first. Watch a conversation stored by three servers whose clocks are off by 0, −40 and +25 ms:
1) A chat, each message sent 10 ms after reading the previous one; servers' clocks off by 0, −40 and +25 ms
sorted by server wall-clock timestamp:
980 ms Ravi: Yes, from 7 am.
1000 ms Ravi: See you there.
1010 ms Asha: Is the dosa place open on Mondays?
1055 ms Meena: Thanks! Booking for 8.
sorted by Lamport timestamp:
L=1 Asha: Is the dosa place open on Mondays?
L=2 Ravi: Yes, from 7 am.
L=3 Meena: Thanks! Booking for 8.
L=4 Ravi: See you there.
Sorted by timestamps, answers come before the question. Errors of a few tens of milliseconds, which are normal, were enough.
Two clocks in every computer
Every OS gives you a wall clock (System.currentTimeMillis(), time.time(), Date.now()): the time of day, which can jump when corrected. And a monotonic clock (System.nanoTime(), time.monotonic(), performance.now()): it never goes backwards, but means nothing across machines or reboots.
a 1-second task timed with the wall clock: -3.995 s | with the monotonic clock: 1.005 s
That's a real measurement: the clock was stepped back 5 seconds during a 1-second task. Measure durations and timeouts with the monotonic clock; use the wall clock only to display or record the time of day.
Logical clocks: order without trusting time
Leslie Lamport's 1978 insight: what usually matters is causality (could event A have influenced B?), not the time of day. A Lamport clock is a counter: increment it on every event, send it with every message, and on receipt set it to max(mine, received) + 1. If A caused B, A's number is smaller, so sorting by it never puts a reply before its question. Lamport clocks can't tell you whether two events were concurrent. Vector clocks can, by keeping one counter per node:
2) vector clocks: Asha's edit {'asha': 1} vs Ravi's {'ravi': 1, 'asha': 1} → before
Ravi's {'ravi': 1, 'asha': 1} vs Meena's {'meena': 1, 'asha': 1} → concurrent (a real conflict to resolve, not a clock accident)
Ravi's edit happened after seeing Asha's, so it simply supersedes it. Ravi's and Meena's edits were made without seeing each other: neither vector is ≤ the other, so they're concurrent, and the system knows it must merge or ask, instead of letting a clock pick a winner (chapter 71's LWW losses). Hybrid logical clocks (HLC, used by CockroachDB, YugabyteDB and MongoDB) combine a physical time with a logical counter: close to real time, and never violating causality (the lab tests one).
How deep to go in time and ordering
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain clock skew, wall versus monotonic clocks, and causal order |
| L2 | Use monotonic clocks for durations, UTC for storage, and logical versions for ordering |
| L3 | Explain Lamport, vector, hybrid logical clocks and TrueTime; event time and watermarks |
| L4 | Diagnose bugs from clock steps, skew, leap seconds, ID collisions and late events |
| L5 | Design ordering, ID generation and time semantics for a system |
| L6 | Operate time infrastructure (NTP/PTP, chrony, clock-bound) and set organisation-wide policies |
Physical clocks
How computers keep time
Each machine has a quartz oscillator that ticks at a nominal frequency; the OS counts ticks to keep time. Quartz frequency varies with temperature and age, so clocks drift: a typical drift of 10–100 ppm means 1–9 seconds per day. Two unsynchronised machines diverge quickly.
Terms:
- Skew (offset): the difference between two clocks' readings at the same instant.
- Drift: the rate at which a clock gains or loses relative to true time.
- Resolution: smallest increment the clock can report; precision: how consistent readings are; accuracy: closeness to true (UTC) time.
NTP
The Network Time Protocol synchronises clocks over the network. Servers form a hierarchy of strata: stratum 0 is a reference clock (GPS, atomic), stratum 1 servers connect to them directly, stratum 2 sync from stratum 1, and so on.
A client estimates offset from four timestamps: client send t0, server receive t1, server send t2, client receive t3:
- Round-trip delay δ = (t3 − t0) − (t2 − t1)
- Offset θ = ((t1 − t0) + (t2 − t3)) / 2
This assumes symmetric network paths; asymmetry (one direction slower) shows up as error of up to half the asymmetry. NTP filters many samples and picks good servers.
Accuracy: sub-millisecond within a good datacentre network; a few to tens of milliseconds over the internet; worse under congestion. Implementations: chronyd (the modern default on most Linux distributions), ntpd, systemd-timesyncd (simple client). Cloud providers offer local time services (Amazon Time Sync Service, Google's metadata NTP), some with PTP hardware clocks on instances giving microsecond accuracy.
PTP (Precision Time Protocol, IEEE 1588) uses hardware timestamping in NICs and switches to reach sub-microsecond accuracy. It's used in finance (regulations such as MiFID II require traceable timestamps), telecoms, and increasingly in cloud datacentres.
How the clock is corrected
When NTP finds the clock is off, it can:
- Slew: speed up or slow down the clock slightly (up to 500 ppm in classic NTP) until corrected. Time stays monotonic but correction is slow.
- Step: jump the clock to the correct time. Fast, but time can jump backwards.
Typical setups slew small offsets and step large ones (e.g. at boot). Other causes of jumps: VM migration and resume, a user or script setting the time, a misconfigured NTP server.
Leap seconds
UTC occasionally inserts a leap second (23:59:60) to stay within 0.9 s of Earth's rotation. Systems have crashed on leap seconds (the 2012 Linux kernel livelock affecting many Java and MySQL processes). Approaches:
- Leap smearing: Google, AWS, Meta and others spread the extra second over a period (e.g. 24 hours) by slewing, so clocks never show 23:59:60. Mixing smeared and unsmeared time sources gives up to 0.5 s disagreements.
- In 2022 the General Conference on Weights and Measures decided to abolish leap seconds by 2035. None has been inserted since 2016.
Wall-clock time versus monotonic time
Operating systems expose two kinds of clock:
| Wall clock (time-of-day, realtime) | Monotonic clock | |
|---|---|---|
| Meaning | Current date and time (UTC) | Time since some arbitrary point (often boot) |
| Can jump? | Yes: NTP steps, manual changes, leap handling | Never goes backwards (may be slewed by NTP but not stepped) |
| Comparable across machines? | Roughly (to within sync accuracy) | No: meaningless across machines or reboots |
| Use for | Timestamps shown to humans, log timestamps, expiry dates | Measuring durations: timeouts, latency, rate limiting, leases (locally) |
The classic bug: measuring elapsed time with the wall clock. If NTP steps the clock back during a request, "elapsed" becomes negative, and timeouts fire too early or never.
// C (POSIX): CLOCK_MONOTONIC for durations, CLOCK_REALTIME for wall time
#include <time.h>
struct timespec a, b, now;
clock_gettime(CLOCK_MONOTONIC, &a);
do_work();
clock_gettime(CLOCK_MONOTONIC, &b);
double ms = (b.tv_sec - a.tv_sec) * 1e3 + (b.tv_nsec - a.tv_nsec) / 1e6;
clock_gettime(CLOCK_REALTIME, &now); // wall time: may jump
// Linux also has CLOCK_BOOTTIME (includes suspend) and CLOCK_MONOTONIC_RAW (no NTP slewing)
// C++: steady_clock is monotonic; system_clock is wall time
auto t0 = std::chrono::steady_clock::now();
do_work();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0);
auto wall = std::chrono::system_clock::now(); // for timestamps
// Java: System.nanoTime() is monotonic (durations only); Instant.now()/currentTimeMillis() is wall time
long t0 = System.nanoTime();
doWork();
Duration elapsed = Duration.ofNanos(System.nanoTime() - t0);
Instant stamp = Instant.now(); // wall clock, for records shown to humans
// Inject java.time.Clock into services so tests can control time: Clock.fixed(...), Clock.offset(...)
// Go: time.Now() carries BOTH a wall reading and a monotonic reading;
// Sub/Since use the monotonic part automatically, so this is jump-safe
start := time.Now()
doWork()
elapsed := time.Since(start) // monotonic
stamp := time.Now().UTC().Round(0) // Round(0) strips the monotonic reading (e.g. before serialising)
// Rust: Instant is monotonic; SystemTime is wall time (and can fail if it goes backwards)
use std::time::{Instant, SystemTime, UNIX_EPOCH};
let start = Instant::now();
do_work();
let elapsed = start.elapsed();
let unix = SystemTime::now().duration_since(UNIX_EPOCH)?; // Err if the clock is before 1970
// Zig: std.time.Instant (monotonic) vs std.time.timestamp()/milliTimestamp() (wall)
const std = @import("std");
const start = try std.time.Instant.now();
doWork();
const now = try std.time.Instant.now();
const elapsed_ns = now.since(start);
const wall_ms = std.time.milliTimestamp();
# Python: time.monotonic() / perf_counter() for durations; time.time() / datetime.now(UTC) for wall time
import time, datetime
t0 = time.monotonic()
do_work()
elapsed = time.monotonic() - t0
stamp = datetime.datetime.now(datetime.UTC)
Clock skew and its consequences
Even with NTP, clocks on different nodes differ by milliseconds or more, and occasionally much more (a broken NTP config can leave a node minutes off). Consequences:
- Last-write-wins by timestamp discards the truly later write when the earlier writer's clock is ahead. Cassandra and DynamoDB global tables are exposed; a node with a fast clock "wins" every conflict.
- Event ordering across services by timestamp is wrong at fine granularity. Logs merged from many hosts can show an effect before its cause.
- Leases and locks: a lock holder thinks its lease is valid while the lock service already expired it (chapter 77).
- Snapshot reads at a timestamp may miss committed data if the reader's clock is behind.
- Certificate validation, token expiry (JWT
exp,nbf): allow a small clock skew leeway (typically 30–60 s).
Rule: never rely on wall clocks across nodes for correctness. Use them for display and approximate analytics; use logical ordering or bounded-uncertainty clocks for correctness.
Logical clocks
Lamport clocks
Leslie Lamport's 1978 paper "Time, Clocks, and the Ordering of Events in a Distributed System" is one of the most cited in computing. It defines happens-before (→, chapter 69) and a logical clock consistent with it.
Algorithm: each process keeps a counter C.
- Before each local event, C = C + 1.
- When sending a message, attach C (after incrementing).
- On receiving a message with timestamp T: C = max(C, T) + 1.
Property: if a → b then L(a) < L(b). The converse doesn't hold: L(a) < L(b) doesn't mean a happened before b; they may be concurrent.
Total order: break ties by process ID, (L, pid). All processes agree on this order, which is consistent with causality. Lamport used it to build a distributed mutual-exclusion algorithm, and it underlies many ordering schemes.
Vector clocks
To detect concurrency (not just order), use vector clocks (Fidge and Mattern, 1988). With n processes, each keeps a vector V of n counters.
- Local event at process i: V[i] += 1.
- Send: increment V[i], attach V.
- Receive message with vector W: V[j] = max(V[j], W[j]) for all j, then V[i] += 1.
Comparison:
- V(a) ≤ V(b) if every component of V(a) ≤ the corresponding one of V(b).
- a → b iff V(a) ≤ V(b) and V(a) ≠ V(b). Unlike Lamport clocks, this is an "if and only if".
- If neither ≤ the other, a and b are concurrent.
Costs: vectors grow with the number of processes (or clients). Variants: version vectors (per replica, for data versions, chapter 71), dotted version vectors (Riak), interval tree clocks (dynamic membership), and bounded or pruned vectors.
# Python: vector clock with happens-before / concurrent detection
class VClock:
def __init__(self, me: str, v: dict[str, int] | None = None):
self.me, self.v = me, dict(v or {})
def tick(self) -> dict[str, int]:
self.v[self.me] = self.v.get(self.me, 0) + 1
return dict(self.v) # attach to outgoing message
def receive(self, w: dict[str, int]) -> None:
for k, n in w.items():
self.v[k] = max(self.v.get(k, 0), n)
self.tick()
def happened_before(a: dict, b: dict) -> bool:
keys = a.keys() | b.keys()
return all(a.get(k, 0) <= b.get(k, 0) for k in keys) and a != b
def concurrent(a: dict, b: dict) -> bool:
return not happened_before(a, b) and not happened_before(b, a) and a != b
Hybrid logical clocks (HLC)
Logical clocks capture causality but have no relation to real time; physical clocks relate to real time but don't capture causality. Hybrid logical clocks (Kulkarni et al., 2014) combine both in a timestamp (l, c):
ltracks the maximum physical time seen (close to wall time, within the clock skew bound).cis a logical counter that breaks ties whenldoesn't advance.
Rules (simplified): on a local or send event, l' = max(l, pt); if l' equals the old l, increment c, else reset c to 0. On receive, take the max of local l, the message's l and physical time, and adjust c similarly.
Properties: if a → b then HLC(a) < HLC(b); HLC stays within the clock skew bound of physical time; it fits in 64 bits. Used by CockroachDB (transaction timestamps, plus an uncertainty interval of max clock offset, default 500 ms, within which reads restart), YugabyteDB, MongoDB (cluster time) and Couchbase.
// Go: a minimal hybrid logical clock
type HLC struct {
mu sync.Mutex
l int64 // physical component (ns)
c uint32 // logical component
}
func (h *HLC) Now() (int64, uint32) { // local or send event
h.mu.Lock(); defer h.mu.Unlock()
pt := time.Now().UnixNano()
if pt > h.l { h.l, h.c = pt, 0 } else { h.c++ }
return h.l, h.c
}
func (h *HLC) Update(ml int64, mc uint32) { // receive event
h.mu.Lock(); defer h.mu.Unlock()
pt := time.Now().UnixNano()
switch {
case pt > h.l && pt > ml: h.l, h.c = pt, 0
case ml > h.l: h.l, h.c = ml, mc+1
case h.l > ml: h.c++
default: if mc > h.c { h.c = mc }; h.c++ // h.l == ml
}
}
Bounded-uncertainty clocks
TrueTime and commit-wait
Google Spanner (2012) uses TrueTime, an API that returns an interval [earliest, latest] guaranteed to contain true time. GPS receivers and atomic clocks in each datacentre keep the uncertainty ε small (typically a few milliseconds, often under 1 ms in later reports).
To make transactions externally consistent (strictly serializable, chapter 69), Spanner:
- Picks commit timestamp s ≥ TT.now().latest.
- Commit-waits: doesn't make the commit visible until TT.now().earliest > s, about 2ε later.
After commit-wait, s is guaranteed to be in the past everywhere, so any transaction starting later anywhere gets a larger timestamp. The cost is waiting out the uncertainty on every write, so better clocks directly mean lower latency.
Other bounded clocks
- AWS ClockBound (with Amazon Time Sync Service and PTP hardware clocks): a daemon and client library returning
(earliest, latest)bounds, available to anyone on EC2. Amazon Aurora DSQL uses precise synchronised time for its distributed transactions. - CockroachDB: no specialised hardware; uses HLC plus a configured maximum clock offset, restarting reads that fall in the uncertainty window, and nodes shut themselves down if their clock drifts beyond the bound relative to peers.
- Meta's PTP rollout and Huygens-style software clock sync (Clockwork) reach sub-microsecond to tens-of-nanoseconds accuracy in datacentres.
Ordering without clocks
Sequence numbers from a single authority
The simplest total order comes from one sequencer: a partition leader assigns offsets (Kafka), a database primary assigns LSNs, a Raft log assigns indexes. Within its domain, ordering is free and exact. The trade-offs are throughput and availability limits of the single authority; hence per-partition or per-key sequencers.
Total-order broadcast across many nodes is equivalent to consensus (chapter 72).
Time-ordered identifiers
IDs that roughly sort by creation time help database index locality (B-tree inserts at the right edge, Vol. 4 ch. 58) and let you sort by ID:
| Format | Layout | Notes |
|---|---|---|
| Snowflake (Twitter, 2010) | 41-bit ms timestamp + 10-bit machine ID + 12-bit sequence, 64-bit | Needs unique machine IDs; ordering across machines only to clock accuracy |
| UUIDv7 (RFC 9562, 2024) | 48-bit Unix ms timestamp + random/counter bits, 128-bit | Standard, sortable; PostgreSQL 18 uuidv7(); good default primary key |
| ULID | 48-bit ms timestamp + 80 random bits, Crockford base32 string | Popular before UUIDv7 |
| KSUID | 32-bit seconds + 128 random bits | Coarser timestamp |
Caveat: these orders are only as good as the generators' clocks. Don't use ID order to infer causality across machines; use them for locality and approximate ordering.
Event time versus processing time
Two clocks in stream processing
In stream processing (Kafka Streams, Flink, Beam, Spark Structured Streaming), every event has:
- Event time: when the event actually happened (set at the source: the phone tap, the sensor reading).
- Ingestion time: when it entered the pipeline (broker append time).
- Processing time: when the processor handles it.
They differ due to network delays, offline devices uploading hours later, backpressure, retries, and replays (reprocessing last month's data in an hour). Aggregating by processing time gives results that depend on when you ran the job; aggregating by event time gives correct, reproducible results, but you must decide when a window is complete.
Watermarks, windows and late data
- Windows: tumbling (fixed, non-overlapping: per 5 minutes), hopping/sliding (overlapping: 10-minute windows every minute), session (bursts separated by inactivity gaps).
- A watermark W(t) asserts "all events with event time ≤ t have probably arrived". It's a heuristic: typically max event time seen minus a bounded out-of-orderness (e.g. 30 s), or per-source tracking. When the watermark passes a window's end, the window fires.
- Late data (arriving after the watermark): drop it, send it to a side output, or update the result if within allowed lateness (emit refinements). Downstream must handle updated results (upserts).
- Trade-off: a conservative watermark waits longer (higher latency, fewer late events); an aggressive one is faster but marks more events late.
// Java: Flink event-time windowing with bounded out-of-orderness and allowed lateness
DataStream<Click> clicks = env.fromSource(kafkaSource,
WatermarkStrategy.<Click>forBoundedOutOfOrderness(Duration.ofSeconds(30))
.withTimestampAssigner((c, ts) -> c.eventTimeMillis())
.withIdleness(Duration.ofMinutes(1)), // idle partitions don't stall the watermark
"clicks");
OutputTag<Click> late = new OutputTag<>("late") {};
var counts = clicks
.keyBy(Click::pageId)
.window(TumblingEventTimeWindows.of(Duration.ofMinutes(5)))
.allowedLateness(Duration.ofMinutes(10)) // re-emit updated counts for late events
.sideOutputLateData(late) // anything later still goes here
.aggregate(new CountAgg());
Kafka Streams uses grace periods on windows (TimeWindows.ofSizeAndGrace(...)) and stream time (max event time seen per partition); Apache Beam's model (from Google's Dataflow paper, 2015) formalised what is computed, where in event time, when in processing time (triggers), and how refinements relate (accumulating or discarding).
Lab: clocks that jump, and clocks that don't matter
Python 3.13 on Linux. Experiments 2 and 3 really step this machine's clock with date -s while the program runs (and step it back afterwards); don't do this on a machine running anything else that cares about time. Experiments 4 and 5 are simulations with stated clock errors and delays.
Experiment 1: reading clocks is cheap
One million calls each:
time.time_ns() (wall) : 87 ns per call
time.monotonic_ns() : 80 ns per call
time.perf_counter_ns() : 88 ns per call
On Linux, both clocks are read through the vDSO without a system call (around 20 ns in C or Java; most of the 80 ns here is Python's function call). There's no performance reason to prefer the wall clock for durations.
Experiment 2: a timeout written with the wrong clock
A loop waits up to 2 seconds; 0.3 s in, the clock is stepped forward 10 s (as when NTP corrects a machine that booted with a wrong time, or a VM resumes from a pause):
measured with the wall clock: fired after 0.31 s
measured with the monotonic clock: fired after 2.01 s
The wall-clock timeout fired immediately: from its point of view 10.3 s had passed. Stepped backwards, it would wait far too long. The same bug affects lease expiry, cache TTLs, rate-limit windows and retry backoff if they're computed with currentTimeMillis. The reliable rule is nanoTime/monotonic for every duration, and code review that treats currentTimeMillis() arithmetic as a smell.
Experiment 3: time-ordered IDs when the clock goes backwards
A Snowflake-style generator (milliseconds shifted left 12 bits, plus a 12-bit sequence) produced 20,000 IDs; halfway through the clock was stepped back 1 second:
no guard: 29 duplicate IDs, 2 out-of-order IDs
guard (never go backwards): 0 duplicate IDs, 0 out-of-order IDs
Going back in time reused milliseconds the generator had already issued, so sequence numbers repeated: 29 IDs collided, which as primary keys means failed inserts or, worse, overwritten rows. The guard remembered the last millisecond, kept issuing from it (borrowing future milliseconds when the sequence ran out) until the clock caught up. Twitter's Snowflake refuses to generate IDs while the clock is behind; UUIDv7 implementations (RFC 9562) use the same "monotonic counter within a millisecond" technique.
Experiment 4: hybrid logical clocks under skew
3,000 messages between three nodes whose clocks are off by 0, −50 and +30 ms; network delays 0.2–2 ms:
physical timestamps: 1509 receives stamped before their send
hybrid logical clock: 0 violations; HLC ran at most 30 ms ahead of true time
With raw clocks, half of all receives looked earlier than the send that caused them. The HLC takes the maximum of its own physical time, its last value and the message's timestamp, adding a logical counter on ties, so causality was never violated, and the timestamps never ran ahead of real time by more than the largest clock error. CockroachDB relies on this, plus a configured --max-offset (500 ms by default), beyond which a node shuts itself down.
Experiment 5: event time, watermarks and late data
20,000 events (one every 3 ms of event time); most arrive within about 0.2 s, but 2% arrive 5–30 s late (phones that were offline). Results are computed in 10-second event-time windows, closed when the watermark passes them:
watermark = arrival − 0.5 s: 418 late events (2.1%), each window's result delayed ≥ 0.5 s
watermark = arrival − 2.0 s: 365 late events (1.8%), each window's result delayed ≥ 2.0 s
watermark = arrival − 10.0 s: 231 late events (1.2%), each window's result delayed ≥ 10 s
Waiting longer caught more stragglers but made every result later, and a 30-second straggler beats any reasonable wait. Stream processors (Flink, Beam, Kafka Streams) therefore separate event time (when it happened) from processing time (when you saw it), use watermarks to decide when a window is probably complete, and add allowed lateness with updated results, or a side output for very late data.
Try it yourself
- Step the clock back during experiment 2 and measure how long the wall-clock timeout waits.
- Run
chronyc tracking(install chrony) and read the offset, frequency error and root dispersion of your machine. - Implement a version vector store for chapter 71's experiment 3 and count conflicts detected instead of writes lost.
- Generate UUIDv7 values with a library in your language and step the clock back. Does it keep them ordered?
Revision sheet: time and ordering
Key ideas
- Physical clocks: quartz drift, NTP (ms over the internet), PTP (µs on LANs), steps vs slews, leap seconds and smearing, VM pauses.
- Wall vs monotonic: wall for time of day (store UTC), monotonic for durations, timeouts, leases and rate limits.
- Skew consequences: LWW losses, wrong ordering, expired-early leases, duplicate time-based IDs, broken TTLs.
- Logical clocks: Lamport (happened-before ⇒ smaller), vector clocks (detect concurrency), version vectors and dotted version vectors for replicas.
- Bounded uncertainty: TrueTime intervals and commit wait (Spanner); AWS ClockBound; HLC with max offset (CockroachDB).
- Ordering without clocks: sequence numbers from a single leader, consensus logs, per-partition offsets, causal tokens.
- Event time: event vs processing time, windows (tumbling, sliding, session), watermarks, allowed lateness, triggers.
- IDs: Snowflake, ULID, UUIDv7 (RFC 9562) with monotonic guards.
Numbers to remember
- NTP: a few ms over the internet; CockroachDB max offset 500 ms; Snowflake: 41-bit ms, 10-bit node, 12-bit sequence.
- Lab: clock reads ~80 ns in Python; a wall-clock timeout fired after 0.31 s instead of 2 s; a 1 s backward step made 29 duplicate IDs; HLC 0 causality violations vs 1,509 with raw clocks; a 10 s watermark still left 1.2% late events.
Pitfalls
currentTimeMillis()for durations.- Local time zones in stored timestamps.
- Ordering cross-server events by timestamp.
- ID generators without a backwards-clock guard.
- Lease logic assuming clocks agree.
- Windows on processing time when results must reflect event time.
Glossary
- Clock skew: difference between two clocks' readings.
- Drift: rate at which a clock gains or loses time.
- Monotonic clock: never decreases; for intervals.
- Happened-before: Lamport's causal partial order.
- Watermark: a stream's estimate that no earlier events remain.
- HLC: hybrid logical clock (physical + logical components).