Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Time, agreement and coordination · Lesson 5 of 11

Time, clocks and ordering

Why you cannot trust timestamps from different machines, and what to use instead. Happens-before, Lamport and vector clocks, hybrid logical clocks, TrueTime and commit wait, and the places where clocks quietly break real systems.

ConceptCore28 min readUpdated

  • 2 sequence flows
  • 5 code samples
  • 8 interviewer follow-ups
  • 4 self-checks
By the end you will be able to
  • Explain why wall-clock timestamps from different machines cannot order events, and name the ways a clock goes wrong (drift, steps, pauses).
  • Use the happens-before relation to define causality, and state what Lamport clocks, vector clocks and hybrid logical clocks each guarantee and cost.
  • Describe how TrueTime-style bounded clocks and commit wait give a real-time order, and what a system without them does instead.
  • Spot the places time breaks real designs (last-write-wins, leases, ID generators, token expiry, traces) and apply the right fix.

5 code samples (223 lines), collapsed so the explanation stays in focus.

Ask two servers what time it is and you get two answers. That would not matter if systems only used time to print log lines, but they also use it to decide which write wins, when a lock has expired, which event came first and whether a token is still valid. Each of those decisions quietly assumes that clocks on different machines agree and that a process notices when time passes. Neither is true.

HLD

Why time is hard in a distributed system

There are really three notions of time, and mixing them up causes most bugs.

  • Wall-clock time is the date and time of day (DateTime.UtcNow in .NET). It is meaningful across machines only as far as their clocks agree, and it can jump: forwards or backwards.
  • Monotonic time only moves forward and measures durations on one machine (Stopwatch.GetTimestamp() in .NET). Its absolute value means nothing, and it is not comparable between machines or across a restart. Use it for timeouts, retries and elapsed time.
  • True time is what physics says. No program can read it, only estimate it.

Why do wall clocks disagree and misbehave?

  • Drift. A quartz oscillator runs a little fast or slow, by tens of parts per million. A clock that is 50 parts per million fast gains about 4 seconds a day. Google's TrueTime design assumes up to 200 microseconds per second of worst-case drift, about 17 seconds a day.
  • Imperfect synchronisation. A time daemon (NTP, chrony) corrects the clock by asking servers over a network. The achievable accuracy is a few milliseconds on a good local network and tens of milliseconds or worse across the internet, and the error is never zero. When the offset is large the clock may be stepped, which can move it backwards.
  • Leap seconds. The extra second is shown as a repeated or an extra second, so naive code sees time go back or a minute with 61 seconds. Large providers hide it by smearing the second over many hours.
  • Pauses. A garbage-collection pause, a virtual machine being suspended or migrated, a container throttled by its CPU quota (see profiling and finding the bottleneck) or a page fault can freeze a process for seconds. A thread can check the time, be frozen, and wake up believing it is still the time it checked.

Cloud time services with hardware clocks reduce the error to well under a millisecond, which is useful and still not zero. The consequences are concrete:

What the code doesHow a clock breaks it
Sorts events from several servers by timestampAn effect sorts before its cause
Keeps the write with the highest timestamp (last write wins)The older write wins and the newer is lost without any error
Grants a lock or lease for 30 secondsA paused holder wakes up and acts after the lease has gone to someone else
Builds IDs from the current timeThe clock steps back and IDs repeat or go backwards
Trusts a token or cache entry until it expiresA skewed clock rejects a fresh token or accepts an expired one
Measures a timeout with wall-clock timeA step makes the timeout fire at once or never

LLD

Ordering without clocks: happens-before

Leslie Lamport's 1978 paper starts from the idea that what matters is not the time an event happened but whether it could have influenced another. Event a happens before event b (written a → b) if:

  1. they are on the same process and a came first, or
  2. a is the sending of a message and b is its receipt, or
  3. there is an event c with a → c and c → b (it is transitive).

If neither a → b nor b → a, the events are concurrent: no information could have flowed between them, so there is no fact about which came first. This is a partial order, and it is the right notion of "before" for a distributed system. Real-time order is a separate and stronger property that needs more than messages.

Wall clocks can get this wrong in an obvious way. If Bob's clock runs 300 ms behind Alice's, then a reply that Bob sends in response to Alice's question can carry an earlier timestamp than the question.

Fig. A reply that looks older than the question it answers
Fig. A reply that looks older than the question it answers

Lamport clocks

A Lamport clock is one counter per process. The rules are:

  • On every local event or send, add one to the counter and use it as the event's timestamp.
  • A message carries the sender's timestamp. On receiving it, set the counter to the larger of its own value and the message's, then add one.

The guarantee is one-way: if a → b then the timestamp of a is less than the timestamp of b. The reverse does not hold. A smaller timestamp does not mean "happened before"; it may be concurrent. Break ties by process id and you get a total order that agrees with causality, which is enough to build a mutual-exclusion protocol or a replicated log, and not enough to say whether two writes conflicted.

Vector clocks

A vector clock keeps one counter per process, and a timestamp is the whole vector. A process increments its own entry on each event, and on receiving a message takes the element-wise maximum of its vector and the message's before incrementing its own. Compare two vectors entry by entry: if every entry of a is less than or equal to b's (and they are not equal), a → b. If neither vector dominates the other, the events are concurrent. This is an exact characterisation of happens-before, which is what you need to detect conflicting updates. The price is a vector as large as the number of participants. Dynamo-style stores keep such vectors per object (the consistency and availability lesson builds a version vector), and prune them or fall back to last-write-wins when they grow.

A small example with three processes (A, B, C), showing the Lamport value and the vector at each step:

StepEventLamportVector (A, B, C)
1A: local event1(1, 0, 0)
2A sends m1 to B2(2, 0, 0)
3C: local event1(0, 0, 1)
4B receives m1max(0, 2) + 1 = 3(2, 1, 0)
5B sends m2 to C4(2, 2, 0)
6C receives m2max(1, 4) + 1 = 5(2, 2, 2)

Steps 1 and 3 are concurrent. Their Lamport values (1 and 1) hide that, and their vectors, (1, 0, 0) and (0, 0, 1), neither dominate the other, which shows it. Step 3 is before step 6 because (0, 0, 1) is less than or equal to (2, 2, 2).

Hybrid logical clocks

Lamport clocks lose touch with real time, so you cannot ask "what did the system look like at 10:00?". Hybrid logical clocks (HLC) fix that with a pair: l, the largest physical time this node has seen (its own clock or a message's), and c, a counter that breaks ties. The rules:

Example · formula
local event or send:  l' = l;  l = max(l', physical clock)
                      c = (l == l') ? c + 1 : 0
receive message m:    l' = l;  l = max(l', m.l, physical clock)
                      if l == l' == m.l:  c = max(c, m.c) + 1
                      else if l == l':    c = c + 1
                      else if l == m.l:   c = m.c + 1
                      else:               c = 0

The timestamp (l, c) compares like a number, respects causality like a Lamport clock, stays within the clock error of real time, and fits in 64 bits. CockroachDB and YugabyteDB use hybrid clocks to timestamp transactions, so a snapshot can be taken "as of a time" and still respect cause and effect.

One experiment, four kinds of stamp

The sample below runs five nodes that exchange messages (1 to 20 ms in flight) with wall clocks off by up to 100 ms. Every event is stamped four ways. The simulator also records the ground truth of which events happened before which, by following the messages. Then the test counts how often each stamp contradicts the truth.

C# · A hybrid logical timestamp: the largest physical time seen (in ms) plus a counter that…110 lines
using System;
using System.Collections.Generic;
using System.Linq;

// A hybrid logical timestamp: the largest physical time seen (in ms) plus a counter that breaks ties and carries causality.
public readonly record struct Hlc(long L, int C)
{
    public static bool operator <(Hlc a, Hlc b) => a.L != b.L ? a.L < b.L : a.C < b.C;
    public static bool operator >(Hlc a, Hlc b) => b < a;
}

public sealed class HybridClock
{
    private long l;
    private int c;
    private readonly Func<long> physicalNow;                 // the node's own wall clock, in milliseconds

    public HybridClock(Func<long> physicalNow) { this.physicalNow = physicalNow; }

    public Hlc Now()                                         // a local event, or a message about to be sent
    {
        long previous = l;
        l = Math.Max(previous, physicalNow());
        c = l == previous ? c + 1 : 0;
        return new Hlc(l, c);
    }

    public Hlc Receive(Hlc message)
    {
        long previous = l;
        l = Math.Max(Math.Max(previous, message.L), physicalNow());
        if (l == previous && l == message.L) c = Math.Max(c, message.C) + 1;
        else if (l == previous) c++;
        else if (l == message.L) c = message.C + 1;
        else c = 0;
        return new Hlc(l, c);
    }
}

// One event in a run, stamped four ways. `Before[k]` is the ground truth: did event k happen before this one?
public sealed class Event
{
    public int Id, Node;
    public long TrueTime, Wall, Lamport;
    public int[] Vector;
    public Hlc Hybrid;
    public bool[] Before;
}

public static class Execution
{
    private sealed class Message { public long DeliverAt; public int To, SendEvent; public long Lamport; public int[] Vector; public Hlc Hybrid; }

    // Nodes exchange messages that take 1 to 20 ms. Each node's wall clock is off by a fixed amount of up to `maxSkew` ms.
    public static List<Event> Run(int nodes, int count, int seed, int maxSkew)
    {
        var random = new Random(seed);
        var offset = Enumerable.Range(0, nodes).Select(_ => (long)random.Next(-maxSkew, maxSkew + 1)).ToArray();
        long now = 1_000_000;                                // true time in ms, which no node can read directly
        var lamport = new long[nodes];
        var vector = Enumerable.Range(0, nodes).Select(_ => new int[nodes]).ToArray();
        var hybrid = Enumerable.Range(0, nodes).Select(n => new HybridClock(() => now + offset[n])).ToArray();
        var last = Enumerable.Repeat(-1, nodes).ToArray();   // each node's previous event
        var inFlight = new List<Message>();
        var events = new List<Event>();

        static void Merge(bool[] into, Event from) { for (int k = 0; k < into.Length; k++) into[k] |= from.Before[k]; into[from.Id] = true; }
        Event Add(int node, Event sent)                      // `sent` is the send event when this is a receive
        {
            var e = new Event { Id = events.Count, Node = node, TrueTime = now, Wall = now + offset[node], Before = new bool[count] };
            if (last[node] >= 0) Merge(e.Before, events[last[node]]);
            if (sent != null) Merge(e.Before, sent);
            events.Add(e);
            last[node] = e.Id;
            return e;
        }

        while (events.Count < count)
        {
            now += random.Next(1, 6);
            foreach (var m in inFlight.Where(m => m.DeliverAt <= now).OrderBy(m => m.DeliverAt).ToList())
            {
                inFlight.Remove(m);
                if (events.Count >= count) break;
                var receive = Add(m.To, events[m.SendEvent]);
                lamport[m.To] = Math.Max(lamport[m.To], m.Lamport) + 1;
                for (int k = 0; k < nodes; k++) vector[m.To][k] = Math.Max(vector[m.To][k], m.Vector[k]);
                vector[m.To][m.To]++;
                receive.Lamport = lamport[m.To];
                receive.Vector = (int[])vector[m.To].Clone();
                receive.Hybrid = hybrid[m.To].Receive(m.Hybrid);
            }
            if (events.Count >= count) break;

            int node = random.Next(nodes);
            var local = Add(node, null);
            lamport[node]++;
            vector[node][node]++;
            local.Lamport = lamport[node];
            local.Vector = (int[])vector[node].Clone();
            local.Hybrid = hybrid[node].Now();
            if (random.Next(3) > 0)                          // two events in three also send a message carrying their stamps
            {
                int to = (node + 1 + random.Next(nodes - 1)) % nodes;
                inFlight.Add(new Message { DeliverAt = now + random.Next(1, 21), To = to, SendEvent = local.Id, Lamport = local.Lamport, Vector = local.Vector, Hybrid = local.Hybrid });
            }
        }
        return events;
    }
}
C#42 lines
using System;
using System.Diagnostics;
using System.Linq;

bool VectorLessThan(int[] a, int[] b) => a.Zip(b, (x, y) => x <= y).All(ok => ok) && !a.SequenceEqual(b);

int pairsCausal = 0, pairsConcurrent = 0;
int wallWrong = 0, lamportWrong = 0, hybridWrong = 0, vectorWrong = 0, lamportOrderedAnyway = 0;
long worstHybridDrift = 0;
int largestCounter = 0;
for (int seed = 1; seed <= 20; seed++)
{
    var events = Execution.Run(nodes: 5, count: 300, seed: seed, maxSkew: 100);
    foreach (var a in events)
    {
        worstHybridDrift = Math.Max(worstHybridDrift, Math.Abs(a.Hybrid.L - a.TrueTime));
        largestCounter = Math.Max(largestCounter, a.Hybrid.C);
        foreach (var b in events)
        {
            if (a.Id == b.Id) continue;
            bool aBeforeB = b.Before[a.Id], bBeforeA = a.Before[b.Id];
            if (VectorLessThan(a.Vector, b.Vector) != aBeforeB) vectorWrong++;      // vector clocks must match the truth exactly
            if (aBeforeB)
            {
                pairsCausal++;
                if (a.Wall >= b.Wall) wallWrong++;                                   // the effect looks older than its cause
                if (a.Lamport >= b.Lamport) lamportWrong++;
                if (!(a.Hybrid < b.Hybrid)) hybridWrong++;
            }
            else if (!bBeforeA && a.Id < b.Id)                                       // each concurrent pair once
            {
                pairsConcurrent++;
                if (a.Lamport != b.Lamport) lamportOrderedAnyway++;                  // Lamport values rank them although neither caused the other
            }
        }
    }
}
Debug.Assert(wallWrong > 0);                                   // with 100 ms of skew and 20 ms messages, wall clocks put effects before causes
Debug.Assert(lamportWrong == 0 && hybridWrong == 0 && vectorWrong == 0);
Debug.Assert(lamportOrderedAnyway > 0);                        // so Lamport timestamps cannot tell you two events were concurrent
Debug.Assert(worstHybridDrift <= 100);                         // the hybrid timestamp never strays more than the skew from true time
Debug.Assert(largestCounter < 64);                             // and the counter stays small

Across 20 runs of 300 events, there were 792,912 pairs where one event caused the other and 104,088 concurrent pairs:

StampCause/effect pairs ordered wronglyTells you two events were concurrent?Size
Wall clock43,773 (5.5%)No8 bytes
Lamport0No: it ranked 96,634 of the 104,088 concurrent pairs anyway8 bytes
Vector clock0Yes, exactly, for every pairOne counter per node
Hybrid logical0No8 bytes; never more than 100 ms (the skew) from true time

Wall clocks put an effect before its cause in about one pair in eighteen, with nothing visibly wrong in any single log line. The three logical stamps never did. The largest hybrid counter in these runs was 22: when a node receives a message from a clock that is ahead, its own events share that time until its clock catches up, and the counter separates them.

HLD

TrueTime and bounded uncertainty

Logical clocks give causal order, but not real-time order: if a transaction finishes and then a client starts another one on a different machine, a logical or hybrid timestamp does not guarantee the second gets the later timestamp, because the two machines never exchanged a message the clock could use. Google Spanner's answer is to bound the uncertainty instead of ignoring it.

Each datacenter has GPS receivers and atomic clocks, and every machine runs a daemon that tracks them. The TrueTime API does not return a time. It returns an interval, TT.now() = [earliest, latest], that is guaranteed to contain true time. The width of that interval, 2ε, is a few milliseconds (the paper reports an average ε around 4 ms).

For a read-write transaction, Spanner picks the commit timestamp s as TT.now().latest, and then performs commit wait: it does not make the commit visible or release the locks until TT.after(s) is true, that is, until even the earliest possible current time has passed s. From then on any transaction that starts after this one has finished will pick a larger timestamp. The cost is a wait of about 2ε, overlapped with the replication that has to happen anyway.

Fig. Commit wait in a TrueTime-style system
Fig. Commit wait in a TrueTime-style system

The model below reduces it to arithmetic. Every clock is within ε = 7 ms of true time. Transaction 1 commits on node A with timestamp s = A's reading + ε. Transaction 2 starts on node B the moment it hears transaction 1 is done, and takes B's reading + ε.

C# · Spanner's idea, reduced to arithmetic. Every clock is within Epsilon ms of true time…24 lines
using System;
using System.Diagnostics;

// Spanner's idea, reduced to arithmetic. Every clock is within Epsilon ms of true time, and a clock reads as the interval
// [reading - Epsilon, reading + Epsilon]. A commit takes the latest time its clock allows as its timestamp.
const int Epsilon = 7;
var clockError = new Random(3);
int reversedWithoutWait = 0, reversedWithWait = 0;
for (int trial = 0; trial < 10_000; trial++)
{
    long trueNow = 1_000_000 + clockError.Next(1000);
    long errorA = clockError.Next(-Epsilon, Epsilon + 1), errorB = clockError.Next(-Epsilon, Epsilon + 1);

    long commitTs = trueNow + errorA + Epsilon;                       // transaction 1 commits on node A
    long ackedNow = trueNow;                                          // without commit wait it is acknowledged at once
    long ackedAfterWait = trueNow + 2 * Epsilon + 1;                  // with it, only when A's earliest possible time passes commitTs

    // Transaction 2 starts on node B the moment it hears the acknowledgement, and also takes the latest time B's clock allows.
    long laterTsNow = ackedNow + errorB + Epsilon;
    long laterTsAfterWait = ackedAfterWait + errorB + Epsilon;
    if (laterTsNow <= commitTs) reversedWithoutWait++;                // started later, yet timestamped earlier
    if (laterTsAfterWait <= commitTs) reversedWithWait++;
}
Debug.Assert(reversedWithoutWait > 3_000 && reversedWithWait == 0);

Without the wait, transaction 2 got an earlier timestamp than the transaction it started after in 5,315 of 10,000 trials, so a read at transaction 2's timestamp would miss transaction 1's writes. With the wait, never. The wait was 2ε + 1 = 15 ms in this model.

That property, commit order matching real-time order, is external consistency (also called strict serializability, see transactions and isolation levels). The principle generalises: if you can bound the clock error, you can wait it out. Cloud providers publish clock-error bounds in the same spirit (for example, AWS's ClockBound daemon), which lets ordinary services reason about uncertainty.

Systems without special hardware live with the uncertainty. CockroachDB assumes a maximum clock offset (500 ms by default) and gives each read an uncertainty interval of that width: if a read finds a value written inside the interval, it cannot tell whether that write happened before it, so the transaction restarts at a later timestamp. A node whose clock drifts too far from its peers shuts itself down rather than risk the guarantee. Tighter clocks mean fewer restarts.

LLD

Where time bites in real systems

Last write wins

Some databases resolve conflicting writes by keeping the highest timestamp: Cassandra does this per column, and DynamoDB global tables reconcile concurrent updates in different regions the same way (see multi-region design for the alternatives). With skewed clocks, a write that causally follows another (the client read the value and then changed it) can carry a lower timestamp and be silently discarded. A hybrid or logical timestamp avoids that for causally related writes. For truly concurrent writes, "last" is arbitrary whatever clock you use, so decide whether losing one is acceptable, or use versions and merge (see the consistency lesson).

Leases, locks and expiry

A lease says "you are the leader until 12:00:30". The grantor's clock decides when it expires; the holder's clock, the network and its own pauses decide whether it knows. A holder that was paused for 20 seconds can wake up and write, believing the lease is valid, while a new leader is already working. Defences:

  • Measure lease time with monotonic clocks, and have the holder stop acting before the grantor would expire it (hold for 80% of the term, for example).
  • Never rely on "I checked the lease a moment ago". Make the resource reject stale holders with a fencing token: a number that increases with every grant, which the storage layer checks on every write. The next lesson, on consensus, builds this.

Unique IDs

Time-based IDs such as Twitter's Snowflake pack milliseconds, a node number and a per-millisecond sequence into 64 bits, so IDs sort roughly by time and need no coordination. UUIDv7 and ULID do the same with 48 bits of milliseconds. The failure is the clock: a step backwards makes the generator repeat a (millisecond, sequence) pair that it has already used. The original Snowflake refuses to issue IDs until the clock catches up. A friendlier rule is the one hybrid clocks use: never let the timestamp go backwards.

C# · 41 bits of milliseconds since an epoch, 10 bits of node, 12 bits of sequence: IDs that…27 lines
using System;
using System.Collections.Generic;

// 41 bits of milliseconds since an epoch, 10 bits of node, 12 bits of sequence: IDs that sort by time and need no coordination.
public sealed class SnowflakeIds
{
    private const long Epoch = 1_700_000_000_000L;
    private readonly long node;
    private readonly Func<long> clock;                       // wall-clock milliseconds, passed in so a test can move it
    private long lastMs = -1;
    private long sequence;

    public SnowflakeIds(int node, Func<long> clock) { this.node = node; this.clock = clock; }

    public long Next()
    {
        long ms = Math.Max(clock(), lastMs);                 // never let the timestamp go backwards, even if the clock does
        if (ms == lastMs)
        {
            sequence = (sequence + 1) & 4095;
            if (sequence == 0) ms++;                         // 4,096 IDs in one millisecond: borrow the next one
        }
        else sequence = 0;
        lastMs = ms;
        return ((ms - Epoch) << 22) | (node << 12) | sequence;
    }
}
C#20 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;

long fakeNow = 1_700_000_100_000L;
var ids = new SnowflakeIds(node: 7, clock: () => fakeNow);
var seenIds = new HashSet<long>();
long previousId = -1;
var steps = new Random(12);
for (int i = 0; i < 100_000; i++)
{
    int roll = steps.Next(100);
    if (roll < 20) fakeNow += steps.Next(1, 4);                // time moves on
    else if (roll == 20) fakeNow -= 5_000;                     // an NTP step puts the clock five seconds back
    long id = ids.Next();
    Debug.Assert(id > previousId, "IDs must keep increasing");
    Debug.Assert(seenIds.Add(id), "IDs must be unique");
    Debug.Assert(((id >> 12) & 1023) == 7, "the node is recoverable from the ID");
    previousId = id;
}

The test moves the clock back five seconds from time to time, stays in the same millisecond for long stretches, and still gets 100,000 unique, strictly increasing IDs from one node. The price is that after a step back the IDs carry a timestamp ahead of the real clock until it catches up, so the time inside an ID is approximate. Forty-one bits of milliseconds last about 69 years from the epoch you choose, and 12 sequence bits allow 4,096 IDs per millisecond per node, about four million a second. Different nodes differ in the node bits, so they never collide.

Tokens, caches and traces

  • Token validity. Signed tokens carry nbf and exp times. A verifier with a skewed clock rejects fresh tokens or accepts dead ones, so libraries allow some leeway; .NET's JWT validation allows five minutes of ClockSkew by default, which also means a token is accepted for five minutes after it expires. Keep the leeway small and synchronise the servers.
  • Cache TTLs are relative durations. Count them on the machine that holds the entry, with a monotonic clock, not by comparing a stored absolute time with another machine's.
  • Traces and logs. Spans from different hosts show negative durations when clocks disagree. Tracing systems order spans by parent-child links, not by timestamps; add a per-source sequence number or a log offset when you need a reliable order.

HLD

Choosing an ordering tool

You needUseCost
Order inside one process or machineA counter or a monotonic clockNone
One order that everyone agrees onA single sequencer or a replicated log (a consensus group, a Kafka partition)A throughput and latency bottleneck
An order that respects causality, cheaplyLamport or hybrid logical timestampsThey cannot show that two events were concurrent
To detect concurrent updates exactlyVector clocks or version vectorsSize grows with the writers
Real-time order across data centersBounded clocks and commit wait (TrueTime style)Special hardware, or latency of about 2ε per commit
Expiry, timeouts, leasesMonotonic local timers with a margin, plus fencingCareful design

Timestamps are still fine for display, for coarse metrics and for choosing what to expire, as long as no correctness decision rests on their order.

HLD

Failure modes and edge cases

SituationWhat happensDefence
Events from several servers sorted by wall-clock timestampAn effect appears before its causeLogical or hybrid clocks, or order by a log offset
Last-write-wins with skewed clocksThe older write wins and the newer is lost silentlyHybrid timestamps, compare-and-set, merge on conflict
The clock steps backwardsTimeouts misfire; time-based IDs repeatMonotonic clocks for durations; a generator whose timestamp never decreases
A process pauses after checking a leaseTwo nodes act as the holderFencing tokens validated by the resource
Token or cache expiry near the edgeFresh tokens rejected or expired ones acceptedA small, explicit leeway and one time source
Daylight saving and leap secondsA repeated or missing hour; a job runs twice or not at allStore UTC and a zone; use zone-aware libraries; smear leap seconds
The time daemon fails quietlyDrift grows unnoticedMonitor the offset and alert; refuse leadership above a bound

Senior depth

What senior interviews ask about time and ordering

Interviewer follow-upL5Why can't you order events from different servers by timestamp, and what do you use instead?How to answer

Their clocks drift, are corrected by steps and are never exactly equal, so an effect can carry an earlier timestamp than its cause (in the experiment above, one causal pair in eighteen). Order by causality with a logical or hybrid clock, or put the events through one log or sequencer and use the offset. Use wall-clock time only for display and for coarse decisions.

Interviewer follow-upL5What is the difference between a wall clock and a monotonic clock, and which do you use for a timeout?How to answer

A wall clock gives the date and time and can jump forwards or backwards when it is corrected. A monotonic clock only moves forward and is meaningful only on one machine, for measuring durations. Use the monotonic clock for timeouts, retries and elapsed time, and the wall clock when you need a calendar time to show or store.

Interviewer follow-upL6What does a Lamport clock guarantee, what can't it do, and how do vector clocks differ?How to answer

If one event happened before another, its Lamport timestamp is smaller. The converse is false, so you cannot tell from two timestamps whether the events were concurrent. A vector clock keeps one counter per process and compares entry by entry: it identifies exactly whether one event is before the other or they are concurrent, which is what conflict detection needs. The price is a vector as large as the number of participants.

Interviewer follow-upL6Your last-write-wins store is losing updates. What is going on and what are the options?How to answer

The "last" write is chosen by timestamps from different clocks, so with skew a later write can carry an older timestamp and be discarded without any error. Options: use hybrid logical timestamps, so causally related writes are ordered correctly; use compare-and-set or versions so a stale write is rejected rather than silently winning; or keep both values with version vectors and merge. Concurrent writes still need a rule for which one wins.

Interviewer follow-upL6Design a unique ID generator for many nodes with no coordination. What happens when a clock moves back?How to answer

A Snowflake-style ID: milliseconds, a node number and a per-millisecond sequence in 64 bits, sortable by time and unique because node numbers differ. When the clock moves back, either refuse to issue IDs until it catches up, or keep issuing from the last timestamp used and let the sequence advance, so IDs never repeat or go backwards. Say that node numbers must be assigned uniquely (a registry or lease) and that the time inside an ID is approximate.

Interviewer follow-upL7How does Spanner get external consistency, and what would you do without atomic clocks?How to answer

TrueTime returns an interval guaranteed to contain true time. A commit chooses the latest value in the interval as its timestamp and waits until that value is certainly in the past before becoming visible, so later transactions get larger timestamps. The cost is about twice the clock error per commit, overlapped with replication. Without such clocks, use hybrid logical clocks with a configured maximum offset, restart reads that fall into the uncertainty interval, and shut down nodes whose clocks drift too far, as CockroachDB does. Or accept causal consistency and say so.

Interviewer follow-upL7A leader's lease expired while it was in a garbage-collection pause, and it still wrote to storage. How do you stop that?How to answer

Do not rely on the leader noticing. Give each lease a fencing token, a number that increases with every grant, and have the storage system reject any write carrying a token older than the highest it has seen. The paused leader wakes up with an old token and is refused. Add margin so leaders stop earlier than the grantor expires them, and use monotonic clocks to measure the lease.

Interviewer follow-upL7How would you order events from a thousand services for an audit trail?How to answer

Do not trust timestamps for order. Append events to a replicated log (partitioned by entity, so each entity has one total order from the offset), and carry causal metadata: a trace and parent id, and a per-source sequence number so gaps and reordering are visible. Keep the timestamp for display, with its source and an uncertainty note, and keep the clocks monitored so the display is trustworthy.

HLD

Putting it into an answer

When a design says "latest", "first", "expired" or "within 5 minutes", ask whose clock decides it and what happens when that clock is wrong. If you need an order, say what produces it: one log, a sequencer, a logical timestamp, or bounded clocks. If you need an expiry, say it is measured on one machine with a monotonic clock and a margin, and protected by a fencing token.

Summary

Clocks on different machines disagree, jump, and can be frozen by pauses, so wall-clock timestamps cannot order events. What matters is happens-before: causal order is a partial order, and events with no causal path are concurrent. Lamport clocks give a total order that respects causality but cannot reveal concurrency. Vector clocks reveal it exactly at a cost that grows with the number of participants. Hybrid logical clocks keep causality, fit in 64 bits and stay close to real time, which is why databases use them for transaction timestamps. TrueTime goes further, bounding the clock error and waiting it out at commit, to give real-time order. In everyday designs, use monotonic clocks for durations, a log or hybrid timestamp for order, fencing tokens for leases, a never-decreasing generator for time-based IDs and a small explicit leeway for expiry.

Check yourself

Try answering out loud before you reveal each answer.

QuestionAlice sends a question and Bob replies at once, but Bob's clock is 300 ms behind. What does sorting by timestamp show, and what fixes it?Reveal answer

The reply appears before the question, because its timestamp is earlier. Order by causality instead: a Lamport or hybrid logical timestamp gives the reply a larger value than the question it responds to, since the reply's clock was updated on receiving the question. Or order both through one log and use the offset.

QuestionTwo events have Lamport timestamps 3 and 5. Can you say the first happened before the second? What would a vector clock tell you?Reveal answer

No. A smaller Lamport timestamp is consistent with happening before, but the events may be concurrent. Compare their vectors: if every entry of the first is less than or equal to the second's, the first happened before the second; if neither vector dominates, they were concurrent.

QuestionWhat does Spanner's commit wait buy, and why does it need a bound on the clock error?Reveal answer

It guarantees that a transaction which starts after another has finished gets a larger timestamp, so timestamp order matches real-time order. A commit picks the latest value its clock might show, then waits until even the earliest possible current time has passed that value. That only works if the clock reports an interval guaranteed to contain true time, and the wait is about twice the interval's half-width.

QuestionA Snowflake-style generator runs on a VM whose clock is stepped back five seconds. Describe two ways the generator can behave and the trade-off between them.Reveal answer

It can refuse to issue IDs until the clock catches up, which is safe and simple but stalls for up to five seconds. Or it can keep issuing from the last timestamp it used and let the sequence advance, which never stalls and never repeats an ID, but the time embedded in the IDs runs ahead of the real clock until it catches up.

Sources and further reading

Lesson 5 of 11

Nice. Lock it in, then keep going.

Up next · Lesson 6Consensus, leader election and distributed locksHow a group of machines agrees on one order of events when some of them crash. Quorums, Raft leader election and log replication in a tested simulation, then leases and the fencing tokens that make a distributed lock safe.

Send a message

It goes straight to my inbox. I usually reply within a few days.