NTP: how the internet keeps time
Updated
Every computer keeps its own time with a small crystal oscillator, and no two crystals tick at exactly the same rate. Left alone, a clock drifts by seconds a week. The Network Time Protocol, NTP, is how devices on the internet keep their clocks right by asking other computers what time it is.
Where the time comes from
The reference is a set of atomic clocks in laboratories around the world, whose readings are combined into Coordinated Universal Time, UTC. GPS satellites carry atomic clocks too, and anyone with a receiver can read the time from them. These are called stratum 0 and are never reached over the internet directly.
Strata: layers of servers
- Stratum 1 servers are wired directly to a stratum 0 clock, such as a GPS receiver
- Stratum 2 servers copy the time from stratum 1 servers, stratum 3 from stratum 2, and so on
- A higher number means more hops from the clock, not a worse server: a stratum 2 server is usually just as good for everyday use
- Many providers run public time servers, and pool.ntp.org is a volunteer-run group of thousands of them that spreads the load
How a device asks
NTP sends a small message over UDP, port 123, and the server replies. Four timestamps are involved: when the request left, when the server received it, when the server replied, and when the reply arrived. From them the device works out how long the round trip took and how far its clock is from the server's.
offset = ((server received - request sent) + (server replied - reply arrived)) / 2 delay = (reply arrived - request sent) - (server replied - server received)
The calculation assumes the trip out took as long as the trip back, which is why a short, steady trip gives a better answer. A device asks several servers and ignores any that disagree with the rest.
Correcting the clock gently
A small error is fixed by running the clock slightly faster or slower until it catches up, so time never jumps backwards. Only a large error is fixed by setting the clock outright. That is why a healthy device is usually within a few milliseconds of true time.
Why it matters
- A certificate is valid between two dates, so a clock that is far off can make a secure website look expired or not yet valid
- Two-factor codes are computed from the time, and are rejected when the clocks differ by more than about thirty seconds
- DNSSEC signatures, logs, backups and distributed databases all depend on clocks that agree
Leap seconds and newer protocols
The Earth's rotation is slightly uneven, so UTC has occasionally had a leap second added to keep it in step. Operators handle it in different ways, which is one reason the time of a single second can differ between systems. Newer work includes Network Time Security, which adds authentication to NTP, and the Precision Time Protocol, used inside data centers where microseconds matter.
Check how far off your clock is