Two questions sound simple and are not: when did this happen, and in what order? Every machine has its own clock, and clocks drift, get stepped backwards, and disagree, so ordering events by their timestamps can put "delivered" before "out for delivery". This lesson separates the clocks you have (the wall clock, which says what time it is, and the monotonic clock, which measures how long something took), the clocks you can build (Lamport, vector, and hybrid logical clocks, which record what caused what), and the IDs made from them (UUIDv7 and Snowflake-style IDs, which sort by time). It follows one parcel scan from a van whose clock is 90 seconds slow, with two failures: events ordered by wall clock, and an ID generator whose clock was stepped back.
Difficulty: Advanced · Know this first: Lesson 65, Lesson 78
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up milliseconds from the scan to the tracking page. It is a worked example, not a measurement. The time hardly changes between the scenarios: what changes is whether the order and the IDs are right.
The van's handheld clock may be slow, the tracking service may sort by wall clock or by hybrid clock, and events may get different kinds of ID. See what the customer sees, and what the IDs do to the index.
Three questions. No score is saved anywhere — this is just you against the material.
Handling time grows in four levels: using the right clock, ordering by causality, making IDs that sort and stay unique, and treating time as a monitored dependency.
At the basic level every program reads the clock that fits the question.
Where it breaks: a timeout computed from the wall clock fires early or never when the clock is stepped.
Try it: Basic
A job measures its run time as end wall time minus start wall time, and once reported -3 seconds. Why?
Now do it: Find one duration in your code measured with time.time() and switch it to time.monotonic().
At the intermediate level order comes from what caused what, not from timestamps.
Try it: Intermediate
Event A has Lamport time 5 and event B has 7. What can you conclude?
Now do it: Run the lesson's program and change the van's skew to +90 s; watch both orders.
At the advanced level IDs are made anywhere, sort by time, and never repeat.
Try it: Advanced
NTP steps the clock of the ID service back 2 seconds, to correct a clock that ran fast. What should a Snowflake-style generator do?
Now do it: Read the guard in the lesson's program and remove it; count the duplicates.
At the master level clock error is measured, bounded, and designed for.
Trade-off: hybrid clocks and guards add a little code and a counter; trusting wall clocks costs nothing until the first clock drifts.
Try it: Master
A leader holds a 10-second lease, and its clock runs 2% fast compared to the others. What should the lease design include?
Now do it: Write down the maximum clock drift your leases assume.
The three logical clocks, as rules. Lamport: on each local event or send, c = c + 1; on receive, c = max(c, received) + 1. Vector: each node increments its own entry on each event; on receive, take the element-wise maximum, then increment your own entry; a happened before b if every entry of a is less than or equal to b's and they differ, and two vectors where neither holds are concurrent. Hybrid logical clock (Kulkarni et al., 2014), with l the largest wall time seen and c a counter:
def send_or_local(pt): # pt: this machine's wall clock now
global l, c
old = l
l = max(old, pt)
c = c + 1 if l == old else 0
return (l, c)
def receive(pt, lm, cm): # (lm, cm): the timestamp on the message
global l, c
old = l
l = max(old, lm, pt)
if l == old == lm:
c = max(c, cm) + 1
elif l == old:
c = c + 1
elif l == lm:
c = cm + 1
else:
c = 0
return (l, c)
The right clock in Python, and a UUIDv7 (Python 3.14 and later; in PostgreSQL 18, SELECT uuidv7()):
import time, uuid deadline = time.monotonic() + 30 # timeouts and durations: monotonic started_at = time.time() # "when": wall clock, seconds since 1970 in UTC event_id = uuid.uuid7() # 48 bits of milliseconds, then a counter and random bits made_ms = event_id.int >> 80 # the time is inside the ID: anyone who sees it can read it
Watching the clocks: on a Linux host, chronyc tracking shows how far the system clock is from the time server ("System time … seconds slow of NTP time"), and timedatectl show -p NTPSynchronized whether it is synchronised. Prometheus's node_exporter exports node_timex_offset_seconds and node_timex_sync_status; alert when the absolute offset goes over a limit you choose (say 50 ms) or sync is lost. Devices in vans and depots need the same, reported with every batch of events.
Leap seconds: the time services of Google and AWS smear a leap second over many hours instead of repeating a second, and the international standards body decided in 2022 to stop adding leap seconds by 2035. Until then, mixing smeared and unsmeared time servers on the same machines produces offsets of up to a second.
Other ID schemes you will meet: ULID (48 bits of milliseconds and 80 random bits, written as 26 characters that sort as text), database sequences (ordered and compact, but a single point of coordination and easy to guess), and Snowflake variants at Twitter, Discord, and Instagram, which differ in epoch and bit widths.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The parcel that came back.
Events carry hybrid logical clock timestamps, merged when a handheld downloads its manifest; ordering and status use them, never device wall time; devices report their clock offset with every batch and alert above 5 seconds; the ID service got a guard against clocks going backwards; and status fields resolved by last-writer-wins were listed and reviewed.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: Linux with Python 3.14 or later (uuid.uuid7() arrived in 3.14; on older Python, step 5 fails with an AttributeError and the rest still works).
Type each one, read what it prints, and compare it with the note above it.
Make a practice folder, and look at the two clocks every Linux machine has: the wall clock, which says what time it is and can be adjusted, and the monotonic clock, which only counts up from boot.
mkdir -p ~/labs/clocks && cd ~/labs/clocks
date -u '+wall clock (UTC): %Y-%m-%d %H:%M:%S.%N'
awk '{print "monotonic clock: " $1 " s since boot"}' /proc/uptime
timedatectl show -p NTPSynchronized 2>/dev/null || echo "no timedatectl here (a container, or WSL without systemd)"Ask Python which system clock each of its clock functions reads, and whether that clock can be adjusted.
python3 -c "import time
for name in ('time', 'monotonic'):
i = time.get_clock_info(name)
print(f'{name:<9} {i.implementation:<34} adjustable={i.adjustable} monotonic={i.monotonic}')"Measure a duration the right way, with the monotonic clock: a wall-clock step in the middle cannot make it negative.
python3 -c "import time
t0 = time.monotonic(); time.sleep(0.25)
print(f'slept {time.monotonic() - t0:.2f} s, measured on the monotonic clock')"Make a UUIDv7 and read the time back out of it: its first 48 bits are milliseconds since 1970.
python3 -c "import uuid, datetime
u = uuid.uuid7()
print(u, 'version', u.version)
print('made at', datetime.datetime.fromtimestamp((u.int >> 80) / 1000, datetime.UTC).isoformat(timespec='milliseconds'))"Make 100,000 of each kind and check whether sorting them gives back the order they were made in.
python3 -c "import uuid
v7 = [uuid.uuid7() for _ in range(100000)]
v4 = [uuid.uuid4() for _ in range(100000)]
print('uuid7 sorts in creation order:', v7 == sorted(v7))
print('uuid4 sorts in creation order:', v4 == sorted(v4))"Build and take apart a Snowflake-style 64-bit ID with shell arithmetic: 41 bits of milliseconds since a chosen epoch, 10 bits of machine, 12 bits of sequence.
EPOCH=1288834974657 id=$(( ((1796090298620 - EPOCH) << 22) | (17 << 12) | 5 )); echo "id: $id" echo "ms: $(( (id >> 22) + EPOCH )), machine: $(( (id >> 12) & 1023 )), sequence: $(( id & 4095 ))"
Clean up.
cd ~ && rm -rf ~/labs/clocks ls ~/labs
clocks_and_ids.pyThis program replays the lesson's story and its failures without a network: a depot and a van whose clock runs 90 seconds slow, ordered by wall clock and by a hybrid logical clock (with last-writer-wins on both); two depots editing the same address, compared with vector clocks; a Snowflake-style ID generator whose clock is stepped back, with and without a guard; UUIDv7s built by hand from the RFC 9562 layout, with and without a counter; and how full B-tree leaf pages end up under random and time-ordered keys. Save it as clocks_and_ids.py, then run it.
# clocks_and_ids.py
import bisect
import random
import uuid
random.seed(7)
def hms(s): # seconds since midnight -> "10:41:30"
return f"{s // 3600:02d}:{s // 60 % 60:02d}:{s % 60:02d}"
class HLC: # hybrid logical clock (Kulkarni et al., 2014)
def __init__(self, skew):
self.skew, self.l, self.c = skew, 0, 0
def now(self, true_time): # a local event or a send
pt, old = true_time + self.skew, self.l
self.l = max(old, pt)
self.c = self.c + 1 if self.l == old else 0
return (self.l, self.c)
def receive(self, true_time, msg): # merge the sender's timestamp
pt, old, (lm, cm) = true_time + self.skew, self.l, msg
self.l = max(old, lm, pt)
if self.l == old == lm:
self.c = max(self.c, cm) + 1
elif self.l == old:
self.c += 1
elif self.l == lm:
self.c = cm + 1
else:
self.c = 0
return (self.l, self.c)
depot, van = HLC(skew=0), HLC(skew=-90) # the van's handheld runs 90 s slow
T = 10 * 3600 + 41 * 60 + 30 # 10:41:30, true time
events = []
stamp = depot.now(T)
events.append(("depot", "out for delivery", T + depot.skew, stamp))
van.receive(T + 10, stamp) # the handheld downloads its manifest
events.append(("van", "delivered", T + 65 + van.skew, van.now(T + 65)))
print("order by wall clock: ", " -> ".join(e[1] for e in sorted(events, key=lambda e: e[2])))
print("order by hybrid clock:", " -> ".join(e[1] for e in sorted(events, key=lambda e: e[3])))
for who, what, wall, (l, c) in events:
print(f" {what:<17} wall {hms(wall)} hybrid ({hms(l)}, {c}) from the {who}")
lww_wall = max(events, key=lambda e: e[2])[1]
lww_hlc = max(events, key=lambda e: e[3])[1]
print(f"last writer wins, by wall clock: status = {lww_wall!r}; by hybrid clock: {lww_hlc!r}")
print()
def compare(a, b): # vector clocks: one counter per node
if a == b:
return "same"
if all(x <= y for x, y in zip(a, b)):
return "before"
if all(x >= y for x, y in zip(a, b)):
return "after"
return "concurrent: a person or a merge rule decides"
north, south = [2, 1], [1, 2] # both changed the address, neither saw the other
print("address edit at north vs south:", compare(north, south))
print("after south syncs from north: ", compare(north, [max(x, y) for x, y in zip(north, south)]))
print()
EPOCH, MACHINE = 1288834974657, 17 # a Snowflake-style 64-bit ID
def snowflake(clock_ms, guard):
ids, last, seq = [], -1, 0
for now in clock_ms:
ms = max(now, last) if guard else now # the guard never lets time go backwards
seq = seq + 1 if ms == last else 0
last = ms
ids.append(((ms - EPOCH) << 22) | (MACHINE << 12) | seq)
return ids
base = 1796090298000
clock = [base + d for d in (0, 0, 1, 2, 0, 0, 1, 2, 3)] # NTP steps the clock back 2 ms after the 4th ID
for guard in (False, True):
ids = snowflake(clock, guard)
print(f"snowflake, {'with' if guard else 'no':<4} guard: {len(ids)} IDs, {len(ids) - len(set(ids))} duplicates")
print()
def uuid7(ms, rand_a, rand_b): # RFC 9562 layout: 48 + 4 + 12 + 2 + 62 bits
return uuid.UUID(int=(ms << 80) | (7 << 76) | (rand_a << 64) | (2 << 62) | rand_b)
ms = 1796090298620
same_ms_random = [uuid7(ms, random.getrandbits(12), random.getrandbits(62)) for _ in range(5)]
start = random.getrandbits(11)
same_ms_counter = [uuid7(ms, start + i, random.getrandbits(62)) for i in range(5)]
u = same_ms_counter[0]
print(f"hand-made UUIDv7: {u} version {u.version}, timestamp {u.int >> 80} ms")
print("5 in one millisecond, random bits only, sort in creation order:", same_ms_random == sorted(same_ms_random))
print("5 in one millisecond, with a counter, sort in creation order:", same_ms_counter == sorted(same_ms_counter))
if hasattr(uuid, "uuid7"): # Python 3.14+
lib = [uuid.uuid7() for _ in range(1000)]
print("uuid.uuid7(): version", lib[0].version, "| 1,000 sort in creation order:", lib == sorted(lib))
print()
def leaf_pages(keys, capacity=64): # B-tree leaves: split in half, or start a new page at the right edge
pages = [[]]
for k in keys:
i = max(0, bisect.bisect_right([p[0] for p in pages if p], k) - 1)
page = pages[i]
bisect.insort(page, k)
if len(page) > capacity:
if i == len(pages) - 1 and page[-1] == k: # appending at the end: keep the full page full
pages.append([page.pop()])
else:
half = len(page) // 2
pages[i:i + 1] = [page[:half], page[half:]]
return len(pages), sum(map(len, pages)) / (len(pages) * capacity)
n = 20000
for name, keys in (("random keys (UUIDv4-like)", [random.getrandbits(122) for _ in range(n)]),
("time-ordered keys (UUIDv7)", list(range(n)))):
count, fill = leaf_pages(keys)
print(f"{name:<27} {n:,} rows -> {count} leaf pages, {fill:.0%} full")
Run it, and you should see this output:
$ python3 clocks_and_ids.py order by wall clock: delivered -> out for delivery order by hybrid clock: out for delivery -> delivered out for delivery wall 10:41:30 hybrid (10:41:30, 0) from the depot delivered wall 10:41:05 hybrid (10:41:30, 2) from the van last writer wins, by wall clock: status = 'out for delivery'; by hybrid clock: 'delivered' address edit at north vs south: concurrent: a person or a merge rule decides after south syncs from north: before snowflake, no guard: 9 IDs, 4 duplicates snowflake, with guard: 9 IDs, 0 duplicates hand-made UUIDv7: 01a22f53-00fc-71b7-8580-28d6099950d8 version 7, timestamp 1796090298620 ms 5 in one millisecond, random bits only, sort in creation order: False 5 in one millisecond, with a counter, sort in creation order: True uuid.uuid7(): version 7 | 1,000 sort in creation order: True random keys (UUIDv4-like) 20,000 rows -> 459 leaf pages, 68% full time-ordered keys (UUIDv7) 20,000 rows -> 313 leaf pages, 100% full
uuid.uuid7() uses one. Random keys leave B-tree leaf pages about 68% full (theory says about 69%), so the same 20,000 rows take 459 pages instead of 313: about 47% more pages to cache and write.The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/clocks-ordering-and-unique-ids && cd ~/labs/clocks-ordering-and-unique-ids) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Clocks, Ordering, and Unique IDs", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Make a practice folder, and look at the two clocks every Linux machine has: the wall clock, which says what time it is and can be adjusted, and the monotonic clock, which only counts up from boot.'
'Ask Python which system clock each of its clock functions reads, and whether that clock can be adjusted.'
'Measure a duration the right way, with the monotonic clock: a wall-clock step in the middle cannot make it negative.'
'Make a UUIDv7 and read the time back out of it: its first 48 bits are milliseconds since 1970.'
'Make 100,000 of each kind and check whether sorting them gives back the order they were made in.'
'Build and take apart a Snowflake-style 64-bit ID with shell arithmetic: 41 bits of milliseconds since a chosen epoch, 10 bits of machine, 12 bits of sequence.'
'Clean up.'
)
step_1() {
mkdir -p ~/labs/clocks && cd ~/labs/clocks
date -u '+wall clock (UTC): %Y-%m-%d %H:%M:%S.%N'
awk '{print "monotonic clock: " $1 " s since boot"}' /proc/uptime
timedatectl show -p NTPSynchronized 2>/dev/null || echo "no timedatectl here (a container, or WSL without systemd)"
}
step_2() {
python3 -c "import time
for name in ('time', 'monotonic'):
i = time.get_clock_info(name)
print(f'{name:<9} {i.implementation:<34} adjustable={i.adjustable} monotonic={i.monotonic}')"
}
step_3() {
python3 -c "import time
t0 = time.monotonic(); time.sleep(0.25)
print(f'slept {time.monotonic() - t0:.2f} s, measured on the monotonic clock')"
}
step_4() {
python3 -c "import uuid, datetime
u = uuid.uuid7()
print(u, 'version', u.version)
print('made at', datetime.datetime.fromtimestamp((u.int >> 80) / 1000, datetime.UTC).isoformat(timespec='milliseconds'))"
}
step_5() {
python3 -c "import uuid
v7 = [uuid.uuid7() for _ in range(100000)]
v4 = [uuid.uuid4() for _ in range(100000)]
print('uuid7 sorts in creation order:', v7 == sorted(v7))
print('uuid4 sorts in creation order:', v4 == sorted(v4))"
}
step_6() {
EPOCH=1288834974657
id=$(( ((1796090298620 - EPOCH) << 22) | (17 << 12) | 5 )); echo "id: $id"
echo "ms: $(( (id >> 22) + EPOCH )), machine: $(( (id >> 12) & 1023 )), sequence: $(( id & 4095 ))"
}
step_7() {
cd ~ && rm -rf ~/labs/clocks
ls ~/labs
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
awk, mkdir, rm, echo, ls, cd, Pipes, Redirection, If...Else, Variables.Quillfern records every parcel event from 400 depots and 12,000 van handhelds. Design how events are timestamped, ordered, identified, and resolved, and how clock problems are detected.
Which clock does each device and service use for what? How are events ordered for the tracking page and for status? Which ID scheme does each table use, and how is uniqueness guaranteed when clocks go wrong? How are concurrent edits detected and resolved? How is clock offset monitored on devices you do not control? What does the customer see when a device clock is known to be wrong?
Say 50,000 events a second at peak, 2 billion events a year, devices that may be offline for an hour, and a target of the right order for 99.99% of parcels.
Hybrid logical clocks on every event, merged when devices sync with the depot; ordering and status by HLC, wall times for display only; UUIDv7 keys made on devices, with a counter within the millisecond; a Snowflake-style service with a clock guard and assigned machine numbers for server-side IDs; vector clocks or explicit version numbers on editable fields such as addresses, with concurrent edits sent to a person; device offset reported with every batch, alerts above 5 s, server receive time recorded alongside device time; node_exporter timex metrics and alerts on every server.
HLC timestamps are slightly larger and need merging on every message, but they keep order without trusting device clocks; time-ordered IDs reveal creation time to anyone who sees them, which matters for public URLs; resolving concurrent edits by a person costs support time but avoids silently losing a change.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| A van clock 90 s slow | Hop 2: Clock | Degrades | The handheld cannot reach its time server through the van's mobile network and has drifted: it is 90 s slow and nothing alerts on it. |
| A van clock 90 s slow | Hop 6: Order | Breaks | The service sorts by the device's wall time. "Delivered" says 10:41:05; the depot's "out for delivery" says 10:41:30. Sorted by those times, the parcel was delivered 25 seconds before it left the depot. |
| A van clock 90 s slow | Hop 8: Resolve | Breaks | Last-writer-wins compares wall times: "out for delivery" (10:41:30) beats "delivered" (10:41:05). The status goes back to "out for delivery". |
| A van clock 90 s slow | Hop 9: Show | Breaks | The page says "out for delivery", with "delivered" listed underneath as older. The customer, holding the parcel, calls support. |
| Clock stepped back, duplicate IDs | Hop 3: ID | Breaks | IDs come from a central Snowflake-style service. Its clock had run 2 s fast while its time server was unreachable; when the server came back, NTP stepped the clock back 2 s. |
| Clock stepped back, duplicate IDs | Hop 7: Store | Breaks | The insert fails: duplicate key. The ID was issued 2 s earlier to a different scan. Over the 2 seconds, 3,100 scan events are rejected and, because the consumer treats a duplicate as already processed, dropped. |
| Clock stepped back, duplicate IDs | Hop 9: Show | Breaks | The page still says "out for delivery": the delivered scan was dropped. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by December 2027. Found something out of date? Tell me.