📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Why can't you order events across machines by their wall-clock timestamps? Explain clock skew and clock jumps, how NTP and the cloud keep time, logical clocks (Lamport, vector, hybrid), and how .NET's TimeProvider and Stopwatch help you write time-safe code.

Time in distributed systems: clock skew, drift and jumps, NTP and cloud time sync, why timestamps can't order events across machines, Lamport, vector and hybrid logical clocks, and safe time handling in .NET with Stopwatch, DateTimeOffset and TimeProvider.

Senior Theory Advanced clock-skew distributed-systems logical-clocks ntp ordering timeprovider

🎯 Key points

  • Every machine has its own clock; drift and skew of milliseconds (or seconds when sync fails) are normal
  • Wall clocks can jump backwards or forwards (NTP step, VM restore, leap smearing), so timestamps aren't monotonic
  • Last-writer-wins by timestamp silently loses newer writes when clocks are skewed
  • Measure durations with a monotonic clock (Stopwatch.GetTimestamp / GetElapsedTime, TimeProvider.GetTimestamp), never DateTime differences
  • Lamport clocks give an order consistent with happens-before; vector clocks detect concurrent updates; hybrid logical clocks combine both with physical time
  • Practical ordering: sequence numbers from a single writer, database rowversion, Kafka offsets per partition, Service Bus sequence numbers
  • Cloud time sync (Azure host PTP/VMICTimeSync, Amazon Time Sync Service, Google Cloud's metadata NTP server) is good but not a guarantee; monitor skew
  • TimeProvider (introduced in .NET 8) abstracts time for testing (FakeTimeProvider) and makes timers and delays controllable

⏱ 30-second answer

Each machine has its own clock, and clocks drift and skew: a few milliseconds is normal, seconds when sync breaks. Worse, wall clocks can jump, backwards or forwards, when NTP corrects them or a VM is restored. So timestamps from different machines can't reliably tell you which event happened first, and last-writer-wins by timestamp silently discards newer data. For ordering, use something that only goes up: a sequence number from a single writer, a database rowversion, a Kafka offset per partition, or logical clocks (Lamport, vector, hybrid) when nodes write independently. For durations, use a monotonic clock (Stopwatch, TimeProvider.GetTimestamp), never DateTime differences. In .NET, inject TimeProvider so time can be faked in tests. The trade-off: logical clocks give correct order but no human-readable time, so you usually keep both.

🗣 Full answer (senior)

How I would answer this in an interview

"The problem is there's no shared clock. Every server has a quartz oscillator that drifts, and something like NTP or the cloud host keeps nudging it back. Inside one Azure region you can usually expect clocks within a few milliseconds, but that's not a guarantee: when sync fails, or a VM is paused and resumed, a clock can be seconds out and then jump when it's corrected, including backwards. So if service A writes an event at 10:00:00.120 and service B writes one at 10:00:00.118, you genuinely don't know which came first. Anything that sorts or resolves conflicts by wall-clock time across machines, like last-writer-wins, can silently throw away the newer write.

What I use instead depends on the job. For durations and timeouts, a monotonic clock: Stopwatch or TimeProvider.GetTimestamp, which never goes backwards; computing DateTime.UtcNow - start can even go negative after a clock step. For ordering, I want a number assigned by one authority: an identity or rowversion in SQL Server, the sequence number Service Bus stamps on each message, or the offset in a Kafka partition. When several nodes write independently, logical clocks come in: a Lamport clock gives an order consistent with causality, vector clocks can tell that two updates were concurrent so you can merge them, and hybrid logical clocks combine physical time with a counter, which is what CockroachDB and similar databases use. For [example, at company] we [replaced a timestamp-based 'latest status wins' rule with a per-order version number, and the 'order shows Delivered then Shipped' bug disappeared].

In .NET 8 and later I inject TimeProvider rather than calling DateTime.UtcNow, so tests can use FakeTimeProvider to move time forward. The line I'd end on: wall-clock time is for humans and audit logs; ordering needs counters."


Kinds of clock

Clock What it gives Use for Don't use for
Wall clock (DateTimeOffset.UtcNow) Human time, can jump Display, audit, expiry dates Ordering across machines, measuring durations
Monotonic (Stopwatch, TimeProvider.GetTimestamp) Elapsed time, never goes back Timeouts, latency, rate limits Comparing across machines
Single-writer sequence (identity, rowversion, Service Bus sequence number) Total order from one authority Ordering within one store or entity Ordering across independent stores
Lamport clock Order consistent with causality Ordering messages between services Detecting concurrency
Vector clock Detects concurrent updates Multi-master conflict detection Large numbers of nodes (vectors grow)
Hybrid logical clock Causal order close to physical time Distributed databases, event stores Simple apps (overkill)

Production example

A delivery-tracking service accepted status updates from drivers' devices and two back-end services, keeping the one with the latest timestamp. About 0.2% of orders showed 'Delivered' and then flipped back to 'Out for delivery', because one device's clock was 90 seconds fast. Switching to a per-order version number checked on write (and recording device time only for display) removed the flips.

🔍 What the interviewer is checking

Checks whether the candidate knows why wall-clock time is unreliable across machines and has practical tools for ordering and measuring time correctly.

Green flags

  • Explains skew, drift and backward jumps.
  • Separates monotonic clocks (durations) from wall clocks (human time).
  • Uses single-writer sequence numbers or logical clocks for ordering, and knows what Lamport vs vector clocks can and can't tell you.
  • Mentions TimeProvider and testing with FakeTimeProvider.

Red flags

  • Sorts cross-service events by DateTime.Now.
  • Measures timeouts with wall-clock differences.
  • 'NTP keeps everything in sync, so it's fine.'

📚 Learn in depth

1. How computer clocks go wrong

  • Drift: quartz crystals run fast or slow by tens of parts per million, a few seconds a day if uncorrected.
  • Skew: the difference between two clocks at the same instant.
  • Steps: NTP slews the clock gradually for small errors but steps it for large ones; a step can move time backwards.
  • Pauses: VM live migration, snapshot restore or a container being frozen stop the clock from the process's point of view, then it catches up.
  • Leap seconds: cloud providers smear them over hours, so their clocks differ from strict UTC during the smear.

2. How the cloud keeps time

Azure VMs get time from the Hyper-V host, which syncs to Microsoft's stratum-1 servers. Linux VMs use chrony with the Hyper-V PTP clock source (/dev/ptp_hyperv); Windows VMs use the VMICTimeSync provider. AWS offers the Amazon Time Sync Service. These are good, often sub-millisecond, but still not a guarantee, and containers inherit the node's clock. Monitor skew (chrony tracking, node exporter metrics) rather than assuming it.

3. Why timestamps can't order events

Service A clock: +40 ms fast        Service B clock: correct
A: writes status=Shipped  @ 10:00:00.140 (real 10:00:00.100)
B: writes status=Delivered @ 10:00:00.120 (real 10:00:00.120)
Last-writer-wins by timestamp -> Shipped (wrong: Delivered really came later)

4. Lamport clocks

Each process keeps a counter. Increment it before each event; send it with each message; on receive, set counter = max(local, received) + 1. If event a happened before b (causally), then L(a) < L(b). The reverse isn't true: L(a) < L(b) doesn't prove causality.

5. Vector clocks and hybrid logical clocks

A vector clock holds a counter per node. Compare two vectors: if every entry of one is less than or equal to the other's, it happened before; otherwise the events are concurrent, and you need a merge (or a CRDT). Vectors grow with the number of writers.

A hybrid logical clock (HLC) stores (physical time, logical counter). It stays close to wall time for humans but never goes backwards and respects causality, which is why CockroachDB and YugabyteDB use it. Google Spanner goes further with TrueTime, which exposes clock uncertainty and waits it out.

6. Time in .NET

  • DateTime.UtcNow / DateTimeOffset.UtcNow: wall clock. Store DateTimeOffset or UTC, never local time.
  • Stopwatch.GetTimestamp() and Stopwatch.GetElapsedTime(start) (.NET 7+): monotonic, high resolution.
  • TimeProvider (.NET 8+): abstract class with GetUtcNow(), GetTimestamp(), GetElapsedTime(), CreateTimer() and LocalTimeZone. Task.Delay, CancellationTokenSource and PeriodicTimer accept it. FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) lets tests advance time instantly.

Try it yourself

  1. Measure a loop with DateTime.UtcNow differences and with Stopwatch.GetElapsedTime, then change the system clock during the run (in a VM) and compare.
  2. Write a 20-line Lamport clock class and simulate three services exchanging messages; print the resulting order.
  3. Replace DateTime.UtcNow in a token-expiry check with an injected TimeProvider and test expiry with FakeTimeProvider.Advance.
  4. On a Linux VM run chronyc tracking and note the current offset and the reference source.

💻 Code

Time-safe code in .NET 10: TimeProvider for testable wall time, monotonic timestamps for durations, and a version number (not a timestamp) to decide which update wins.

namespace Tracking;

public sealed record StatusUpdate(Guid OrderId, string Status, long Version, DateTimeOffset ReportedAt);

public sealed class OrderStatus
{
    public Guid OrderId { get; init; }
    public string Status { get; private set; } = "Created";
    public long Version { get; private set; }
    public DateTimeOffset LastReportedAt { get; private set; } // for display only

    // Order by version (assigned by one authority), never by device or server clock
    public bool TryApply(StatusUpdate update)
    {
        if (update.Version <= Version) return false; // stale or duplicate: ignore
        Status = update.Status;
        Version = update.Version;
        LastReportedAt = update.ReportedAt;
        return true;
    }
}

public sealed class LamportClock
{
    private long _counter;
    public long Tick() => Interlocked.Increment(ref _counter);

    // On receiving a message: jump past the sender's clock
    public long Receive(long remote)
    {
        long current, next;
        do
        {
            current = Volatile.Read(ref _counter);
            next = Math.Max(current, remote) + 1;
        } while (Interlocked.CompareExchange(ref _counter, next, current) != current);
        return next;
    }
}

public sealed class ReservationService(TimeProvider time)
{
    private static readonly TimeSpan HoldFor = TimeSpan.FromMinutes(10);

    // Wall time for an expiry users see; injectable so tests can advance it
    public DateTimeOffset HoldExpiresAt() => time.GetUtcNow() + HoldFor;

    // Monotonic time for measuring how long work took (immune to clock steps)
    public async Task<TimeSpan> TimeCallAsync(Func<CancellationToken, Task> call, CancellationToken ct)
    {
        var start = time.GetTimestamp();
        await call(ct);
        return time.GetElapsedTime(start);
    }
}
// Test with FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing)
using Microsoft.Extensions.Time.Testing;

var fake = new FakeTimeProvider(new DateTimeOffset(2026, 11, 21, 9, 0, 0, TimeSpan.FromHours(11)));
var service = new Tracking.ReservationService(fake);
var expires = service.HoldExpiresAt();
fake.Advance(TimeSpan.FromMinutes(11));
Console.WriteLine(fake.GetUtcNow() > expires); // True, without waiting 11 minutes

⚠ Common mistakes

  • Mistake: Resolving conflicts with last-writer-wins on wall-clock timestamps from different machines. Why it is wrong: skew of even milliseconds lets an older write win. Instead: use a version or sequence number from one authority, or a logical clock.
  • Mistake: Measuring durations with DateTime.UtcNow - start. Why it is wrong: a clock step can make the result wrong or negative. Instead: use Stopwatch.GetTimestamp or TimeProvider.GetElapsedTime.
  • Mistake: Trusting client or device timestamps for ordering. Why it is wrong: user devices can be minutes or hours out. Instead: record device time for display; order on the server.
  • Mistake: Storing local times. Why it is wrong: daylight saving changes in Australia (for example NSW and Victoria, but not Queensland) create duplicate or missing hours. Instead: store UTC or DateTimeOffset.
  • Mistake: Calling DateTime.UtcNow directly in business logic. Why it is wrong: time-based rules become untestable without waiting. Instead: inject TimeProvider and use FakeTimeProvider in tests.
  • Mistake: Assuming cloud clocks are perfectly synced. Why it is wrong: sync can fail, and VMs can pause and resume. Instead: monitor skew and design so correctness doesn't depend on it.
  • Mistake: Using a Lamport clock to detect conflicts. Why it is wrong: it orders events but can't tell concurrent ones apart. Instead: use vector clocks or version checks when you need conflict detection.

🏛 Senior insight: trade-offs

When I review a design, I look for any place where correctness depends on two machines agreeing on the time: lease expiry, token expiry across services, conflict resolution, 'process events after timestamp X' in a consumer. Each of those gets either a tolerance (allow a few seconds of clock skew in JWT validation; the default ClockSkew is 5 minutes, which is generous) or a redesign around counters.

The practical rule I give teams: wall-clock time is for humans, audit and coarse expiry; ordering comes from a single authority. If you can route all writes for an entity through one place (one database row, one Kafka partition, one Service Bus session), you get a total order for free and don't need logical clocks at all.

Option When it fits Cost When not to
Single-writer version / sequence One database or partition owns the entity Writes funnel through one place Truly multi-master writes
Lamport clock Causal order of messages between services A counter on every message You need to detect concurrency
Vector clock / CRDT Multi-region writes that must merge Metadata grows with writers, merge logic Few writers, or a single primary exists
Hybrid logical clock Distributed databases and event stores Implementation complexity Typical line-of-business apps

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TimeProvider. Why: Checks practical use of TimeProvider and FakeTimeProvider.
    How to answer

    Inject TimeProvider (registered as TimeProvider.System in DI) instead of calling DateTime.UtcNow or Task.Delay directly. In tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing: set a start time, call Advance to move time forward, and timers, delays and PeriodicTimer created from it fire deterministically with no real waiting. Test the boundaries (exactly at expiry, one tick either side), keep business time in UTC, and cover daylight-saving rules with a fake local time zone.

  2. When: Candidate talks about events being seen out of order. Why: Checks how ordering guarantees relate to consistency models such as consistent prefix.
    How to answer

    A consistency model is the contract that says which values a read may return when data is replicated. At one end, strong (linearisable) consistency makes every read see the latest committed write, as if there were one copy. At the other, eventual consistency only promises replicas converge once writes stop. In between are the session guarantees: read-your-writes (you see your own updates), monotonic reads (you never go back in time) and consistent prefix (you never see writes out of order). Cosmos DB exposes this as five levels: Strong, Bounded Staleness, Session (the default), Consistent Prefix and Eventual; stronger levels cost more latency and request units, and Strong can't be used with multi-region writes. I choose per feature: what does a stale or out-of-order read cost here? The trade-off is freshness against latency, cost and availability.

🛠 Real-world problems: how you handle them

Delivery status flips back because a device clock is fast
Situation
A delivery-tracking service took status updates from [drivers' mobile devices] and [two] back-end services, storing the update with the latest timestamp per order, for about [n] deliveries a day across Australia.
Signals
Customer complaints that orders showed 'Delivered' then 'Out for delivery'; about [0.2%] of orders had a status regression in the history table; no errors logged.
Investigation
Queried the status history for regressions and compared reported timestamps with server receive times; found one device model's clock running [90 seconds] fast and a back-end service writing with server time, so the device's earlier event carried a later timestamp. Distributed traces in Application Insights confirmed the real order of arrival.
Resolution
Immediate: a data fix that rebuilt current status from server-side receive order. Real fix: each status change carries a per-order version assigned by the order service; writes with a version less than or equal to the stored one are ignored; device time kept for display only.
Prevention
A unit test feeding out-of-order and skewed updates; an analyser rule banning DateTime.Now/UtcNow in domain code in favour of TimeProvider; a dashboard of device-vs-server clock offset.

How to tell it (STAR)

**S:** Customers of our [delivery tracking] saw orders flip from Delivered back to Out for delivery. **T:** I had to find the cause and stop it. **A:** I compared reported timestamps with server receive times and found [a device clock 90 seconds fast] winning a timestamp-based last-writer-wins rule, so I replaced it with a per-order version checked on write and kept device time only for display. **R:** Status regressions went from about [0.2%] of orders to zero, and the related support tickets stopped within a week.

↩ Usually asked after

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me