Clock Skew in Distributed Systems: Problems and Solutions

Explore how clock skew affects distributed systems, causes silent data corruption, breaks conflict resolution, and what you can do to mitigate these issues.

published: reading time: 32 min read author: Geek Workbench updated: November 8, 2026
Quick Summary

Clock skew can make timestamps disagree with the order in which distributed events occurred. This guide distinguishes physical-clock readings from logical ordering, explains how to measure offset, and shows where timestamp-based conflict resolution can violate application assumptions. NTP reduces error but does not promise one accuracy level across networks and machines; choose clock behavior to match the system’s actual invariants.

Introduction

Clock skew is the difference between two clocks at a given moment. Clock drift is the rate at which a clock runs faster or slower than true time. In distributed systems, these imperfections create subtle bugs that are hard to reproduce and harder to debug.

Most engineers know about clock skew in theory. Few have encountered its real-world manifestations. This post explores what happens when clocks lie, and how to build systems that survive their lies.


Why Clocks Lie

Hardware Reality

Hardware clocks are imperfect. For illustration, an oscillator specified at 20 parts per million (ppm) could drift by about 20 microseconds per second if left uncompensated:

20 ppm × 86,400 seconds per day is about 1.7 seconds of drift per day. This arithmetic describes an uncompensated oscillator, not the expected offset of a synchronized host.

Actual oscillator specifications and clock behavior vary with hardware, temperature, virtualization, and time-service corrections. Measure the host you depend on rather than treating a ppm example as a cluster-level accuracy figure.

NTP Synchronization Helps but Does Not Solve

NTP reduces skew but cannot eliminate it. Several reasons:

  1. Round-trip latency uncertainty: NTP estimates network delay but cannot measure it exactly
  2. Clock stepping: When NTP corrects large errors, it might step the clock forward or backward
  3. Leap seconds: These cause unusual clock behavior
  4. Virtual machine effects: VMs running on shared infrastructure see erratic clock behavior
graph TD
    A[Server A Clock] -->|drifts| B[A: 10:00:00.050]
    A2[Server B Clock] -->|drifts| C[B: 10:00:00.100]

    D[NTP Server] -->|syncs| B
    D -->|syncs| C

    Skew["50ms skew persists even after NTP sync"]

NTP offset depends on the source, network path, host clock, time service, and configuration. “Synchronized” reports that a client is using a time source; it is not a guarantee that two machines agree within a fixed number of milliseconds. Measure the offset and uncertainty on the hosts that matter, then compare those readings with the application’s tolerance. The NTP specification describes the protocol, not a universal accuracy service level.


How Clock Skew Breaks Systems

Problem 1: Incorrect Event Ordering

The most common issue is events appearing to happen in the wrong order. A write at 10:00:00.000 on Server A might have a lower timestamp than a causally-dependent write at 10:00:00.001 on Server B, even though B’s write depended on A’s.

// Example: two-server timestamp ordering failure
// Server A: writes x=1 at wall-clock 10:00:00.000
// (A's clock is 50ms slow)
// Server B: receives A's message, writes y=x at wall-clock 10:00:00.001
// (B's clock is perfectly synchronized)

// On disk: timestamps suggest B's write happened AFTER A's
// But if B's clock was 50ms slow relative to A's at that moment,
// A's write might actually have happened AFTER B's write
// Causality is violated!

This breaks database replication, distributed logging, and any system that relies on timestamps to determine what happened first.

Problem 2: Cache Invalidation Failures

Cache invalidation often uses timestamps. If your cache key is “last-modified-time”, clock skew causes stale cache to be served:

// Cache invalidation with timestamps
async function getUser(userId) {
  const cached = await cache.get(`user:${userId}`);
  const lastModified = await db.getLastModified(userId);

  if (cached && cached.modified >= lastModified) {
    return cached.data; // Problem: if DB server clock is ahead,
    // lastModified might be in the future
  }

  const fresh = await db.getUser(userId);
  await cache.set(`user:${userId}`, fresh, lastModified);
  return fresh;
}

Problem 3: Lease and Expiration Bugs

Distributed systems often use leases with timeouts. If clock skew causes a lease to appear valid when it should have expired, you get split-brain scenarios:

// Lease-based lock
async function acquireLock(resourceId, ttlSeconds) {
  const leaseExpiry = Date.now() + ttlSeconds * 1000;

  const acquired = await redis.set(
    `lock:${resourceId}`,
    myInstanceId,
    "NX", // Only if not exists
    "PX", // Set expiry in milliseconds
    ttlSeconds * 1000,
  );

  if (acquired) {
    return { success: true, expiresAt: leaseExpiry };
  }

  // Problem: another instance might see this lease as expired
  // while the lock holder still thinks it holds the lock
  return { success: false };
}

Problem 4: JWT and Security Token Issues

JSON Web Tokens include expiration times. If server clocks disagree about the current time, tokens might be accepted or rejected incorrectly:

// JWT verification
const token = jwt.sign({ userId: 123 }, secret, { expiresIn: "1h" });

// Server A (ahead 30s): issues token valid until 11:30
// Server B (behind 30s): at 11:00, sees token as not yet valid!

// This can allow replay attacks or block legitimate users

Silent Data Corruption

The most dangerous clock skew issues are silent. The system appears to work, but data is subtly wrong.

Example: Last-Write-Wins Databases

Consider a last-write-wins (LWW) database using timestamps for conflict resolution. Server A and Server B both write to the same key:

sequenceDiagram
    participant A as Server A
    participant B as Server B
    participant DB as Database

    Note over A: Clock drifts -100ms
    Note over B: Clock drifts +50ms

    A->>DB: Write K=V1 at T=1000
    B->>DB: Write K=V2 at T=1050

    Note over DB: DB clock = T=1025

    Note over DB: LWW keeps V2 (higher timestamp)<br/>But V1 was actually written 75ms AFTER V2!
    Note over DB: Data corruption!

The database made the wrong decision. The user wanted V1 but got V2. No error occurred, no exception was thrown. The data is simply wrong.

The Heisenbug Problem

Clock skew bugs are heisenbugs: they disappear when you look at them. Adding logging changes timing. Debugging affects the system enough that the bug no longer manifests.

// You add this log to debug:
console.log(`Writing at ${Date.now()}`);

// The I/O for logging slightly changes timing
// The race condition that depended on precise timing no longer triggers
// The bug appears to fix itself when you try to observe it

Detecting Clock Skew

Active Monitoring

Monitor clock offset between your servers and a reference time source:

#!/bin/bash
# Inspect chrony's measured synchronization state and offset estimates.
chronyc tracking

# Set alert thresholds from the service's actual time tolerance.
# A synchronized status alone is not an accuracy bound.

Passive Detection

Detect skew from application behavior, not just clock comparisons:

// Detect skew from message timestamps
function detectClockSkew(messages) {
  // Sort by send timestamp, then by receive timestamp
  // If receive timestamps violate send ordering, skew is likely

  const sorted = [...messages].sort((a, b) => {
    const sendDiff = a.sendTime - b.sendTime;
    if (sendDiff !== 0) return sendDiff;
    return a.recvTime - b.recvTime;
  });

  let violations = 0;
  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i].recvTime < sorted[i - 1].recvTime) {
      violations++;
    }
  }

  return { violations, skewLikely: violations > 0 };
}

Responding When Offset Exceeds the Tolerance

Treat the threshold as an application requirement. When a host crosses it, compare the measured offset and source on that host, check whether the correction service is healthy, and determine which workflows rely on wall time. Use a monotonic clock for elapsed durations; pause or fence operations that require a clock bound the system can no longer meet. Prefer gradual correction when the time daemon supports it, and plan any clock step because timers, leases, and timestamp ordering may be affected. After recovery, verify both the measured offset and the application invariant that triggered the alert.

The sample alert thresholds below are placeholders. Set them from the database or application’s documented clock tolerance, and verify the metric’s units and semantics for the exporter version in use.

Distributed Tracing for Skew Detection

Modern tracing systems can detect clock skew from trace data:

// Jaeger-style span timing
// If a child span starts before its parent ends, clock skew exists
function validateSpanTiming(span) {
  if (span.startTime < span.parent.endTime) {
    return { valid: false, issue: "child-before-parent" };
  }

  if (span.endTime > span.startTime + MAX_SPAN_DURATION) {
    return { valid: false, issue: "duration-anomaly" };
  }

  return { valid: true };
}

Mitigating Clock Skew

Use Logical Clocks Instead

For event ordering, use logical clocks rather than physical timestamps:

// Instead of:
const timestamp = Date.now();

// Use:
const logicalTime = lamportClock.tick();

The Logical Clocks and Vector Clocks posts cover this in depth.

Fencing Tokens

For distributed locks, use fencing tokens that increment with each write:

class FencedLock {
  async acquire(resourceId) {
    const lock = await redis.set(
      `lock:${resourceId}`,
      fencingToken++,
      "NX",
      "EX",
      30,
    );

    if (lock) {
      return { acquired: true, token: fencingToken };
    }
    return { acquired: false };
  }

  async write(resourceId, data, token) {
    // Check token on write - reject if lower than last successful token
    const lastToken = await redis.get(`lastToken:${resourceId}`);

    if (token <= lastToken) {
      throw new Error("Stale write rejected");
    }

    await redis.set(`lastToken:${resourceId}`, token);
    await redis.set(`data:${resourceId}`, data);
  }
}

Hybrid Logical Clocks

A Hybrid Logical Clock (HLC) combines a physical-time component with a logical counter. A correct implementation can keep timestamps monotonic and preserve the happened-before order for events whose messages carry HLC state and update the receiving clock. That guarantee depends on the protocol: a timestamp alone cannot reveal an application dependency that was never propagated. Concurrent events can still be ordered by a tie-breaker; that total order does not prove one event caused the other. See the HLC paper and a database’s implementation notes before using an HLC as a correctness mechanism.

The sketch below shows the receive rule only. It is explanatory pseudocode, not a production clock: a real implementation must define serialization, overflow, restart behavior, clock bounds, and how messages carry the timestamp.

receive(local = (l, c), remote = (l′, c′), physicalNow):
  nextL = max(l, l′, physicalNow)
  if nextL == l and nextL == l′:
    nextC = max(c, c′) + 1
  else if nextL == l:
    nextC = c + 1
  else if nextL == l′:
    nextC = c′ + 1
  else:
    nextC = 0
  return (nextL, nextC)

A Small Timeline: Wall Clock, Lamport, and HLC

Node A updates an account and sends the update to node B. B applies it after receiving the message, but B’s wall clock is behind A’s.

Event Wall-clock reading Lamport counter HLC
A writes and sends 10:00:00.010 7 (10:00:00.010, 0)
B receives and applies 10:00:00.005 8 (10:00:00.010, 1)

Wall-clock values appear reversed even though the message establishes an order. Lamport counters preserve that happened-before relation but carry no calendar time. An HLC can retain a physical component while advancing its logical counter on receipt. The receiving node must process the message timestamp before creating its dependent event.

UTC vs TAI: Understanding Time Scales

There is confusion about time scales that matters for distributed systems. UTC (Coordinated Universal Time) is not continuous—leap seconds cause it to repeat or skip. TAI (International Atomic Time) is continuous but not commonly used.

// The problem with UTC leap seconds
// TAI is continuous: ... TAI-32: 1000000000, TAI-32: 1000000001, ...
// UTC is not: 2016-12-31 23:59:59 UTC, then 2016-12-31 23:59:60 UTC (leap second), then 2017-01-01 00:00:00 UTC

// Most systems use UTC but handle leap seconds poorly
// Some systems use TAI internally for continuous time

// Google Spanner uses TrueTime which accounts for uncertainty bounds
// CockroachDB uses Hybrid Logical Clocks (HLC)

UTC characteristics:

  • Based on atomic time but corrected with leap seconds
  • Not continuous—can repeat or skip seconds
  • Used by NTP and most operating systems
  • The UTC–TAI offset changes when leap seconds are introduced; systems should obtain it from a maintained time source rather than hard-code it.

TAI characteristics:

  • Pure atomic time, no leap seconds
  • Continuous and monotonically increasing
  • Used in scientific contexts and some databases
  • Not directly available on most systems

For continuous time systems:

  • Use TAI internally if your application cannot tolerate leap seconds
  • Some Linux systems expose CLOCK_TAI; support and maintenance depend on the kernel and time configuration
  • GPS time is TAI-based (minus small offset)
# Check if your system supports CLOCK_TAI
# Check support and time-source configuration for the deployed kernel
clock_gettime(CLOCK_TAI, &ts);

// Verify TAI support
cat /proc/version | grep -i tai
# Or check via chrony
chronyc sources | grep TAI

NTP Clock Slewing vs Stepping

NTP has two modes for correcting clock drift: slewing and stepping. Understanding when each is used matters for your application.

Clock Slewing (preferred for most applications):

  • Adjusts the clock frequency slightly to gradually correct drift
  • Clock continues forward without jumps
  • No effect on gettimeofday() or clock_gettime()
  • Safe for applications that measure elapsed time between events
  • Uses the -x flag in ntpd or is default in chrony

Clock Stepping (can cause problems):

  • Directly changes the clock value
  • Can make time go backward or forward suddenly
  • Breaks applications that calculate elapsed time
  • Can cause issues with databases, caches, and security tokens
# Configure chrony for slewing (default behavior)
# /etc/chrony/chrony.conf
# By default, chrony uses slewing for small offsets

# To enable stepping for large offsets (not recommended):
# maxdistance 1.0
# This allows stepping for offsets > 1 second

# For ntpd, use -x for slewing only:
# ntpd -x -g -q
# -x: slew instead of step
# -g: step if offset exceeds panic threshold
# -q: query only and exit

# Check current NTP behavior
chronyc tracking | grep "System time"
# Output shows if time is being slewed or stepped
# "slew" means slewing is active
# "step" would indicate stepping occurred

When to use each:

Scenario Recommended Mode Reason
Normal operation Slewing No time jumps, safe for all apps
Large initial offset Stepping once at startup Get into sync quickly
Real-time trading Slewing only Cannot have time going backwards
Scientific computing Slewing only Elapsed time must be accurate
Virtual machines Slewing (with hypervisor sync) VM clock can drift erratically

Vendor-Specific Time Synchronization

Cloud providers offer time-sync options, but an endpoint or “synchronized” status does not establish an accuracy bound for every guest and workload. Network path, VM configuration, host behavior, and the provider’s product all matter. Use the provider’s current instructions for endpoint configuration, then measure the resulting offset from the application’s point of view. The examples below are configuration starting points, not precision guarantees.

Cloud Provider Time Sync

AWS Time Sync Service
# AWS EC2: Use the link-local time sync service
# Available at 169.254.169.123 (no network hops needed)

# For Amazon Linux / RHEL / CentOS:
# Already configured by default with chrony
cat /etc/chrony/chrony.conf
# Should show: server 169.254.169.123 prefer iburst

# For Ubuntu/Debian with systemd-timesyncd:
cat /etc/systemd/timesyncd.conf
[Time]
NTP=169.254.169.123
FallbackNTP=

# Verify it's working
timedatectl status
# Should show "System clock synchronized: yes"

# Check measured offset and consult current AWS time-service guidance; no fixed accuracy is assumed.
Google Cloud Platform Time Sync
# GCP: Use the metadata server for time
# metadata.google.internal provides time via DHCP/metadata

# For Debian/Ubuntu:
cat /etc/systemd/timesyncd.conf
[Time]
NTP=metadata.google.internal
FallbackNTP=time.google.com

# For CentOS/RHEL with chrony:
echo "server metadata.google.internal iburst" >> /etc/chrony/chrony.conf
systemctl restart chronyd

# Verify
chronyc tracking
# Should show Reference ID of metadata.google.internal

# GCP also offers Google Public NTP at time.google.com
# for non-GCP infrastructure
Microsoft Azure Time Sync
# Azure VMs get time from the host server by default
# For explicit NTP configuration:

# Ubuntu/Debian:
cat /etc/systemd/timesyncd.conf
[Time]
NTP=time.windows.com

# CentOS/RHEL with chrony:
echo "server time.windows.com iburst" >> /etc/chrony/chrony.conf
systemctl restart chronyd

# Verify Azure VM time sync
systemctl status systemd-timesyncd
timedatectl status

# Verify the configured source and measured offset; follow current Azure guidance for the VM image.
Verification Commands for All Providers
# Common verification commands across all platforms

# Check current time sync status
timedatectl status
# Look for:
# - System clock synchronized: yes/no
# - NTP service: active/inactive
# - Time zone and offset

# Check detailed NTP statistics with chrony
chronyc sources -v
# Columns: M=mode, S=state, * = current sync, # = selected
# ^ indicates good sources

chronyc sourcestats
# Look for: sd (standard deviation) - lower is better

# Check for clock offset
chronyc tracking | grep "System time"
# Shows offset and whether it's being slewed or stepped

# Test NTP query directly
ntpdate -q pool.ntp.org
# Shows offset from multiple NTP servers

# For Prometheus node_exporter metrics (if installed)
curl localhost:9100/metrics | grep node_timex
# node_timex_offset_seconds - current offset
# node_timex_maxerror_seconds - maximum estimated error
# node_timex_sync_status - 1 if synced
# node_timex_loop_time_constant - PLL time constant

Application-Level Skew Detection from Database Replication

Beyond monitoring clocks directly, you can detect clock skew from database behavior:

// Detect clock skew from replication timestamps
async function detectSkewFromReplication(db) {
  // Most databases track replication lag with timestamps
  const replicationStatus = await db.query(`
    SELECT
      application_name,
      pg_last_xact_replay_timestamp() as replay_time,
      now() as current_time,
      now() - pg_last_xact_replay_timestamp() as lag
    FROM pg_stat_replication
  `);

  for (const replica of replicationStatus.rows) {
    const lagMs = replica.lag;
    const clockOffset = new Date(replica.current_time) - replica.replay_time;

    // If lag is small but clock offset is large, clocks are skewed
    if (lagMs < 1000 && Math.abs(clockOffset) > 100) {
      console.warn(`Clock skew detected on ${replica.application_name}`, {
        lagMs,
        clockOffsetMs: clockOffset,
      });
    }
  }
}

// MySQL replication skew detection
async function detectMySQLSkew(connection) {
  const [rows] = await connection.query(`
    SELECT
      Source_Log_File,
      Read_Master_Log_Pos,
       Relay_Log_File,
      Relay_Log_Pos,
      Seconds_Behind_Master
    FROM SHOW SLAVE STATUS
  `);

  for (const replica of rows) {
    // Seconds_Behind_Master > 0 indicates lag
    // But sudden jumps might indicate clock skew
    if (replica.Seconds_Behind_Master > 0) {
      console.warn("Replication lag detected", replica);
    }
  }
}

Prometheus node_timex Metrics Reference

For comprehensive clock monitoring in Prometheus:

# prometheus.yml
scrape_configs:
  - job_name: "node"
    static_configs:
      - targets: ["localhost:9100"]

# Key metrics to monitor:
# node_timex_offset_seconds - Current clock offset from NTP server
#   Alert threshold: > 0.1 seconds (warning), > 0.5 seconds (critical)

# node_timex_maxerror_seconds - Maximum estimated error
#   Should be relatively stable, spikes indicate issues

# node_timex_sync_status - Whether clock is synchronized
#   0 = unsynchronized, 1 = synchronized

# node_timex_loop_time_constant - Phase-locked loop time constant
#   Affects how quickly clock adjustments are made

# node_timex_frequency_adjustment - Current frequency adjustment in ppm
#   Large values indicate unstable clock

# Alerting rules for clock skew
groups:
  - name: clock_alerts
    rules:
      - alert: ClockOffsetHigh
        # Example only; set from the application clock-error budget.
        expr: abs(node_timex_offset_seconds) > 0.1
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Clock offset exceeds 100ms on {{ $labels.instance }}"
          description: "Offset: {{ $value }} seconds"

      - alert: ClockOffsetCritical
        # Example only; set from the application clock-error budget.
        expr: abs(node_timex_offset_seconds) > 0.5
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Clock offset exceeds 500ms on {{ $labels.instance }}"
          description: "Critical clock skew: {{ $value }} seconds"

      - alert: ClockSyncLost
        expr: node_timex_sync_status == 0
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "NTP synchronization lost on {{ $labels.instance }}"

Tight NTP Synchronization

For applications that must use physical time, use tighter NTP synchronization:

# Use multiple NTP servers for better accuracy
# /etc/chrony/chrony.conf

server time1.google.com iburst
server time2.google.com iburst
server time3.google.com iburst

# Increase polling frequency for tighter sync
minpoll 4
maxpoll 6

# Enable hardware timestamping if available
hwtimestamp *

# Set maximum allowed offset
maxdistance 1.0

Reference Clocks for Critical Systems

For financial or trading systems, use dedicated reference clocks:

# GPS-based NTP server for critical infrastructure
# Stratum 1 server with GPS receiver

# /etc/chrony/chrony.conf
refclock GPS /dev/pps0 poll 3 precision 1e-9
refclock SHM 0 offset 0.5 delay 0.001 refid NMEA

Illustrative Failure Scenario: Clock Step During a Request

Imagine a service that calculates a timeout by subtracting two wall-clock readings. An administrator corrects a large offset by stepping the clock backward while a request is running. The second reading can be earlier than the first, so the computed elapsed time is negative. This example is hypothetical; the failure depends on the operating system, time service, and application. Use a monotonic clock for elapsed-time measurement, and test how the application behaves when wall time moves forward or backward.


Common Pitfalls / Anti-Patterns

Do

// DO: Use logical clocks for ordering
const order = lamportClock.tick();

// DO: Use fencing tokens for distributed writes
await writeWithFencing(key, value, fencingToken++);

// DO: Monitor clock offsets
metrics.gauge("clock_offset_ms").set(measureOffset());

// DO: Use hybrid approaches for user-facing timestamps
// Show wall-clock time, use logical time internally

Do Not

// DO NOT: Use wall-clock for conflict resolution
if (remote.timestamp > local.timestamp) return remote;

// DO NOT: Assume clocks are synchronized across regions
const t1 = await fetchFromUS(key);
const t2 = await fetchFromEU(key); // t2 might have different clock source

// DO NOT: Use timestamps as unique identifiers
const id = `${Date.now()}-${random()}`; // Collisions possible

Quick Recap Checklist

Monitoring

  • Clock offset from reference (alert at 100ms, critical at 500ms)
  • Clock drift rate per server
  • NTP synchronization failures
  • Leap second announcement alerts

Testing

  • Inject clock skew in testing environments
  • Test with NTP stopped for extended periods
  • Verify behavior during leap seconds
  • Test failover with clocks at different offsets

Design Review

  • Identify all uses of wall-clock time
  • Replace timestamp-based ordering with logical clocks
  • Add fencing tokens to any distributed write path
  • Review session/token expiration for clock skew tolerance

Trade-off Analysis

When designing systems that handle time, various approaches trade accuracy for complexity, latency, or operational overhead. Here are the key trade-offs:

Approach Accuracy Complexity Latency Impact Best For
Wall-clock only Depends on the time source and host Low None Human-readable event times; not a causal-order guarantee
NTP synchronization Must be measured in the target environment Low to moderate Network and correction behavior vary Systems that need synchronized civil time
Provider time service Use provider documentation and measure guest offset Low to moderate Provider-specific Cloud workloads
GPS/PTP reference Deployment and hardware dependent High Network and hardware dependent Workloads with a justified precision requirement
Lamport clock Orders events when messages propagate clock state Medium None Happened-before ordering without calendar time
Vector clock Tracks causal relationships and concurrency Higher metadata cost None Detecting concurrent updates
HLC Physical component plus logical ordering Implementation dependent None by itself Systems that propagate HLC metadata and define clock bounds
TrueTime Returns an uncertainty interval Provider implementation dependent May require waiting out uncertainty Systems such as Spanner that use the API protocol

Key insights:

  • No physical clock provides perfect global time. Logical ordering records information that the wall clock cannot provide.
  • HLCs can preserve happened-before relationships when the protocol propagates clock state; they do not infer dependencies that the application never communicates.
  • Stratum 1 GPS infrastructure only makes sense when the cost of clock skew exceeds the hardware and operational cost of running it

Interview Questions

1. You notice that Server A's clock is 50ms ahead of Server B's. Both servers are running NTP and appear synchronized. Why might this be a problem for a distributed database using timestamp-based conflict resolution?

Expected answer points:

  • Last-write-wins databases may choose the wrong version—writes that happened first at the source could be discarded if their timestamps appear later
  • The 50ms skew means causally-dependent writes can appear in reversed order, violating application-level invariants
  • A synchronization status is not an offset measurement or an accuracy guarantee; inspect the measured offset and the database’s clock assumptions
2. A service uses wall-clock timestamps to invalidate cached responses based on a `max-age` value fetched from another service. What clock skew scenario causes stale cache to be served, and how does it manifest?

Expected answer points:

  • If the cache's server has a clock behind the origin server, the `modified` timestamp comparison sees lastModified as greater than the cached version's timestamp, causing premature stale returns
  • Conversely, if cache server clock is ahead, it may think content is fresh when origin already updated
  • The issue is asymmetric: whichever server has the higher clock wins the comparison regardless of actual freshness
3. Explain the difference between clock skew and clock drift. Why do engineers sometimes call clock skew bugs "heisenbugs"?

Expected answer points:

  • Clock skew is the difference between two clocks at a single point in time; clock drift is the rate at which a clock runs fast or slow relative to true time
  • Heisenbugs disappear when you observe them—adding logging changes I/O timing, which changes the precise timing conditions the bug depends on
  • The act of measurement changes the system enough that the race condition no longer triggers
4. Your team wants to use wall-clock timestamps for distributed event ordering. What is the fundamental limitation that makes this approach unreliable across data centers?

Expected answer points:

  • Wall-clock readings can disagree because of drift, offset, network asymmetry, or correction behavior; measure the actual hosts rather than assuming a fixed range
  • If B receives a message from A and then performs a dependent write, B’s wall-clock timestamp can still sort before A’s timestamp
  • Logical clocks can preserve a happened-before relation when the timestamp is propagated through messages; a Lamport timestamp comparison alone does not prove causality in both directions
5. Describe how a fencing token solves the problem of stale lock holders in a distributed lock implementation.

Expected answer points:

  • When acquiring a lock, the holder receives a monotonically increasing token
  • On every write operation, the token must be presented—writes with tokens lower than the last successful token are rejected
  • Even if clock skew causes a lock to appear valid to an expired holder, the rejected write still prevents corruption
  • The token increments on each successful lock acquisition, so no two holders can have the same token
6. Why can a leap-second correction affect wall-clock applications, and how would you test your system’s response?

Expected answer points:

  • Time services and operating systems may step, slew, or smear time; application behavior depends on that correction strategy
  • Code that assumes wall time always advances uniformly can miscalculate deadlines, ordering, or elapsed time
  • Test with a controlled clock abstraction or an isolated test environment; do not inject a time step into a production host
  • Use monotonic time for elapsed durations and keep civil timestamps for display and external records
7. Your application uses JWT tokens with `exp` claims for authentication. Server A's clock is 30 seconds ahead of Server B's. What security or availability issues can occur?

Expected answer points:

  • Server A issues a token valid until 11:30; Server B at 11:00 sees the token as not yet valid, blocking legitimate users
  • This can enable replay attacks if an attacker captures a token that one server rejects but another accepts
  • Tokens may be accepted or rejected inconsistently depending on which server handles the request
8. What is the difference between NTP clock slewing and clock stepping? When would you prefer one over the other?

Expected answer points:

  • Slewing adjusts clock frequency gradually—time continues forward without jumps; preferred for real-time apps, trading systems, and anywhere elapsed time calculations matter
  • Stepping directly changes the clock value—time can jump forward or backward; breaks any code that calculates elapsed time between events
  • For financial trading or scientific computing, slewing is mandatory—you cannot have time going backwards
9. Explain Hybrid Logical Clocks (HLCs). How do they combine physical and logical time, and why would you choose HLCs over pure logical clocks?

Expected answer points:

  • An HLC combines a physical component with a logical counter and can retain happened-before order when messages propagate timestamps and receivers update their clocks
  • Events without a causal path can still be ordered by tie-breaker; the HLC order does not mean one event caused the other
  • HLC implementations need explicit choices for clock bounds, restarts, serialization, and overflow
  • CockroachDB documents its HLC assumptions; Spanner’s TrueTime is a separate API that exposes clock uncertainty
10. You need to monitor clock skew across 100 servers in multiple regions. What metrics would you collect, and what alert thresholds would you set?

Expected answer points:

  • Use a host offset metric such as `node_timex_offset_seconds`; set alert thresholds from the application’s documented tolerance rather than copying a universal value
  • Track `node_timex_maxerror_seconds` for maximum estimated error; spikes indicate problems
  • Monitor `node_timex_sync_status` (1 = synced, 0 = unsynchronized) for loss of NTP sync
  • Check `node_timex_frequency_adjustment` for unstable clocks (large ppm values indicate oscillator problems)
11. A distributed trace shows a child span starting before its parent span ended. What does this indicate, and how would you investigate it?

Expected answer points:

  • Clock skew exists between the machines recording the parent and child spans—child's machine clock is behind parent's
  • Could be VM clock drift, network asymmetry, or NTP not yet synced on one machine
  • Investigate by checking clock offsets against a reference time source on all hosts involved in the trace
12. Your PostgreSQL replica shows replication lag under 1 second, but the clock offset between primary and replica exceeds 100ms. What does this indicate, and what is the risk?

Expected answer points:

  • Replication lag measures how far behind the replica is in applying WAL; small lag with large clock offset means the clocks themselves are skewed, not just replication slow
  • Timestamp-based queries or time-dependent constraints may behave incorrectly across primary and replica
  • The replica may serve stale data for read-after-write patterns if the application checks timestamps
13. What is CLOCK_TAI and why might a distributed system prefer it over CLOCK_REALTIME (UTC-based)?

Expected answer points:

  • CLOCK_TAI expresses time on the TAI scale and does not label leap seconds as UTC does; the UTC–TAI offset changes when leap seconds are introduced
  • Do not treat CLOCK_TAI as a monotonic elapsed-time clock; system synchronization can adjust clock readings
  • Use CLOCK_MONOTONIC for measuring durations and deadlines, and check the operating system documentation for clock semantics
14. Explain how Google Spanner's TrueTime API handles clock uncertainty. Why is this important for distributed transaction ordering?

Expected answer points:

  • TrueTime returns a time interval `[earliest, latest]` instead of a point estimate, explicitly representing uncertainty bounds
  • A transaction can only commit when the wall time has advanced past the transaction's start time by at least the maximum uncertainty interval
  • This guarantees that if Transaction A commits before Transaction B starts in real time, B sees A's commit as in the past
  • Spanner waits until the uncertainty interval has passed before exposing a commit timestamp; the wait depends on the interval, not a universal fixed duration
15. Hypothetical example: an EC2 host shows a large offset from its time source. What AWS time-sync option could you check, and how would you measure the host's offset?

Expected answer points:

  • AWS documents the Amazon Time Sync Service and its available endpoints for EC2; the configured endpoint depends on instance and operating-system setup.
  • Inspect the active time client configuration and its sources using the tools for that operating system, such as chronyc sources and chronyc tracking for chrony.
  • Use the reported offset and uncertainty to compare with the application's tolerance. A synchronized status alone does not prove that the offset meets a particular bound.
16. Your team considers using wall-clock timestamps as unique identifiers for requests. What is the fundamental problem with this approach in a distributed system?

Expected answer points:

  • Wall-clock timestamps can repeat at the available resolution and do not coordinate uniqueness across hosts
  • Appending a random or host-specific component changes the collision model but does not make time itself unique
  • Use an identifier scheme whose uniqueness assumptions match the deployment, and document its clock and coordination requirements
17. A microservices system uses wall-clock time to determine which of two conflicting updates to accept. What is a safer alternative that does not require perfectly synchronized clocks?

Expected answer points:

  • Vector clocks can distinguish some causally ordered updates from concurrent ones; concurrent versions still need a merge or conflict policy
  • Lamport clocks preserve happened-before order when propagated, but a smaller Lamport value does not prove causality in the reverse direction
  • Fencing tokens can reject writes from an expired lock holder when the storage system checks the token
18. A replicated database uses timestamp-based conflict resolution across data centers. What clock-skew issues should you investigate?

Expected answer points:

  • Writes from hosts with different wall-clock readings can receive timestamps that do not match the application's causal or real-time order
  • A host with an ahead clock may cause its write to win a last-write-wins rule, depending on the database's timestamp and conflict-resolution semantics
  • Timestamp-based last-write-wins conflict resolution may select a write based on clock readings rather than the application’s causal order; the exact behavior depends on the database and write path
  • Check the database’s documented timestamp and consistency semantics, then choose an operation or data model that protects the invariant; LWT is not a general replacement for timestamp-based conflict handling
19. During a chaos engineering test, you inject 200ms of clock skew between two servers. What specific behaviors would you expect to observe in a system that relies on wall-clock for event ordering but does not use fencing tokens?

Expected answer points:

  • Events that were causally ordered in real time appear reversed in the application's event log
  • Cache invalidation fails—stale data is served because the cache key timestamp is compared against a server with the skewed clock
  • Database writes may be lost or cause phantom conflicts if using LWW conflict resolution
  • JWT or session tokens may be rejected or accepted inconsistently
20. Your CTO asks you to recommend a time synchronization architecture for a high-frequency trading system where 1ms of clock skew can affect P&L reporting. What do you recommend and why?

Expected answer points:

  • Start from the venue, regulator, and reporting requirements; define an end-to-end error budget for the timestamping path
  • Evaluate PTP, hardware timestamping, reference clocks, and the host NIC together; a GPS receiver alone does not prove the application’s timestamps meet a bound
  • Use monotonic time for elapsed durations and document how civil time is represented in reports
  • Test failure, holdover, source loss, and clock correction behavior in an isolated environment
  • Set alert thresholds from the required error budget and measured host behavior, with an owner for response and failover

Further Reading

Core Concepts

  • Physical Clocks — Deep dive into hardware clocks, oscillator drift, and time scale foundations
  • Logical Clocks — Lamport clocks and why physical time fails for ordering
  • Vector Clocks — Distributed conflict resolution without centralized coordination

Operational


Conclusion

Physical clocks provide calendar time, but their readings alone do not establish the order of events on different machines. Lamport clocks and HLCs can preserve causal information when systems propagate and update their timestamps; use fencing tokens or another explicit mechanism when a storage system must reject stale writers. Choose the mechanism from the invariant the application needs.

For more on clock solutions, see Physical Clocks, Logical Clocks, and Vector Clocks.

Category

Related Posts

Logical Clocks: Lamport Timestamps and Event Ordering

Understand Lamport timestamps, vector clocks, and hybrid logical clocks through one trace that shows causal order and concurrent events.

#distributed-systems #distributed-computing #logical-clocks

Physical Clocks in Distributed Systems: NTP and Synchronization

Learn how physical clocks work in distributed systems, including NTP synchronization, clock sources, and the limitations of wall-clock time for ordering events.

#distributed-systems #distributed-computing #clock-synchronization

TrueTime: Google's Globally Synchronized Clock Infrastructure

Learn how Google uses TrueTime for globally distributed transactions with external consistency. Covers the Spanner system, time bounded uncertainty, and HW-assisted synchronization.

#distributed-systems #distributed-computing #true-time