Simulating NTP with a Tiny Internet
In my previous post, I explained NTP's four timestamps and how they give us estimates of delay and clock offset. I wanted to see how those calculations behave when the network delay changes.
I built a small simulation with one server that has the correct time, one client whose clock starts out wrong, and a toy network that adds random delay in both directions. Running it a few times shows why correcting a large initial clock error is easier than getting the last few milliseconds right.
NTP assumes that the delay from client to server is roughly the same as the delay on the return trip. On a real network, queueing, routing, and transient congestion make the two directions differ. NTP works well, but that difference affects its estimate. The simulation makes this source of error visible.
A 20-Second Refresher
When a client talks to an NTP server, four timestamps matter:
- T1: the client sends the request
- T2: the server receives it
- T3: the server sends the reply
- T4: the client receives the reply
From those four timestamps, the client computes:
delay = (T4 - T1) - (T3 - T2)
offset = ((T2 - T1) + (T3 - T4)) / 2
The first number tells us how much time was spent on the wire. The second tells us how far off the client's clock seems to be.
If the delays to the server and back were equal, the offset would be exact. The simulation lets us see what happens when they differ.
The Tiny Internet
The simulation uses:
- A time server that knows the correct time
- A client device whose clock starts out wrong
- A tiny internet that adds separate random delays to the outbound and inbound trip
That is enough to reproduce the basic behaviour of NTP: one large correction followed by smaller, noisier refinements.
The Code
Save this as tiny_ntp.py and run it with python3 tiny_ntp.py.
import random
import time
class TimeServer:
def __init__(self, name, real_start):
self.name = name
self.real_start = real_start
self.epoch = 1_700_000_000.0
def now(self):
return self.epoch + (time.time() - self.real_start)
def handle_request(self):
t2 = self.now()
time.sleep(random.uniform(0.001, 0.005))
t3 = self.now()
return t2, t3
class ClientDevice:
def __init__(self, name, real_start, clock_offset):
self.name = name
self.real_start = real_start
self.epoch = 1_700_000_000.0
self.clock_offset = clock_offset
self.correction = 0.0
def now(self):
return (
self.epoch
+ (time.time() - self.real_start)
+ self.clock_offset
+ self.correction
)
def sync(self, internet, hostname):
t1 = self.now()
t2, t3, outbound, inbound = internet.connect(hostname)
t4 = self.now()
delay = (t4 - t1) - (t3 - t2)
offset = ((t2 - t1) + (t3 - t4)) / 2
asymmetry = inbound - outbound
# Real NTP usually disciplines the clock gradually.
# This toy steps the clock immediately so the effect is easy to see.
self.correction += offset
return {
"t1": t1,
"t2": t2,
"t3": t3,
"t4": t4,
"delay": delay,
"offset": offset,
"outbound": outbound,
"inbound": inbound,
"asymmetry": asymmetry,
}
class TinyInternet:
def __init__(self):
self.hosts = {}
def register(self, hostname, server):
self.hosts[hostname] = server
def _latency(self):
return random.uniform(0.05, 0.30)
def connect(self, hostname):
if hostname not in self.hosts:
raise ConnectionError(f"DNS lookup failed: {hostname}")
server = self.hosts[hostname]
outbound = self._latency()
time.sleep(outbound)
t2, t3 = server.handle_request()
inbound = self._latency()
time.sleep(inbound)
return t2, t3, outbound, inbound
real_start = time.time()
server = TimeServer("time.tiny.com", real_start)
client = ClientDevice("My MacBook", real_start, clock_offset=3.456)
internet = TinyInternet()
internet.register("time.tiny.com", server)
print("=== Before syncing ===")
print(f"{server.name:>14}: {server.now():.6f}")
print(f"{client.name:>14}: {client.now():.6f}")
print(f"{'difference':>14}: {abs(server.now() - client.now()):.6f}s")
print()
for i in range(1, 6):
result = client.sync(internet, "time.tiny.com")
diff = abs(server.now() - client.now())
print(f"--- Sync #{i} ---")
print(
f"T1={result['t1']:.6f} T2={result['t2']:.6f} "
f"T3={result['t3']:.6f} T4={result['t4']:.6f}"
)
print(
f"path: {result['outbound'] * 1000:6.1f} ms out, "
f"{result['inbound'] * 1000:6.1f} ms back"
)
print(f"asymmetry: {result['asymmetry'] * 1000:+6.1f} ms")
print(f"delay: {result['delay']:.6f} s")
print(f"offset: {result['offset']:+.6f} s")
print(f"difference:{diff:>12.6f} s")
print()
Both machines share the same real_start, so their clocks disagree only by the offset we inject. The client also applies the full correction immediately. Real NTP adjusts the clock more cautiously; stepping it here makes the effect easier to observe.
TinyInternet.connect() returns the outbound and inbound delays so we can compare them with the estimated offset. That helps us trace the error back to the network asymmetry.
A Sample Run
Here is a representative run, trimmed down to the first few exchanges:
=== Before syncing ===
time.tiny.com: 1700000000.000021
My MacBook: 1700000003.456025
difference: 3.456004s
--- Sync #1 ---
T1=1700000003.456030 T2=1700000000.102146 T3=1700000000.105799 T4=1700000003.670822
path: 102.1 ms out, 108.9 ms back
asymmetry: +6.8 ms
delay: 0.211139 s
offset: -3.453454 s
difference: 0.002550 s
--- Sync #2 ---
T1=1700000000.217409 T2=1700000000.405950 T3=1700000000.410667 T4=1700000000.621847
path: 188.4 ms out, 206.4 ms back
asymmetry: +18.0 ms
delay: 0.399721 s
offset: +0.009680 s
difference: 0.012230 s
--- Sync #3 ---
T1=1700000000.631612 T2=1700000000.874329 T3=1700000000.878251 T4=1700000001.027197
path: 242.5 ms out, 148.9 ms back
asymmetry: -93.6 ms
delay: 0.391663 s
offset: -0.045858 s
difference: 0.033628 s
Your numbers will differ from run to run, though the pattern will be similar.
How To Read That Output
The client's clock starts 3.456 seconds off. The first exchange brings that error down to a few milliseconds, showing how much of the initial correction NTP can make in one exchange.
The later exchanges don't move steadily towards zero error. One round leaves the clock 2 milliseconds off, the next 12 milliseconds, and then 33 milliseconds. This variation follows from the estimator's assumptions.
The asymmetry line explains why. In the third sync above, the outbound trip is about 242.5 ms and the return trip is about 148.9 ms. Those paths differ by roughly 93.6 ms. Since the offset formula assumes they are equal, some of that asymmetry leaks into the clock estimate.
Being able to inspect the errors helped me understand why the real protocol uses repeated samples, filtering, and gradual correction.
What This Toy Leaves Out
This is a simulation of the offset calculation, not a full NTP implementation. Real NTP also has to handle the following:
-
Repeated sampling. A single exchange is a noisy observation. Real implementations poll over time and use a stream of measurements to correct the clock.
-
Clock discipline. This toy applies the full offset immediately. A real system usually slews the clock by making it run slightly faster or slower, because abrupt jumps can break timers, logs, and long-running processes.
-
Frequency error. A clock can run fast or slow as well as show the wrong time at a given instant. Production NTP implementations continuously estimate oscillator drift so the clock stays accurate between polls.
-
Sample filtering. Queueing spikes, transient congestion, and other delay anomalies make some exchanges less reliable. Real NTP prefers lower-delay, lower-jitter samples and gives less weight to noisy ones.
-
Multiple time sources. A real client usually compares several upstream sources and avoids those that appear inconsistent or unstable.
-
Estimate quality. Measurements such as jitter, dispersion, and root distance help the system assess how much to trust its current estimate.
-
The server hierarchy. NTP servers have strata and upstream references, with varying distances from primary reference clocks. Our single client and perfect server leave out those layers.
I left these out to keep the code focused on how delay asymmetry affects the offset estimate.
Try It Yourself
Change clock_offset to 30.0 or 500.0 and the first sync still does most of the work. Widen the latency range to something harsher like random.uniform(0.1, 2.0) and the oscillations become more obvious. If you want to push the experiment further, print half the asymmetry next to the computed offset and compare the two.
I find NTP satisfying to study because it can work with an imperfect, unstable network. A few timestamps and an assumption about delay give us an estimate; repeated measurements help refine it.