[LF] Clock synchronisation
This is a series of notes on topics related to Local-First software.
Clock Synchronization
-
Quartz Clocks
- Used in computers to track UTC
- Battery-powered (runs even when off)
- Clock drift: Gradual increase in error due to imperfect timing
- Clock skew: Difference between two clocks at a given time
-
Solutions for Synchronization
- Periodically sync with more accurate time source (atomic clock, GPS)
- Protocols:
- NTP (Network Time Protocol) – Common, reduces skew to milliseconds
- PTP (Precision Time Protocol) – Higher accuracy than NTP
Network Time Protocol (NTP)
-
Hierarchy (Stratum Levels)
- Stratum 0: Atomic clock/GPS (most accurate)
- Stratum 1: Directly synced with Stratum 0
- Stratum 2: Synced with Stratum 1, etc.
-
Process
- Contacts multiple servers, discards outliers, averages rest
- Uses multiple requests to reduce network latency effects
- Limitation: Skew can worsen under poor network conditions
Estimating Clock Skew in NTP
-
Timestamps in NTP Exchange
- t₁ (Client sends request)
- t₂ (Server receives request)
- t₃ (Server sends response)
- t₄ (Client receives response)
-
Calculations
- Round-trip delay (δ):
(t₄ − t₁) − (t₃ − t₂)
- Estimated server time:
t₃ + (δ / 2)
- Estimated skew (θ):
(t₂ − t₁ + t₃ − t₄) / 2
- Assumption: Network latency is symmetric (may not hold under heavy load)
- Round-trip delay (δ):
Correcting Clock Skew
- Small Skew (|θ| < 125 ms)
- Slewing: Gradual clock speed adjustment (≤500 ppm)
- Moderate Skew (125 ms ≤ |θ| < 1000 s)
- Stepping: Immediate clock jump
- Large Skew (|θ| ≥ 1000 s)
- Panic: No adjustment (requires manual fix)
Clock Types Comparison
Time-of-Day Clock
- Tracks time since fixed epoch (e.g., Unix epoch)
- Affected by NTP stepping and leap seconds
- Used for cross-node timestamp comparison
- Examples:
- Java:
System.currentTimeMillis()
- Linux:
clock_gettime(CLOCK_REALTIME)
- Java:
Monotonic Clock
- Tracks time since arbitrary point (e.g., system boot)
- Always moves forward at near-constant rate
- Essential for single-node elapsed time measurement
- Examples:
- Java:
System.nanoTime()
- Linux:
clock_gettime(CLOCK_MONOTONIC)
- Java:
Key Takeaways
- NTP reduces clock skew but depends on network conditions
- Monotonic clocks are essential for reliable timing measurements
- Time-of-day clocks can jump (unreliable for elapsed time)
- Systems using clock sync must actively monitor for skew