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.
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.
"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:
StopwatchorTimeProvider.GetTimestamp, which never goes backwards; computingDateTime.UtcNow - startcan 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
TimeProviderrather than callingDateTime.UtcNow, so tests can useFakeTimeProviderto move time forward. The line I'd end on: wall-clock time is for humans and audit logs; ordering needs counters."
| 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) |
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.
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
TimeProvider and testing with FakeTimeProvider.Red flags
DateTime.Now.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.
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)
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.
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.
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.DateTime.UtcNow differences and with Stopwatch.GetElapsedTime, then change the system clock during the run (in a VM) and compare.DateTime.UtcNow in a token-expiry check with an injected TimeProvider and test expiry with FakeTimeProvider.Advance.chronyc tracking and note the current offset and the reference source.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
DateTime.UtcNow - start. Why it is wrong: a clock step can make the result wrong or negative. Instead: use Stopwatch.GetTimestamp or TimeProvider.GetElapsedTime.DateTimeOffset.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.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 |
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.
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.
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.
Last updated 23 Nov 2026.