Canonical: https://nitride.xyz/blog/clock-sync-for-latency

# Your clock is lying: NTP, PTP and timing shreds

Clock offset only matters when your timestamps come from two machines, so put the feeds on one host where you can, and know your error bound where you can't.

Clock offset spoils a latency number only when the two timestamps you compare come from different machines. Stamp competing feeds on one host and the offset cancels. When you must compare across hosts, discipline both clocks, log chrony's or ptp4l's own error figures beside every result, and call any difference smaller than that error noise.

## The offset only bites across machines
Every arrival time you log is a reading of one machine's `CLOCK_REALTIME`. Suppose that clock runs some hundreds of microseconds ahead of true time. Every stamp it produces carries the same error, so when you subtract two stamps taken on that machine, the error falls out. What is left is drift during the interval, and a clock that is wrong in rate by, say, 50 parts per million gains 50 nanoseconds over a millisecond. For comparing two shred feeds that land a fraction of a millisecond apart, that is nothing.

The trouble starts when the two stamps come from two clocks. A few common cases:

- your receiver's stamp against the `firstShredReceived` event your RPC node stamps on its own clock;
- your box in one data center against a colleague's box in another;
- a sender's timestamp against your receive time, to get a one-way delay.

In each of these, the offset between the two clocks adds straight into every delta, with no way to separate it from the network. Our strong preference is to avoid the problem rather than fight it: bring both feeds to one server, stamp them in the kernel, and subtract. That holds whether the two feeds come from two sellers or from [our Ultra and Standard plans](https://nitride.xyz/compare/ultra-vs-standard-shreds). The method is written up in [measuring arrival time on your server](https://nitride.xyz/docs/receiver/arrival-time), [how to read a shred provider's latency claim](https://nitride.xyz/blog/reading-latency-claims) covers judging other people's numbers, and this post covers what to do when one host is not an option.

## Read chronyc tracking before you read your results
If your server runs chrony, as many Linux distributions do by default, `chronyc tracking` is the one command worth running before and after every capture. The fields that matter for timing work:

- **System time**: the current offset between chrony's idea of true time and the system clock, which chrony is still slewing away.
- **Last offset** and **RMS offset**: the offset estimated at the last update and a long-term average of it.
- **Frequency** and **Skew**: how fast the clock would drift uncorrected, in parts per million, and the error bound on that estimate.
- **Root delay** and **Root dispersion**: the total path delay and accumulated dispersion back to the stratum 1 source.
- **Leap status**: Normal, Insert second, Delete second or Not synchronised.

The number people quote is RMS offset, and it flatters. It describes how well chrony tracks its own estimate, not how close that estimate is to UTC. The chrony manual gives the honest bound: the clock error is at most the absolute system time offset plus root dispersion plus half the root delay. Over a long internet path the half root delay term can exceed the effect you are trying to measure, and then no cross-machine comparison is meaningful.

So compute the bound for both hosts and write it next to the result. `chronyc -c tracking` prints the same report as CSV with values in seconds, which is easy to append to a capture log. If either host shows Not synchronised, throw the run away.

## NTP or PTP: it comes down to where the stamps are taken
NTP estimates offset from four timestamps: client send (T1), server receive (T2), server send (T3) and client receive (T4). RFC 5905 gives the offset as half of (T2 minus T1) plus (T3 minus T4), and the round trip delay as (T4 minus T1) minus (T3 minus T2). The offset formula assumes both directions take equal time. Any asymmetry lands in the offset unseen, and in the worst case it can be as large as half the round trip. Every software stamp also includes interrupt and scheduling noise on both ends.

Two upgrades shrink that error:

1. **Hardware timestamps for NTP.** The chrony `hwtimestamp` directive has the network card stamp NTP packets as they cross the wire. It needs Linux 3.19 or newer and a card that `ethtool -T` shows can do it, and the gain is largest when the server side also uses card stamps, with interleaved mode (`xleave`) enabled. The chrony FAQ says that with hardware stamps, good switches and short polling, sub-microsecond accuracy might be possible on a local network.
2. **PTP.** IEEE 1588 defines a protocol for sub-microsecond clock synchronization over packet networks. On Linux, `ptp4l` runs it and disciplines the card's PTP hardware clock, using hardware stamps by default. `phc2sys` then copies that clock into the system clock; `phc2sys -a -r` follows ptp4l and sets the system time. PTP counts in TAI, not UTC, so let `phc2sys -w` take the UTC offset from ptp4l rather than typing it, or every reading is off by whole seconds.

PTP pays off only when the network gives you a PTP source, meaning a grandmaster and switches that handle the protocol. Running ptp4l against nothing gains nothing. If your host has a hardware clock disciplined this way, you can also take the shred stamps themselves on the card, which [the arrival time docs](https://nitride.xyz/docs/receiver/arrival-time#hardware-timestamps) show how to request. Keep the card clock and the system clock tied together, or the two kinds of stamp will disagree with each other.

## Cloud time services
The large clouds run a time service you can reach from inside an instance, and that should be your only source there. Two examples, read on their own documentation:

- **AWS** offers the Amazon Time Sync Service locally and as `time.aws.com`. Both smear leap seconds. On supported instances it also exposes a PTP hardware clock, and hardware packet timestamping on the network adapter, which AWS pitches for measuring one-way latency. The hardware clock does not smear, and AWS advises against configuring smeared and non-smeared sources together.
- **Google Compute Engine** points instances at `metadata.google.internal`, which smears leap seconds over 24 hours. Google warns that mixing it with external servers that step the clock can cause unpredictable changes in system time.

The lesson carries to every provider: adding a public pool "for redundancy" next to the provider's service is how you end up with two sources that disagree at the worst moment. On a cloud VPS, timing has other problems too, which [can a cloud VPS keep up](https://nitride.xyz/blog/can-a-vps-keep-up) goes through.

## Three traps: steps, smears and virtual clocks
**Steps.** chrony normally corrects by slewing. The `makestep` directive allows a step, and the manual's example, `makestep 0.1 3`, permits it only during the first three updates. A step during a capture puts a discontinuity into every `CLOCK_REALTIME` stamp after it. Slewing has a cost of its own: the default maximum slew rate is 83333 ppm, one twelfth, so right after boot or a large correction the clock can run measurably fast or slow, and even same-host deltas stretch. Start captures only once System time is small.

**Leap smears.** Google's smear is linear over 24 hours from noon to noon UTC, a rate change of about 11.6 ppm, and AWS uses the same. During a smear, a smeared host and a host that follows UTC strictly disagree by up to half a second around the leap itself. The chrony manual warns that clients of a smearing server should not poll anything else, because they may reject it as a falseticker.

**Virtual clocks.** The chrony FAQ notes that some virtual machines drift far more than real hardware and can resume from suspension with the wrong time. On KVM guests, the kernel's `ptp_kvm` driver exposes the host clock as a PTP clock that chrony can read as `refclock PHC`. The kernel's newer VMCLOCK driver goes further: its description says it keeps time reliably across live migration, which the KVM clock does not. A live migration in the middle of a capture is a step you never asked for.

## A two-host offset check you can run today
Before trusting a cross-machine comparison, measure the two hosts against each other directly. This script applies the RFC 5905 formula to UDP probes between them and keeps the sample with the shortest round trip, which carries the least queueing:

```python file="offprobe.py"
# offprobe.py: estimate the clock offset between two of your own hosts, NTP style
# on host B:  python3 offprobe.py serve 9125
# on host A:  python3 offprobe.py probe 10.0.0.2 9125 200
import socket
import struct
import sys
import time

now = time.time_ns  # CLOCK_REALTIME, the clock your arrival stamps use


def serve(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("0.0.0.0", port))
    while True:
        data, peer = s.recvfrom(64)
        t2 = now()
        if len(data) != 8:
            continue
        s.sendto(data + struct.pack("<qq", t2, now()), peer)


def probe(host, port, count):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(0.5)
    samples = []
    for _ in range(count):
        t1 = now()
        s.sendto(struct.pack("<q", t1), (host, port))
        try:
            data = s.recv(64)
        except socket.timeout:
            continue
        t4 = now()
        echo, t2, t3 = struct.unpack("<qqq", data)
        if echo != t1:
            continue  # a late reply to an earlier probe
        offset = ((t2 - t1) + (t3 - t4)) / 2  # B's clock minus A's clock (RFC 5905)
        delay = (t4 - t1) - (t3 - t2)
        samples.append((delay, offset))
        time.sleep(0.01)
    if not samples:
        sys.exit("no replies")
    delay, offset = min(samples)  # the shortest round trip carries the least queueing
    print(f"replies {len(samples)}/{count}")
    print(f"offset B minus A: {offset / 1000:.1f} us")
    print(f"round trip: {delay / 1000:.1f} us, so asymmetry can hide up to {delay / 2000:.1f} us")


if sys.argv[1] == "serve":
    serve(int(sys.argv[2]))
else:
    probe(sys.argv[2], int(sys.argv[3]), int(sys.argv[4]))
```

Run against itself over loopback, with both ends on one clock, it printed:

```text
replies 200/200
offset B minus A: 4.5 us
round trip: 39.3 us, so asymmetry can hide up to 19.7 us
```

The true offset there is zero, so those 4.5 microseconds are the noise floor of stamping in user space on that machine. Between two real hosts, read the last line first. If half the round trip is larger than the difference you hoped to detect, the comparison cannot answer your question, however good the offset looks.

What we write down with every capture, whether it is for a feed test or for [a backtest built on shreds you recorded](https://nitride.xyz/blog/backtesting-with-captured-shreds): the hosts involved, the chrony or ptp4l state at start and end, the error bound for each clock, and whether a step, smear or migration could have happened during the run. [Where Solana latency comes from](https://nitride.xyz/learn/solana-latency) lists the delays you cannot remove, and [the guide to testing a shred feed before you buy](https://nitride.xyz/guides/test-a-shred-feed-before-you-buy) shows where these numbers fit in a trial.

Each plan has a free 2-hour trial, once per person. Email support@nitride.xyz with the IPv4 address and UDP port you want to test. We verify you receive on that address, then your 2 hours start.
