Platform Engineering · Lesson 79

Clocks, Ordering, and Unique IDs

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: one scan, one slow clock

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.

deliveredpage shows
100%index pages full
noneduplicate IDs

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — Use the right clock

At the basic level every program reads the clock that fits the question.

  • The monotonic clock for durations, timeouts, rate limits, and latency.
  • The wall clock, in UTC, for when something happened; converted to local time only for display.
  • Every machine synchronised to a time service, with the sync status visible.

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().

Intermediate — Order events by causality

At the intermediate level order comes from what caused what, not from timestamps.

  • Lamport clocks when a total order consistent with cause is enough.
  • Vector clocks when you must detect concurrent updates.
  • Hybrid logical clocks when you want both closeness to real time and causal order.

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.

Advanced — IDs that sort and stay unique

At the advanced level IDs are made anywhere, sort by time, and never repeat.

  • UUIDv7 or Snowflake-style IDs for high-volume tables; a counter within the same millisecond.
  • A guard that refuses or waits when the clock goes backwards; machine numbers assigned, not guessed.
  • A decision about exposure: time-based IDs reveal when a record was made.

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.

Master — Treat time as a monitored dependency

At the master level clock error is measured, bounded, and designed for.

  • Clock offset and sync status alerted on every machine and device.
  • A stated maximum skew that leases, caches, and certificates are designed around.
  • Where strict order across regions matters, a system that bounds clock uncertainty, as Google Spanner does with TrueTime and a commit wait.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The parcel that came back.

Timeline

  • MonA mobile network change blocks NTP traffic to 140 van handhelds. Their clocks drift; by Thursday some are 90 seconds slow. Nothing alerts.
  • Thu 10:42Deliveries scanned on those handhelds sort before the depot's "out for delivery" event, and last-writer-wins puts the parcels back to "out for delivery".
  • Thu 11:30Support sees a rise in "my parcel says out for delivery but I have it" calls; 2,300 parcels are affected.
  • Thu 16:00The cause is found by comparing device time with server receive time on the scans.

What changed after

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.

Try it yourself, from scratch

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).

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. 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.

    Reversible

    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)"

    Options: date -u prints UTC; %N is nanoseconds. /proc/uptime holds seconds since boot. timedatectl show -p NTPSynchronized says whether the clock is being kept in step with a time server.

    Expect: The current UTC time to the nanosecond, the seconds since boot, and NTPSynchronized=yes on a machine whose clock is being synchronised (or the "no timedatectl" line).

    Clean up: rm -rf ~/labs/clocks (the last step).

  2. Ask Python which system clock each of its clock functions reads, and whether that clock can be adjusted.

    Read-only

    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}')"

    Expect: time clock_gettime(CLOCK_REALTIME) adjustable=True monotonic=False and monotonic clock_gettime(CLOCK_MONOTONIC) adjustable=False monotonic=True. The wall clock can be stepped, even backwards; the monotonic one cannot.

  3. Measure a duration the right way, with the monotonic clock: a wall-clock step in the middle cannot make it negative.

    Read-only

    python3 -c "import time
    t0 = time.monotonic(); time.sleep(0.25)
    print(f'slept {time.monotonic() - t0:.2f} s, measured on the monotonic clock')"

    Expect: slept 0.25 s, measured on the monotonic clock. Use it for timeouts, retries, and latency; use the wall clock only to say when something happened.

  4. Make a UUIDv7 and read the time back out of it: its first 48 bits are milliseconds since 1970.

    Read-only

    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'))"

    Options: u.int >> 80 keeps the top 48 of the 128 bits: the Unix time in milliseconds.

    Expect: A UUID whose third group starts with 7 (late 2026 IDs start 01a2…), version 7, and the time you ran it. An ID that sorts by time also tells anyone who sees it when it was made.

  5. Make 100,000 of each kind and check whether sorting them gives back the order they were made in.

    Read-only

    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))"

    Expect: uuid7 sorts in creation order: True and uuid4 sorts in creation order: False. Nearly all 100,000 UUIDv7s are made inside the same few milliseconds; Python keeps them in order with a counter (RFC 9562, method 1), not just the timestamp.

  6. 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.

    Read-only

    EPOCH=1288834974657
    id=$(( ((1796090298620 - EPOCH) << 22) | (17 << 12) | 5 )); echo "id: $id"
    echo "ms: $(( (id >> 22) + EPOCH )), machine: $(( (id >> 12) & 1023 )), sequence: $(( id & 4095 ))"

    Options: << and >> shift bits; & 1023 keeps the low 10 bits, & 4095 the low 12. Bash arithmetic is 64-bit, enough for these IDs.

    Expect: id: 2127583034319376389, then ms: 1796090298620, machine: 17, sequence: 5. 12 bits of sequence allow 4,096 IDs per millisecond per machine; 10 bits allow 1,024 machines.

  7. Clean up.

    Potentially destructive

    cd ~ && rm -rf ~/labs/clocks
    ls ~/labs

    Expect: No error; clocks is gone.

2. Python: clocks_and_ids.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

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.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
A van clock 90 s slowHop 2: ClockDegradesThe 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 slowHop 6: OrderBreaksThe 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 slowHop 8: ResolveBreaksLast-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 slowHop 9: ShowBreaksThe page says "out for delivery", with "delivered" listed underneath as older. The customer, holding the parcel, calls support.
Clock stepped back, duplicate IDsHop 3: IDBreaksIDs 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 IDsHop 7: StoreBreaksThe 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 IDsHop 9: ShowBreaksThe page still says "out for delivery": the delivered scan was dropped.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Scan → Clock → ID → Send → Merge → Order → Store → Resolve → Show. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 80
When One Fails, Another Steps In

One zone is a single point of failure, no matter how good the machines in it are. I have watched a whole zone go dark and take every request with it. Redundancy is the fix: a second zone standing by with the same code and the…

Go to Lesson 80 →

Or browse the full course from the Lessons index.