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.
Linux exposes different clocks for civil timestamps and elapsed-time measurements. `CLOCK_REALTIME` can be adjusted, `CLOCK_MONOTONIC` does not jump backward and stops during suspend, and `CLOCK_BOOTTIME` includes suspended time. NTP and chrony estimate and reduce clock offset, but their measurements still have uncertainty. Synchronized clocks cannot establish which of two distributed events caused the other; logical clocks and hybrid logical clocks carry ordering information when systems propagate it.
Introduction
Hardware Clocks
Linux timekeeping combines a hardware counter with a software time model. The kernel selects a clocksource available on that machine; examples include an invariant TSC on some x86 systems, an HPET, or an architecture-specific counter. The selected source and its quality depend on the hardware and kernel.
The real-time clock (RTC) can preserve calendar time while a machine is powered off. The kernel’s active clocksource provides counter ticks while it is running. These are different parts of the timekeeping system, not two interchangeable clocks:
# Show the kernel's selected clocksource on this machine
cat /sys/devices/system/clocksource/clocksource0/current_clocksource
# Check whether systemd reports a synchronized wall clock
timedatectl status
The command reports the clocksource selected on this host. Values such as tsc, hpet, or acpi_pm are examples, not a portable list. A clocksource reading by itself does not tell you how closely the wall clock matches UTC. See the Linux kernel’s timekeeping documentation for the clocksource model.
The System Clock
The kernel maintains software time from its selected clocksource. Applications can read it through APIs such as clock_gettime() or a language runtime’s clock functions:
// JavaScript: uses the system clock
const now = Date.now(); // Milliseconds since epoch
// Go: uses the system clock
import "time"
t := time.Now().UnixNano() // Nanoseconds since epoch
// C: uses gettimeofday
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t microseconds = (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
The epoch is typically January 1, 1970 UTC (the Unix epoch), though some systems use different starting points.
Linux clock APIs
Linux applications can ask for clocks with different behavior. Choose by what the measurement needs to mean:
| Clock | Behavior | Use it for |
|---|---|---|
CLOCK_REALTIME |
Calendar time since the Unix epoch. It can be stepped by an administrator or time service and adjusted by synchronization. | Timestamps that people compare with UTC or local dates. |
CLOCK_MONOTONIC |
Does not jump backward when wall time changes, but its rate can be adjusted. It does not include time spent suspended. | Measuring elapsed time while the machine is awake. |
CLOCK_BOOTTIME |
Like CLOCK_MONOTONIC, but includes time spent suspended. |
Deadlines and timeouts that should expire across suspend. |
These clocks are not interchangeable. clock_getres() reports a clock’s resolution, not its accuracy relative to UTC. See the Linux clock_gettime(2) manual for platform details.
Linux Kernel Timekeeping Architecture
Linux’s timekeeping subsystem hides hardware differences and provides clock values to applications.
Kernel timekeeping state
Linux keeps kernel-private state that converts clocksource readings into wall-clock and elapsed-time values. Those internal structures change between kernel versions; applications should use public clock APIs such as clock_gettime() instead of depending on kernel fields.
Clocksource Management
Linux manages multiple clock sources through an abstraction layer:
# List available clocksources
cat /sys/devices/system/clocksource/clocksource0/available_clocksource
# Output: tsc hpet acpi_pm
# Current active clocksource
cat /sys/devices/system/clocksource/clocksource0/current_clocksource
# Output: tsc
The kernel’s clocksource abstraction provides a way to read a counter and convert its cycles into time values. Internal fields and conversion details can change; applications can inspect the active and available sources through the sysfs paths above. The Linux kernel’s timekeeping documentation describes these abstractions.
VDSO and Time Acceleration
For performance, Linux can expose functions such as clock_gettime() through the vDSO (virtual dynamic shared object), avoiding a system call on supported architecture and clock combinations. See the vdso(7) manual.
# Check whether this shell has a vDSO mapping
grep '\[vdso\]' "/proc/$$/maps"
# The vDSO may provide:
# - clock_gettime(CLOCK_REALTIME)
# - clock_gettime(CLOCK_MONOTONIC)
# - gettimeofday()
Whether a call uses the vDSO depends on the architecture, clock, kernel, and C library. The vDSO shares timekeeping data with user space; it is an implementation detail, not a separate clock or accuracy guarantee.
adjtimex and NTP Control
The adjtimex() system call provides low-level access to the kernel’s NTP state:
struct timex tx;
memset(&tx, 0, sizeof(tx));
tx.modes = ADJ_OFFSET; // Set adjustment mode
tx.offset = 500; // 500 microseconds offset
adjtimex(&tx);
// Check kernel NTP status
tx.modes = 0;
adjtimex(&tx);
printf("status: %d, offset: %ld, freq: %ld\n",
tx.status, tx.offset, tx.freq);
Key fields:
offset: Current time adjustment in microsecondsfreq: Frequency offset in parts per million (ppm)status: Clock status flags (STA_PLL, STA_UNSYNC, etc.)maxerror: Maximum error estimate in microsecondsesterror: Estimated error in microseconds
time Namespace
Linux namespaces allow containers to have independent time offsets:
# Create a time namespace with offset
unshare --time --monotonic=3600 --boottime=7200
# Inside the namespace:
# Monotonic time starts at 3600s
# Boottime starts at 7200s
# Useful for testing time-dependent applications
The time namespace feature lets containers test time-dependent behavior without waiting for real time to pass.
timerfd and POSIX Timers
Linux provides high-resolution timers through timerfd:
#include <sys/timerfd.h>
// Create a timer
int tfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
// Set it to fire every 100ms
struct itimerspec spec;
spec.it_interval.tv_sec = 0;
spec.it_interval.tv_nsec = 100000000; // 100ms
spec.it_value.tv_sec = 0;
spec.it_value.tv_nsec = 100000000;
timerfd_settime(tfd, 0, &spec, NULL);
// Read events
uint64_t expirations;
read(tfd, &expirations, sizeof(expirations));
timerfd integrates with select(), poll(), and epoll, making it suitable for event-driven applications needing precise timing.
NTP Synchronization
The Network Time Protocol synchronizes system clocks to external time sources. It is the backbone of timekeeping on the internet.
How NTP Works
NTP uses a hierarchical system of time sources:
graph TD
A[External reference clocks] --> B[Stratum 1: Time Servers]
B --> C[Stratum 2: Downstream Servers]
C --> D[Stratum 3: Downstream Servers]
D --> E[Your Servers]
GNSS receivers, radio clocks, and atomic clocks can act as external reference sources; they are not NTP stratum-0 servers. Stratum indicates distance from a reference in the synchronization hierarchy, not a direct accuracy score. Use measured offset, root delay, and root dispersion to assess uncertainty on a specific path.
NTP Algorithm
NTP works by exchanging UDP packets.
// Simplified NTP exchange
// 1. Client sends timestamp T1
// 2. Server receives at T2
// 3. Server sends response at T3
// 4. Client receives at T4
// Round-trip delay:
delay = T4 - T1 - (T3 - T2);
// Clock offset:
offset = (T2 - T1 + (T3 - T4)) / 2;
NTP clients such as chronyd and ntpd compare samples from configured sources and adjust the system clock. They usually slew small corrections; whether a large correction is stepped depends on the client and its configuration.
Configuring NTP
On a Linux host configured with chrony, inspect the selected source and current synchronization estimate with:
# Install and start chrony
apt install chrony
# Check synchronization status
chronyc tracking
chronyc sources -v
chronyc tracking reports System time, Frequency, Root delay, Root dispersion, and Leap status. Chrony estimates clock error using the offset, root dispersion, and half the root delay; see its chronyc documentation. Chrony’s project gives a few milliseconds between Internet-synchronized machines and tens of microseconds on a LAN as typical examples. Actual error depends on the servers, client clock, and network path.
Clock Accuracy and Drift
Measuring Clock Drift
An oscillator’s rate varies by device, temperature, age, virtualization, and workload. There is no single drift range that applies to every host. For scale, an unsynchronized clock running 1 part per million fast gains about 86 milliseconds in a day. At 50 ppm, it gains about 4.3 seconds. These figures are unit conversions for a constant rate, not typical-device drift ranges.
# Inspect chrony's current frequency estimate and uncertainty.
# Compare measurements over time; do not force a time step on a live host.
chronyc tracking
chronyc sourcestats
Temperature Effects
Oscillator frequency can change with temperature, but the size and direction depend on the component. For virtual machines, scheduling pauses and migration can also affect the observed clock. Use the host’s synchronization measurements rather than assuming a temperature-to-drift table applies to your device.
Kernel clocksource examples
The kernel selects an available source for its timekeeping. The names below are examples; their behavior depends on the processor, firmware, kernel, and virtualization environment.
| Source | Where it comes from | What to check |
|---|---|---|
| TSC (Time Stamp Counter) | CPU counter on x86 systems | Whether the platform and hypervisor provide a stable, invariant counter |
| HPET | Platform timer | Whether the kernel selects it; presence does not make it the most accurate option |
| ACPI PM timer | Platform timer | Whether it is available and used on this host |
| Paravirtual clock | Hypervisor interface, such as kvm-clock |
Host and guest timekeeping configuration |
Inspect current_clocksource on the running system instead of assuming which source is active. A hardware counter’s resolution and rate stability also do not tell you the wall clock’s UTC error.
Limitations of Physical Clocks
Physical clocks have fundamental problems for distributed systems.
Clock Skew vs Clock Drift
Drift is the rate at which a clock runs fast or slow. Skew is the difference between two clocks at a point in time. Even if all your clocks drift at the same rate, skew accumulates because they started from different times.
sequenceDiagram
participant A as Server A
participant B as Server B
participant NTP as NTP Server
Note over A: Clock: 10:00:00.000
Note over B: Clock: 10:00:00.150
A->>NTP: Sync request
B->>NTP: Sync request
Note over A: After sync: 10:00:00.050
Note over B: After sync: 10:00:00.100
Note over A,B: Still 50ms apart due to previous drift
Non-Monotonic Clocks
System clocks can jump forward or backward. An NTP client may step an offset or slew the clock rate, depending on its implementation and configuration. A step can move wall time backward:
// Time going backward is possible with NTP sync
const t1 = Date.now(); // 1000
await doSomething();
const t2 = Date.now(); // 998 - time went backward!
Monotonic clocks solve this for relative time measurements, but they are not globally synchronized.
Leap Seconds
Leap seconds are announced when needed; they do not follow a fixed annual schedule. Linux CLOCK_REALTIME normally follows Unix time, which does not represent a second as 23:59:60. Around an announced insertion or deletion, the time client, kernel, or provider may step, slew, or smear the adjustment. Mixing hosts that use different policies can make their wall-clock readings disagree around the event.
# Check chrony's current leap status
chronyc tracking | grep "Leap status"
Record which leap policy your time sources use and check how dependent software handles it. Chrony can report Normal, Insert second, Delete second, or Not synchronised; its documentation also describes leap smearing. A particular 2015 kernel incident should not be generalized to all Linux hosts.
Using Physical Clocks in Distributed Systems
Despite their limitations, physical clocks are widely used. Knowing when to trust them matters.
When Physical Clocks Work
For non-critical timestamps and logging, wall-clock time is fine:
// Logging: wall-clock time is appropriate
logger.info({
event: "user_login",
timestamp: new Date().toISOString(), // Wall clock OK for logs
userId: user.id,
});
// Audit trails benefit from wall clock
// Even if slightly off, audit timestamps are for human readability
When Physical Clocks Fail
For ordering events or conflict resolution, physical clocks are dangerous:
// BAD: Using wall clock for conflict resolution
function resolveConflict(local, remote) {
// Assumes remote timestamp > local timestamp means remote is newer
// FAILS when clocks are skewed
if (remote.updatedAt > local.updatedAt) {
return remote;
}
return local;
}
The PACELC theorem post discusses why timestamp-based conflict resolution breaks down in distributed systems.
For event order, see logical clocks for Lamport timestamps and clock skew and HLCs for hybrid logical clocks. HLCs can preserve causal order when the application propagates their state; a synchronized wall clock alone cannot prove that one remote event caused another.
Millisecond vs Microsecond vs Nanosecond
Precision vs Accuracy
Precision is how finely you can measure time. Accuracy is how close that measurement is to a reference. A clock can report fine-grained values and still be inaccurate.
clock_getres() gives a clock’s reported resolution. Accuracy relative to UTC is a separate question: it depends on the oscillator, synchronization source, network path, and uncertainty estimate. For a chrony-managed Linux host, inspect System time, Root delay, and Root dispersion in chronyc tracking. For hardware-timestamped PTP, measure the deployed path and equipment; a protocol name alone does not guarantee a particular accuracy.
When You Need Better
Whether NTP is sufficient depends on the application’s error budget. A web page may tolerate a wall-clock offset that would be unacceptable for a telecom or power-grid timing requirement. Measure the system’s error bound against the requirement before choosing a more specialized source.
Before looking at PTP or GPS, check the application’s error budget. A causal-ordering problem may call for logical clocks; a UTC error-bound requirement may call for a better time source and measurement process.
When you do need hardware-level sync, the options are constrained by your environment:
| Requirement | Possible approach | What to validate |
|---|---|---|
| Keep general server clocks within an application-defined bound | NTP with chrony or another supported client | Root distance, source health, path asymmetry, and monitoring |
| Reduce error below what the current NTP path achieves | PTP with supported hardware timestamping | NICs, switches, PTP profile, path symmetry, grandmaster, and measured error |
| Trace time to a reference in a specialized environment | A qualified GNSS or laboratory reference | Antenna or signal path, holdover behavior, calibration, and required uncertainty |
The equipment choice depends on the target error bound and operating environment. GNSS reception may be unavailable indoors; holdover and calibration matter if the reference signal is lost.
IEEE 1588 PTP Deep Dive
IEEE 1588, also known as Precision Time Protocol (PTP), can improve synchronization when the network and devices support its timing features. Hardware timestamping can reduce host scheduling error, but it does not remove path asymmetry or guarantee one accuracy across all deployments.
How PTP Works
PTP synchronizes clocks by exchanging timestamps. Hardware timestamps are available on supported NICs and switches; software timestamping is also possible. NTP can use kernel or hardware timestamping too, depending on the implementation and hardware.
The synchronization process works as follows:
-
Best Master Clock Algorithm (BMCA): Eligible clocks compare their configured clock quality and priorities to select a grandmaster. That selection does not by itself measure the grandmaster’s error relative to UTC.
-
Sync messages: The master sends Sync messages with the send timestamp (hardware-generated). The slave records the receive timestamp (hardware-generated).
-
Follow-up messages: Because the send timestamp for Sync may not be known precisely at transmission time, the master sends a Follow-Up message with the corrected timestamp.
-
Delay Request and Response: The slave sends a Delay Request to the master, which responds with a Delay Response. This measures the path delay.
Master Slave
| |
|------------- Sync (t1) --------------------->|
| (t1 = master send timestamp, hardware) |
| |
|<----------- Delay Request (t4) --------------|
| (t4 = slave send timestamp) |
| |
|----- Follow-Up (t2) ------------------------>|
| (t2 = corrected master send timestamp) |
| |
|<----- Delay Response (t3) --------------------|
| (t3 = master receive timestamp) |
| |
Calculated values:
- Offset from master: ((t2 - t1) - (t4 - t3)) / 2
- Path delay: (t3 - t1) + (t4 - t2)) / 2
Hardware timestamping reduces uncertainty from software scheduling, but network asymmetry and device configuration still affect the result. Measure the deployed system against its timing requirement.
PTP vs NTP: The Key Differences
| Feature | PTP (IEEE 1588) | NTP |
|---|---|---|
| Timestamping | Can use hardware timestamps on supported NICs and switches | Can use software, kernel, or hardware timestamping depending on implementation |
| Accuracy | Depends on timestamp points, path symmetry, clocks, and configuration | Depends on clock quality, source, network delay and asymmetry, and client configuration |
| Network requirements | Often needs PTP-aware network components and a suitable profile | Runs over IP; path quality still affects the error bound |
| Monitoring | Check PTP state, grandmaster, path, and measured offset | Check source selection, offset, root delay, and root dispersion |
| Typical use | Applications with a measured requirement that the existing NTP setup cannot meet | General system time when the measured error bound is acceptable |
Hardware Requirements for PTP
PTP requires specialized network infrastructure:
PTP-Capable NICs: Network interface cards with hardware support for IEEE 1588. These NICs capture timestamps at the hardware level, bypassing OS latency.
PTP-Aware Switches: Standard switches introduce variable latency as packets queue. PTP-aware switches use boundary clocks or transparent clocks to compensate for switch delay. They measure and correct for the time packets spend traversing the switch.
GNSS grandmaster clocks: A GNSS-disciplined clock can provide a reference for a PTP domain. Its error depends on the receiver, antenna installation, signal conditions, calibration, and holdover behavior.
# Check if your NIC supports PTP
ethtool -T eth0 | grep -i timestamp
# Output might show:
# PTP Hardware Clock: 0
# Hardware Timestamping:-supported
# PTPv2 Event Port Transmit: supported
# PTPv2 Event Port Receive: supported
# Check PTP capabilities with ptp4l
ptp4l -i eth0 -l 6 -m
# -l 6 = log level debug
# -m = print messages to stdout
PTP Profiles
IEEE 1588 allows customization through profiles. Two are particularly important:
Default PTP Profile: General-purpose profile for enterprise networks. Allows up to 10ms path delay.
Power Profile (IEEE C37.238): Used in electrical substations for protection and control. Check the current profile and application requirements for the required time error.
Telecom Profile (G.8265.1): For telecom applications requiring frequency synchronization (not phase). Uses only Announce and Sync messages.
# Example: ptp4l configuration for default profile
# /etc/ptp4l.conf
[global]
domainNumber 0
priority1 128
priority2 128
clockType 2
servo_num_offset_threshold 1000
[eth0]
delayMechanism 1 # E2E (End to End)
Deployment Considerations
PTP requires careful network design:
-
Network latency asymmetry: PTP assumes symmetric path delay. If forward and reverse paths have different latency (common in wireless or routed networks), synchronization degrades. Use symmetric network paths or boundary clocks.
-
VLAN and QoS configuration: PTP messages must get priority queuing. Configure switches to give PTP traffic highest priority:
# Cisco switch example for PTP VLAN
vlan 100
name ptp-vlan
!
interface GigabitEthernet1/0/1
switchport mode trunk
switchport trunk allowed vlan 100
priority-mode dscp
!
# QoS configuration for PTP
mls qos map cos-dscp 46 34 26 18 0 0 0 0
# 46 = EF (Expedited Forwarding) for PTP
-
Boundary Clock vs Transparent Clock: Boundary clocks terminate PTP at each switch and act as masters for downstream devices. Transparent clocks pass PTP through while correcting for switch delay. They are different deployment choices; observed accuracy depends on the devices and network design.
-
Multi-domain PTP: Different PTP domains can run independently. Useful when you need separate time references for different subsystems.
When PTP Is Worth the Cost
PTP adds significant complexity and expense. Only deploy it when your requirements demand it:
| Requirement | Starting point | What determines the choice |
|---|---|---|
| General server timekeeping | NTP with chrony or the platform’s supported service | Whether the measured error bound meets the application budget |
| Telecom, power, or industrial timing | Evaluate the applicable timing profile and reference requirements | Required phase/time error, hardware, network design, and regulatory specification |
| Distributed event ordering | Logical or hybrid clocks may be more relevant than PTP | Whether the application needs causal order, bounded UTC time, or both |
Many distributed databases use logical or hybrid clock mechanisms for ordering. PTP addresses synchronization to a physical reference; it does not replace a protocol that records causality. Choose based on the guarantee the application needs.
Production Considerations
Monitoring Clock Synchronization
Monitoring clock synchronization requires checking both the current offset and the stability of the sync over time. chronyc sources -v shows each NTP server and its state. The ^* marker means that server is the current sync source. A ^+ means the server is acceptable but not current. A ^- means the server is rejected. If you see only ^* for one server with no backup, that is a single point of failure.
chronyc sourcestats reports statistics for measurements to each source. Do not use one universal standard-deviation threshold as a definition of healthy synchronization. Compare the measurements and chronyc tracking error estimate with the application’s clock-error budget.
# Check for clock synchronization issues
# Watch for large offset values
chronyc sources -v
# Confirm which source is selected and whether suitable alternatives are reachable.
chronyc sourcestats
# Compare source measurements over time against the service's error budget.
# Also check the current offset directly
chronyc tracking | grep "System time"
Alert when the estimated error bound exceeds the application’s budget or the system loses synchronization. A single offset value is not the full error estimate; include root delay and dispersion.
Alerts to Set
Set alert thresholds from the application’s clock-error budget and the time service’s uncertainty estimate. The rows below are signals to monitor, not universal thresholds.
| Signal | Example response | Why it matters |
|---|---|---|
| Estimated clock error exceeds the service budget | Alert at the budget defined by the application owner | A fixed offset threshold can be too strict for one service and too loose for another |
| Synchronization is lost or the selected source is unavailable | Alert according to the recovery objective | The free-running clock’s error can grow between updates |
| Leap policy changes or an announced leap is approaching | Check host and dependency behavior | Hosts configured to step and smear can diverge temporarily |
When an alert fires, check source reachability, the selected source, root distance, and recent changes to the network or time-service configuration. Escalate according to the service’s error budget and its authentication and ordering dependencies.
Common Issues
NTP daemon not running: If chronyd or another configured client stops, the system clock runs without new network measurements. Its free-running error depends on the measured oscillator and environment. For scale, a constant 20 ppm error would accumulate about 1.7 seconds per day; that is a calculation, not a VM-wide guarantee. Monitor synchronization state as well as whether the process is running.
Firewall blocking NTP: NTP commonly uses UDP port 123. If the configured source is unreachable, check firewall rules, routing, and the daemon’s source reports. With chrony, start with chronyc sources -v and its service logs; a timeout alone does not identify the firewall as the cause.
Virtual machines: Descheduling, host pauses, migration, and the hypervisor’s clock interface can affect a guest’s observed time. The details vary by platform; a virtual counter does not necessarily stop while the VM is descheduled. Some hypervisors expose paravirtualized clocks such as kvm-clock. Check the provider’s guidance and the guest’s synchronization measurements.
Cloud instances: Virtualization and host maintenance can affect timekeeping. Check the cloud provider’s current guidance for the VM image, then inspect the selected source and measured error. The examples below show provider-specific endpoints and host clocks; they do not promise a particular accuracy.
For virtualized and cloud environments, check the hypervisor or provider time source before adding an external NTP source. Mixing sources that use different leap policies can make clocks disagree.
Cloud Provider Time Sync Services
The recommended configuration can vary by provider and VM image. Follow the current provider guide and verify it with the time client installed on the VM.
AWS Time Sync Service
Amazon EC2 exposes the Amazon Time Sync Service at the link-local IPv4 address 169.254.169.123. AWS also documents an IPv6 endpoint for supported Nitro instances. Check AWS’s current EC2 guide for supported configurations.
# Example chrony source line for an EC2 instance
server 169.254.169.123 prefer iburst
# Verify source selection and synchronization estimate
chronyc sources -v
chronyc tracking
Use the configuration for your image, and avoid combining it with servers that use a different leap-second policy. AWS also documents PTP hardware clock support for eligible instances in precision time placement groups.
Google Cloud NTP
Google Cloud documents metadata.google.internal as the NTP source for Compute Engine VMs. Follow its current NTP guide, including its advice about removing unrelated sources where required.
# Example chrony source line; check the image's existing configuration first
server metadata.google.internal iburst
# Verify source selection and synchronization estimate
chronyc sources -v
chronyc tracking
Do not mix the Compute Engine source with an unrelated source unless the provider’s guidance and leap policy are compatible.
Microsoft Azure Time Sync
Azure Linux images can synchronize against the Azure host. Current images may expose the host as a PTP hardware clock, often through /dev/ptp_hyperv; image configuration varies. See Microsoft’s Linux VM time-sync guide before changing a VM’s sources.
# Inspect PTP devices and their reported names
ls /sys/class/ptp
cat /sys/class/ptp/ptp*/clock_name
# Check the chrony source and estimate, if chrony is configured
chronyc sources -v
chronyc tracking
Cloud source examples
| Provider | Example source | Current provider guide |
|---|---|---|
| AWS | 169.254.169.123 (IPv4) |
Amazon Time Sync Service |
| Google Cloud | metadata.google.internal |
Compute Engine NTP |
| Azure | Azure host time; some images expose /dev/ptp_hyperv |
Linux VM time sync |
| Oracle Cloud | 169.254.169.254 |
OCI NTP service |
Virtualization Clock Issues
Virtual machines face unique clock challenges that physical machines do not:
CPU scheduling: A VM can be paused while the hypervisor schedules other work. The guest’s time behavior during and after that pause depends on the virtual clock and hypervisor implementation.
Live Migration: When VMs migrate between hosts, they may pause briefly. This causes clock discontinuities that NTP must compensate for.
Resource contention: Heavy load can delay time-service processing and timestamp capture. Check measured offset and source statistics instead of assuming load creates a fixed drift rate.
Hypervisor Solutions:
# VMware: Enable time synchronization with host
# On VMware, ensure these settings are configured:
# VM Tools > Options > Time synchronization > Synchronize time with host
# Verify VMware tools status
vmware-toolbox-cmd timesync status
# Hyper-V: Enable time synchronization
# On Hyper-V host:
# Set-VMProcessor -VMName "YourVM" -CompatibilityForTimeMigration $true
# Linux guest with Hyper-V integration services:
# The hv_utils driver provides time sync
lsmod | grep hv_utils
Best Practices for VMs:
- Use the cloud provider’s time sync service (169.254.169.123 for AWS)
- Enable hypervisor-level time sync where available
- Avoid using bare metal time sources inside VMs
- Monitor clock drift and set alerts for large offsets
- Consider using a monotonic clock for short-interval timing
Production Monitoring Implementation
Monitoring clock synchronization is critical for systems that depend on event ordering:
Prometheus Metrics for Clock Sync
# prometheus.yml - scrape configuration for node exporter
scrape_configs:
- job_name: "node"
static_configs:
- targets: ["localhost:9100"]
# Key node_timex metrics to monitor:
# node_timex_offset_seconds - current clock offset from NTP
# node_timex_maxerror_seconds - maximum estimated error
# node_timex_loop_time_constant - phase-locked loop time constant
# node_timex_sync_status - whether sync is active (1 = synced)
Alerting Rules
# alerts/clock-sync.yml
groups:
- name: clock_alerts
interval: 30s
rules:
- alert: ClockOffsetHigh
expr: abs(node_timex_offset_seconds) > 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "Clock offset exceeds 100ms"
description: "Clock on {{ $labels.instance }} is {{ $value }} seconds offset"
- alert: ClockOffsetCritical
expr: abs(node_timex_offset_seconds) > 0.5
for: 1m
labels:
severity: critical
annotations:
summary: "Clock offset exceeds 500ms"
description: "Clock on {{ $labels.instance }} is critically offset"
- alert: ClockSyncLost
expr: node_timex_sync_status == 0
for: 1m
labels:
severity: warning
annotations:
summary: "NTP synchronization lost"
description: "Clock on {{ $labels.instance }} is not synchronized"
Clock Selection Decision Matrix
Use this matrix to select the appropriate time source for your use case:
| Use case | Clock or protocol | Decide from |
|---|---|---|
| User-facing timestamps | CLOCK_REALTIME or system wall clock |
The date and time users need to see, including timezone handling |
| Elapsed-time measurement | CLOCK_MONOTONIC or CLOCK_BOOTTIME |
Whether suspended time should count |
| Distributed event ordering | Lamport, vector, or hybrid logical clocks | Whether the system must represent causal relationships |
| UTC synchronization | NTP/chrony or PTP | Whether measured clock error meets the application’s requirement |
When to Use / When Not to Use Physical Clocks
| Scenario | Recommendation |
|---|---|
| User-facing timestamps | Use wall-clock with timezone handling |
| Application logging | Use wall-clock, useful for human review |
| Debugging and tracing | Use wall-clock, correlates with real events |
| Event ordering across machines | Do not use wall-clock |
| Conflict resolution | Do not use wall-clock |
| Distributed consensus | Do not use wall-clock alone |
| High-frequency trading | Select a time service from the measured error requirement and applicable rules |
When TO Use Physical Clocks
Wall clocks are useful for human-readable timestamps and scheduling. Check the required time error for the service rather than assuming a particular clock is accurate enough.
Displaying times to users: User-facing timestamps do not need to be precise. A timestamp that is off by 50ms looks no different to a person than one that is off by 5ms. The wall-clock time you display should match what users expect to see on their own devices. Timezone handling matters more than synchronization accuracy here. Store timestamps in UTC, convert to the user’s local timezone on display.
Logging events for human review: Human-readable logs use wall-clock time because you want to correlate log entries with real-world events. When debugging, you often cross-reference logs with system events, emails, or user reports. A log entry at “2026-03-24 10:15:30 UTC” is meaningful even if it is 20ms off from true UTC. The relative ordering of log entries within a single machine is what matters for debugging, and that is preserved even with clock drift.
Auditing: Wall-clock timestamps make logs easier to compare with external records. Keep the time source and its uncertainty visible where the audit needs reliable ordering; retention and integrity controls are separate requirements.
Non-critical scheduling: Cron jobs, background workers, and periodic tasks that tolerate a few seconds of imprecision can use wall-clock scheduling. A nightly batch job that runs at 2am local time does not need to know if it started at 2:00:00.000 or 2:00:03. The exception is scheduling that must coordinate across machines, which is where physical clocks fail.
When NOT to Use Physical Clocks
Physical clocks fail whenever the answer to “which happened first” must be correct across machines. These are the cases where clock skew breaks your system.
Determining causal ordering of distributed events: If Server A sends a message and Server B receives it later, you need to know that A sent before B received. Physical clocks cannot prove this because the sender and receiver clocks may disagree. A timestamp from A showing “10:00:00.100” and a timestamp from B showing “10:00:00.050” does not mean B received the message before A sent it. Lamport timestamps solve this by using logical counters to capture causality.
Conflict resolution in distributed databases: Last-write-wins conflict resolution using wall-clock timestamps is broken by clock skew. If Data Center A has a clock 200ms ahead of Data Center B, writes from A always appear newer to B, even when B’s write happened first in real time. This causes data loss during network partitions. Use vector clocks or hybrid logical clocks instead. Spanner uses hardware atomic clocks plus GPS to get a bounded-error physical clock, but that requires specialized hardware most teams do not have.
Implementing distributed protocols (consensus, coordination): Raft does not use synchronized wall clocks to order log entries. Its election timers affect liveness, though: a stalled or erratic timer can trigger unnecessary elections or slow progress. Keep timestamps separate from the protocol’s correctness rules.
Any situation where “which happened first” matters: This is the general case of all the above. Whenever your application logic depends on event ordering rather than absolute time, physical clocks are the wrong tool. The question is not “what time was it” but “did A happen before B”. Clock skew makes that question unanswerable with physical clocks alone.
Production Failure Scenarios
Understanding how clock failures manifest in production helps with debugging and prevention.
The 2015 Leap Second Incident
On June 30, 2015, many Linux servers worldwide experienced kernel panics or runaway CPU usage when a leap second was inserted. The issue stemmed from a bug in the Linux kernel’s clocksource_watchdog function, which could cause an infinite loop when the TSC clock source was used.
Cloudflare’s DNS service was among those affected, experiencing intermittent failures. The fix involved properly handling the repeated second in the kernel’s timekeeping code.
AWS EC2 Clock Drift Incident
In 2014, Amazon EC2 instances experienced significant clock drift when the hypervisor’s clock source became unreliable. Instances running applications sensitive to timing showed:
- SSL/TLS handshake failures due to certificate time validation
- Kerberos authentication errors as tickets were considered expired
- Cassandra batch statements timing out due to incorrect timestamp headers
The resolution involved AWS improving their hypervisor-level time synchronization.
High-Frequency Trading Clock Skew
A quantitative trading firm discovered their arbitrage system was losing money due to 2ms clock skew between their primary and backup servers. Despite both running NTP synchronization, network latency asymmetry caused one server’s clock to consistently run 2ms fast.
The fix required moving to GPS-disciplined oscillators with hardware timestamps, eliminating network-based synchronization entirely.
Distributed Database Timestamp Conflict
A social media company experienced data loss in their distributed database during a network partition. The “last write wins” conflict resolution was using wall-clock timestamps, and clock skew between data centers meant updates from one datacenter consistently overwrote the other.
The incident led them to adopt hybrid logical clocks, which provide causality guarantees without requiring tightly synchronized physical clocks.
Kubernetes Insecure Token Validation
In early Kubernetes versions, service account tokens were validated using the node’s system clock. If the node’s clock was significantly skewed, tokens that were legitimately expired could be accepted as valid, or fresh tokens rejected. This was especially problematic in development environments with unreliable NTP sync.
Trade-off Analysis
| Factor | Physical Clocks + NTP | PTP (IEEE 1588) | Atomic/GPS Clocks |
|---|---|---|---|
| Accuracy | Inspect the configured error estimate | Measure on the deployed PTP path | Depends on the reference, receiver, and calibration |
| Cost | Free (software only) | $1,000-10,000+ per location | $10,000-100,000+ |
| Hardware required | None | PTP-capable NICs + switches | Atomic clock or GPS receiver |
| Network requirements | Any IP network | Dedicated VLAN or QoS | Antenna/signal path |
| Convergence time | Minutes | Seconds to minutes | Instant (self-contained) |
| Maintenance | Low | High | Very high |
| Typical use cases | Web servers, logging, general | HFT, telecom, industrial | Telecom backbone, research |
When NTP Is Sufficient
Choose NTP when:
- Millisecond accuracy meets your requirements
- You need broad compatibility and simplicity
- Your infrastructure is in cloud environments with built-in time sync
- You cannot afford specialized hardware or network configuration
When to Consider PTP
Choose PTP when:
- Sub-millisecond accuracy is required
- You operate in financial trading, telecom, or industrial control
- You have dedicated network infrastructure for time traffic
- Regulatory requirements mandate specific accuracy levels
When You Need Hardware Clocks
Choose dedicated hardware clocks when:
- Nanosecond precision is required
- Network path asymmetry cannot be controlled
- Regulatory compliance requires traceable time to UTC
- You operate in environments without reliable network connectivity
Quick Recap Checklist
Before relying on physical clocks in production, make sure you understand:
- The active Linux clocksource is hardware- and kernel-dependent
-
CLOCK_REALTIMEis for calendar timestamps;CLOCK_MONOTONICandCLOCK_BOOTTIMEmeasure elapsed time with different suspend behavior - NTP/chrony estimate offset and uncertainty; synchronization does not make clocks identical
- Clock skew makes wall-clock timestamps unreliable for event ordering across machines
- System clocks can jump forward or backward (non-monotonic)
- Leap handling may step, slew, or smear; hosts should use a documented, compatible policy
- Virtual machines have additional clock challenges (time slicing, live migration)
- Use physical clocks for human-readable logs, not for distributed event ordering
- For event ordering, use Lamport timestamps or vector clocks instead
- PTP can reduce synchronization error with supported hardware and network design, but must be measured in the deployed environment
- Cloud providers offer time sync services optimized for their infrastructure
Interview Questions
Expected answer points:
- Drift is the rate at which a single clock runs faster or slower than ideal time (e.g., ppm drift rate)
- Skew is the difference in time reading between two clocks at a specific moment
- Even clocks with identical drift rates can have skew because they started from different times
- Drift accumulates over time; skew is the observable difference at any point
Expected answer points:
- NTP uses 4 timestamps: T1 (client send), T2 (server receive), T3 (server send), T4 (client receive)
- Round-trip delay = (T4 - T1) - (T3 - T2)
- Clock offset = ((T2 - T1) + (T3 - T4)) / 2
- NTP takes multiple samples and uses filtering algorithms to reject bad measurements
Expected answer points:
- The oscillator's frequency error, which varies by device and environment; use measured frequency rather than a universal ppm range
- Network delay and path asymmetry between the host and its reference
- Clocksource, hypervisor, and timestamping behavior
- Chrony's offset, root delay, and root dispersion provide an estimate, not an exact UTC error
Expected answer points:
- Clock skew means different machines may have different views of "now"
- A timestamp from one machine may appear newer on another due to clock differences, not actual causality
- Last-write-wins conflict resolution fails when clocks are skewed
- The PACELC theorem explains this: in case of network partition, you choose between consistency and availability/performance
Expected answer points:
- Precision is how finely you can measure time (granularity of the measurement)
- Accuracy is how close that measurement is to the true time
- A clock may report nanosecond resolution while its wall time remains uncertain by much more
- `clock_getres()` reports resolution; it does not report accuracy relative to UTC
- For chrony, inspect the offset, root delay, and root dispersion to estimate the error bound under the client's assumptions
Expected answer points:
- PTP can use NIC and switch hardware timestamps when supported and configured
- Hardware timestamps reduce some host scheduling error but do not eliminate network-path asymmetry
- PTP uses a master-slave architecture with Best Master Clock Algorithm (BMCA)
- PTP may reach lower error than a general NTP setup, but accuracy depends on hardware, profile, path, and measurement
Expected answer points:
- A leap second may be inserted or deleted when announced; it is not scheduled on a fixed annual cycle
- Time services and providers may step, slew, or smear the adjustment
- Hosts with different policies can disagree around the event, so document and monitor the chosen policy
- Investigate a specific incident before generalizing it to all systems
Expected answer points:
- Stratum indicates a server's distance from its reference in the NTP hierarchy; external reference clocks are not stratum-0 servers
- A lower stratum does not guarantee a more accurate wall clock
- Network delay, dispersion, oscillator behavior, and source quality affect the error estimate
- Use `chronyc tracking` and `chronyc sources -v` to inspect the path and measurements
Expected answer points:
- Descheduling, host pauses, and migration can affect a guest's observed time; behavior depends on the hypervisor's clock interface
- Virtual clock and paravirtual clock implementations differ across platforms
- Check the configured time source and its measurements inside the guest
- Use a monotonic clock for elapsed-time measurement within one machine
Expected answer points:
- TSC is an x86 CPU counter; its suitability depends on processor, firmware, kernel, and hypervisor support
- HPET and ACPI PM timers are platform timers, but their presence does not mean the kernel selects them
- Check `/sys/devices/system/clocksource/clocksource0/current_clocksource` to see the active kernel source
- A hardware source's resolution does not state the host's UTC accuracy
Expected answer points:
- When a measured NTP error bound does not meet the application's requirement and PTP's deployment cost is justified
- Telecom, power, or industrial timing systems with a defined profile and phase or time-error requirement
- When NICs, switches, reference clocks, and path configuration support the required measurement
Expected answer points:
- `chronyc tracking` reports the selected reference, offset, frequency, root delay, root dispersion, and leap status
- `chronyc sources -v` shows source selection and reachability
- `chronyc sourcestats` summarizes measurements to each source
- Compare the estimated error with the application's own accuracy requirement
Expected answer points:
- Authentication failures: Kerberos tickets expire based on clock skew; certificates may appear invalid
- Cache coherency issues: distributed caches may serve stale data when timestamps disagree
- Audit log misalignment: logs from different machines cannot be accurately ordered
- Scheduled job conflicts: cron jobs firing at wrong times across cluster nodes
- Payment processing failures: retry mechanisms may trigger incorrectly based on timestamps
Expected answer points:
- NTP clients compare configured sources and can reject inconsistent measurements; selection details vary by implementation
- Several independent sources can help reveal a faulty source, but source count alone does not prove the time is correct
- Network Time Security (NTS), specified in RFC 8915, authenticates NTP exchanges when supported and configured
- Restrict who can change time-service configuration and monitor source selection and clock adjustments
Expected answer points:
- Slewing changes the clock rate gradually; stepping changes its value immediately
- A step can make `CLOCK_REALTIME` jump, while a slew changes how quickly it advances
- The sync client's configuration determines when a step is allowed; chrony documents the `makestep` directive
- Use a monotonic clock for elapsed-time measurement that must not follow wall-clock adjustments
Expected answer points:
- Network asymmetry: forward and reverse paths have different latency
- Server selection: different servers within the pool may have different offsets
- Load variation: CPU contention affects timestamp capture timing
- Clocksource and virtualization differences can affect rate and timestamp behavior; inspect the selected source and measurements
- Virtualization effects: VMs may be subject to hypervisor clock issues
Expected answer points:
- PACELC describes trade-offs among consistency, latency, and availability during normal operation and partitions
- Wall-clock timestamps do not prove that one distributed event caused another
- With skewed clocks, last-write-wins can select a value that was not the later event in causal order
- Logical, vector, or hybrid logical clocks can record ordering information when the application propagates it
Expected answer points:
- Oscillator frequency can vary with temperature; its direction and size depend on the component
- Use measurements from the deployed device instead of assuming a fixed ppm-per-degree relationship
- Virtualization, reference quality, and network path also affect system clock error
Expected answer points:
- NTP amplification attacks: attackers spoof requests to NTP servers, reflected traffic overwhelms victim
- Clock manipulation: if attacker controls NTP server, they can manipulate your clock for attacks
- Certificate validation failures: manipulated clocks can cause TLS certificates to appear invalid or expired
- Replay attacks: old valid timestamps may be replayed if clock is manipulated backward
- Mitigation: use Network Time Security (NTS) where supported, restrict time-source configuration, and monitor offset changes
Expected answer points:
- Clock offset: `node_timex_offset_seconds` — deviation from NTP source
- Maximum error estimate: `node_timex_maxerror_seconds` — accumulated uncertainty
- Sync status: `node_timex_sync_status` — 1 means synced, 0 means lost
- Loop time constant: `node_timex_loop_time_constant` — PLL configuration
- Stratum level: indicates NTP server hierarchy distance from primary source
Further Reading
- NTPv4 specification (RFC 5905)
- Network Time Security (RFC 8915)
chronycmanual- Linux
clock_gettime(2)manual - Linux kernel timekeeping documentation
- IEEE 1588 - Precision Time Protocol
- AWS EC2 time synchronization
- Google Cloud Compute Engine NTP
- Azure Linux VM time synchronization
- Oracle Cloud Infrastructure NTP service
Conclusion
Physical clocks are useful for calendar timestamps, logs, and scheduling, provided their measured error fits the application. NTP and chrony reduce clock offset but leave some uncertainty.
The problems arise when you need to order events across machines. Clock skew makes “what happened first” non-trivial to answer with physical clocks alone. This is why distributed systems turn to logical clocks and vector clocks, which the next posts in this series cover.
Key takeaways:
- Linux exposes different clocks for wall time and elapsed-time measurement
- NTP and chrony reduce offset; their measurements still have uncertainty
- Clock skew makes wall-clock timestamps unreliable for event ordering
- Use physical clocks for human-readable timestamps and logging
- Use logical clocks for distributed event ordering
The Logical Clocks post covers Lamport timestamps, which provide a way to order events without synchronized physical clocks.
Category
Related Posts
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.
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.
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.