SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Clock Synchronization Problem
  • NTP: Network Time Protocol
  • Logical Clocks
  • Lamport Timestamps
  • Vector Clocks
  • Hybrid Logical Clocks (HLC)
  • TrueTime (Google Spanner)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Time and Ordering

NTP: Network Time Protocol

How machines ask a time server for the time, and why the answer is only good to a few milliseconds.

⏱ 12 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

NTP (Network Time Protocol) is how almost every computer keeps its clock close to the right time. A machine asks a better clock "what time is it?", measures how long the answer took to travel, and corrects itself.

  • One exchange gives four timestamps. From them, the client works out its offset (how wrong it is) and the delay (round trip).
  • It assumes the trip there took as long as the trip back. That guess is its main source of error.
  • Over the internet it is good to a few milliseconds; in a good data centre, to well under one. Never exact.

02Concept: What is it?

Every computer has a cheap quartz clock that drifts. NTP, one of the oldest internet protocols (designed by David Mills in the 1980s), fixes this by comparing your clock with a server whose clock is better. The servers are arranged in layers called strata. Stratum 0 is the real source (GPS receivers and atomic clocks). Stratum 1 servers are plugged directly into those. Stratum 2 servers sync from stratum 1, and so on.

One exchange works like this. The client records t1 (its clock when it sends the request). The server records t2 (its clock when the request arrives) and t3 (its clock when it sends the reply). The client records t4 (its clock when the reply arrives). Now:

  • Delay = (t4 − t1) − (t3 − t2). Total time on the wire, leaving out the time the server spent thinking.
  • Offset = ((t2 − t1) + (t3 − t4)) / 2. How far the client clock is from the server clock.
The four timestamps
🖥️Clientt1 send, t4 receive
↔request ↔ reply
🕰️Servert2 receive, t3 send
The client's clock and the server's clock are different clocks. Each timestamp is read on its own machine.

The offset formula quietly assumes the request and the reply each took half of the delay. If the request took 5 ms and the reply took 25 ms, the formula is wrong by 10 ms (half the difference), and the client cannot tell.

🧠The two limits of NTP
NTP cannot be better than half the round-trip time (the worst case), and it is wrong by half the path difference (the usual case). A short, steady path is a good path.

03Real-Life Example

🍵Setting Your Watch by Phone
You phone a friend who has the exact time, and say "tell me the time when you hear me". You note your watch when you start talking (t1). They note the time when they hear you (t2), then say the time back to you at t3. You hear it at t4. You do not know how long each direction took, but you know the total, so you guess it was half each way and move your watch. If the line was equally fast both ways, you are perfectly right. If your voice had to go through a slow satellite link but their answer came back fast, your watch is a little off, and you cannot know.
The phone call
NTP
Your watch
The client clock
Your friend with the exact time
A time server
Your friend's friend, who set their clock from a radio
A higher stratum (closer to the real source)
Noting the time you started talking
t1
Guessing half the delay each way
The symmetric path assumption
Calling three friends and ignoring the one that is odd
Using several servers and discarding outliers
Slowly moving the watch hands to avoid confusion
Slewing
Strata: the chain of trust
🛰️Stratum 0GPS, atomic clock (not on the network)
↓
🖥️Stratum 1server wired to stratum 0
↓
🖥️Stratum 2syncs from stratum 1
↓
💻Your laptop or serverstratum 3 and up
Each layer is a little less exact than the one above it.

04Why Do We Need It?

🧾Readable logs
Logs from many machines only line up if their clocks are roughly right.
🔐Security
Certificates, tokens (JWT) and Kerberos check times. A clock that is off by minutes breaks logins.
⏰Expiry and scheduling
Cache expiry, locks with leases, cron jobs and billing all use the wall clock.
🗄️Databases
Last-write-wins stores like Cassandra pick a winner by timestamp. Bad clocks lose real writes.
🪪Everyone uses it
It is built into every OS and every cloud. You get it with no code.
🪜Base for better clocks
Understanding its limit explains why TrueTime and logical clocks exist.
NTP makes clocks good enough for humans and for most software, and its error bound is what tells you when you need something stronger.

05Where Do We Use It?

☁️Cloud providers
AWS Time Sync and Google's NTP service give every VM a nearby, steady source.
🏢Company networks
A few internal servers sync from the outside, and all other machines sync from them.
🧰Kubernetes and VMs
Nodes run chrony or systemd-timesyncd. Pods share the node clock.
🏦Finance rules
Regulations such as MiFID II require trading clocks to be within set limits of real time.
📡Telecom and power
These use PTP (Precision Time Protocol) for sub-microsecond accuracy over special hardware.
🔎Monitoring
Alert when a node's offset passes a limit, so a drifting clock is caught early.

06Types / Parts / How It Works

What a client does with one reading

StepWhat happensWhy
Poll several serversTake samples from 3 to 5 sourcesOne server might be wrong
Filter samplesKeep the one with the shortest delayA short trip leaves less room for asymmetry
Pick the agreeing groupDrop servers whose time disagrees with the majorityRemoves broken or hijacked sources
Combine and correctUse a weighted average, then fix the clockSmoother and safer than trusting one answer
Adjust poll intervalPoll often at first, then every few minutesSaves traffic once the clock is steady

Slew or step?

Two ways to fix a clock that is wrong
Slew (gentle)
🐢Run a bit faster or slowerup to about 0.05%
↓
✅Time never jumps backbut a big gap takes a long time
Step (jump)
🦘Set the clock at onceused for large errors
↓
⚠️Time can go backwardstimers and logs can break
Slew by default. Step only when the clock is far off, ideally at boot.

Other things worth knowing

ItemWhat it isWhat to remember
ntpdThe classic NTP daemonMature, but slow to converge
chronyA newer daemon (default on many Linux systems)Faster to sync, copes well with sleeping VMs and bad networks
Leap secondOne extra second added to UTC now and thenA clock may show 23:59:60 or repeat a second. Big sites 'smear' it over many hours instead
PTPPrecision Time Protocol, with hardware timestamps in network cardsMicrosecond or better, but needs support from switches
NTSNetwork Time SecurityAdds authentication so nobody can fake the server
Monotonic clockA clock that only goes forward and is not set by NTPUse it to measure how long something took
VisualizerOne NTP exchange: make the two paths unequalSet the client clock error, then change the request and reply delays. With equal delays the guess is perfect. Make one longer and watch the mistake grow to half the difference. Then compare slew with step.
Client (clock may be wrong)Server (clock is right)request, 10 msreply, 10 mst1 = 1040t2 = 1010t3 = 1011t4 = 1061
offset = ((t2 − t1) + (t3 − t4)) / 2 = -40 ms  |  delay = (t4 − t1) − (t3 − t2) = 20 ms
Real error of client
+40 ms
what we want to find
NTP says client is off by
+40 ms
its best guess
Mistake in the guess
0 ms
half the path difference
Round trip
20 ms
the guess can never be better than ± half
Both directions took 10 ms, so the answer is exact: NTP guesses -40 ms and the real error was -40 ms. The guess is perfect only because the two paths are equal.
The error can never be larger than ±10 ms (half the round trip), and it hits that worst case only when one direction took all of the delay. After this fix the client would still be off by about 0 ms.
How does the client apply the fix?
Slew: the clock runs slightly slow (at most 0.05 percent) until the gap is gone. Fixing 40 ms takes about 80 seconds. Time never jumps and never goes backwards.

A simplified model: the server clock is perfect, the server needs 1 ms to reply, and the clock rate does not change during the exchange. Real NTP repeats this with several servers, throws away the worst samples (the longest delays), and filters the rest.

07How to Use It / Steps / Implementation

Running NTP well

  1. 1
    Use your cloud's time service
    In a cloud, point to the provider's own source (a link-local address). It is close, fast and steady.
  2. 2
    Configure at least 3 sources
    With 2, if they disagree you cannot tell which is right. With 4 or more, one liar can be outvoted.
  3. 3
    Prefer chrony on servers
    It converges faster and copes with VM pauses and network changes.
  4. 4
    Slew, do not step, on a running machine
    Only allow a step at boot or when the error is very large. Stepping can move time backwards under running apps.
  5. 5
    Monitor the offset
    Export the offset and alert when it passes your limit (for example 50 ms). Also alert if the daemon is not synced.
  6. 6
    Use a monotonic clock for timers
    Measure durations and timeouts with the monotonic clock (for example System.nanoTime, time.monotonic, CLOCK_MONOTONIC).
  7. 7
    Design for the error
    If your logic needs order across machines closer than the offset, do not use the wall clock. Use logical, hybrid or TrueTime-style clocks.
💡Quick check on Linux
chronyc tracking shows the current offset, and chronyc sources shows which servers are used and how far off each one is.
⚠️Keep the error bound in mind
Treat the offset NTP reports as a lower bound on your error, not a promise. The path asymmetry NTP cannot see is not in that number.

08Key Terms to Know

TermMeaning in easy words
NTPNetwork Time Protocol, which sets a clock from a time server
OffsetHow far the client clock is from the server clock
DelayRound-trip network time, not counting the server's thinking time
t1, t2, t3, t4The four timestamps: client send, server receive, server send, client receive
StratumHow many hops a server is from the real time source (0 is the best)
SlewGradually speeding up or slowing the clock to fix it, with no jump
StepSetting the clock at once, which can make time jump backwards
AsymmetryWhen the trip there and the trip back take different times
JitterHow much the delay changes from one exchange to the next
Leap secondAn extra second occasionally added to UTC
Leap smearSpreading a leap second over many hours so no one sees a jump
PTPPrecision Time Protocol, a more accurate sync using hardware timestamps
Monotonic clockA clock that only moves forward, ideal for measuring durations

09Pros, Cons and Trade-offs

✅ Pros
  • Built into every operating system
  • Free, standard and well understood
  • Uses several sources to avoid one bad clock
  • Good enough for logs, certificates and most scheduling
  • Cheap: tiny packets, low traffic
⚠️ Cons
  • Accuracy limited to milliseconds on the internet
  • Assumes equal path delay, so asymmetry becomes hidden error
  • Can step time backwards if configured poorly
  • Unauthenticated by default, so it can be spoofed
  • Not enough to order events across machines

Trade-offs

ChoiceWe gainWe lose
Slew onlyTime never jumpsA big error takes a long time to fix
Step when largeFast recoveryRisk of time going backwards
Poll more oftenLess drift between syncsMore traffic and more noise from one-off delays
Many sourcesResists a bad serverMore setup and more to monitor
Local GPS or PTPMicrosecond accuracyHardware cost and special network gear
Leap smearNo odd 23:59:60Your clock differs from other clocks for a few hours

10Common Problems and Mistakes

Common mistakes

  1. Assuming NTP is exact. It is a few milliseconds at best on the internet, and can be much worse on a loaded network.
  2. Measuring time with the wall clock. If NTP steps the clock back, end − start can be negative. Use a monotonic clock.
  3. Using one time source. If it is wrong, so is every machine that trusts it.
  4. Mixing leap-second styles. Some servers smear and some step, so clocks differ by up to half a second near the leap.
  5. Not monitoring. A stopped daemon lets a clock drift for days, unseen.
  6. Ordering events by timestamp across machines. A 5 ms error makes close events appear in the wrong order.
  7. Letting VMs sync twice. A hypervisor sync and a guest NTP fighting each other makes the clock jump.

Things to watch

🔀Asymmetric paths
A busy upload link or a slow route in one direction hides error that NTP cannot see.
😴VM pause and migration
A paused machine wakes up with an old clock. Make sure it re-syncs at once.
🕵️Spoofed servers
An attacker who fakes the time can break certificates. Use NTS or trusted sources.
📈Big sudden offset
A jump of seconds is a sign of a bad source or a broken daemon. Investigate before stepping.

11Real-World Examples

☁️AWS Time Sync
A built-in, high-quality source for EC2, backed by satellite and atomic clocks, with leap-second smearing.
🔍Google public NTP
Also smears leap seconds over 24 hours, so clocks never show a repeated or extra second.
🌐pool.ntp.org
A large volunteer pool of servers that most Linux systems use by default.
🗄️Cassandra and MongoDB
Warn operators to keep clocks in sync. Timestamps pick winners and drive replica behaviour.
🏛️Spanner and PTP sites
Where NTP is not enough, they use GPS, atomic clocks and hardware time sync.
🔐Kerberos and TLS
Both reject messages when the clock difference is too big (often 5 minutes by default).
📝Note
A famous leap-second bug in 2012 made many Linux servers spin at 100% CPU. Handling the extra second is a real production issue.
Mini case: negative timeout
▶️start = 12:00:00.500wall clock
→↓NTP steps back 2 s
⏹️end = 11:59:58.600wall clock
→↓end − start
💥−1.9 snegative duration
A timer measured with the wall clock breaks when NTP steps the clock back.

12Related Topics to Read Next

Clock Synchronization Problem→

Why clocks drift apart and why NTP is only part of the answer.

TrueTime (Google Spanner)→

What you do when milliseconds of doubt are too much.

Hybrid Logical Clocks (HLC)→

Wall time plus a counter, so order is safe even with imperfect clocks.

Lamport Timestamps→

Order without any clock at all.

Logical Clocks→

The big idea of ordering by cause instead of by time.

Heartbeats→

Timeouts and leases depend on clocks behaving.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Four times: t1 client send, t2 server receive, t3 server send, t4 client receive.
  • ✔Offset: ((t2 − t1) + (t3 − t4)) / 2. Delay: (t4 − t1) − (t3 − t2).
  • ✔Hidden assumption: both directions took the same time. Error = half the path difference.
  • ✔Worst case: error ≤ half the round trip. A short path is a good path.
  • ✔Strata: 0 = real source, 1 = wired to it, 2 = syncs from 1.
  • ✔Slew = gentle, no jump. Step = fast, can go backwards.
  • ✔Rules: 3+ sources, monitor offset, measure durations with a monotonic clock.
  • ✔One line: “NTP is a good guess about the time, not a promise of it.”
← Previous
Clock Synchronization Problem
Next →
Logical Clocks