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

Clock Synchronization Problem

Every machine has its own clock, and they never agree exactly.

โฑ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

The clock synchronization problem is simple to say: every machine has its own clock, no two clocks agree exactly, and in a distributed system you cannot fully trust any of them to say which event came first.

  • Each computer keeps time with a small crystal. It drifts: it runs a little fast or slow, by tens of milliseconds a day or more.
  • Protocols like NTP pull clocks back toward true time, but only to within a few milliseconds (or worse on a bad network), never to zero.
  • So a timestamp can put a newer event before an older one. Code that trusts timestamps for ordering (like "last write wins") can silently lose data.

02Concept: What is it?

On one machine, ordering is easy: there is one clock, and it only moves forward. In a distributed system there are many machines, each with its own clock, and they talk over a network that has delays you cannot predict.

Two things go wrong. First, clock skew: at one instant, two clocks show different times. Second, clock drift: the gap keeps growing, because each crystal ticks at a slightly different speed. A common cheap crystal can be off by about 50 parts per million (ppm), which is roughly 4 seconds of error per day.

To fight this, machines ask a time server for the right time. NTP (Network Time Protocol) measures the round trip, assumes the delay was split evenly between the two directions, and adjusts the local clock. If the outgoing and returning delays are not equal, the clock ends up wrong by about half of the difference. Even after syncing, error is usually a few milliseconds on a good network and can be much worse on a bad one.

Two clocks that disagree
True time
๐Ÿ–ฅ๏ธA writes at 10:00:00.100
โ†“100 ms later
๐Ÿ–ฅ๏ธB writesreally later
What the clocks say
๐Ÿ–ฅ๏ธA stamps 10:00:00.100
โ†“B is 300 ms slow
๐Ÿ–ฅ๏ธB stamps 09:59:59.900looks earlier!
Server B really writes after Server A, but its slow clock gives its write an older timestamp.
๐Ÿง Time in a cluster is a range, not a point
A wall-clock reading really means "the time is somewhere in this window". If two events are closer together than the size of the window, their order is unknown.

03Real-Life Example

๐ŸตTwo Cashiers with Different Watches
Two cashiers write the time on each receipt using their own wrist watches. One watch is 5 minutes slow. A customer is charged at one till, then at the other till 2 minutes later, to fix a mistake. When the manager sorts the receipts by the time printed on them, the correction looks like it happened before the original charge. The manager cancels the wrong one. Nobody lied, the watches were simply different.
Cashiers
Distributed system
A wrist watch
A machine's hardware clock
Watches run at slightly different speeds
Clock drift
Two watches show different times right now
Clock skew
Setting your watch by the shop clock
NTP sync
The walk to the shop clock takes time
Network delay in the sync
Sorting receipts by printed time
Last-write-wins by timestamp
A shared tally book that only counts receipts in order
A logical clock
How one NTP exchange works
๐Ÿ–ฅ๏ธClientasks: what time?
โ†’โ†“request
๐Ÿ•ฐ๏ธTime serverreplies with its time
โ†’โ†“reply
๐Ÿ”งClient adjustsoffset โ‰ˆ server โˆ’ (send + round trip รท 2)

04Why Do We Need It?

๐ŸงฉOrder matters
Databases, logs and chat apps all need to know what happened first. Time is the obvious tool, and it is a flawed one.
๐Ÿ—‘๏ธSilent data loss
Last-write-wins uses timestamps to pick a winner. A slow clock lets an older write beat a newer one.
๐Ÿ”Expiry and tokens
A token or lease that expires at a set time can end early or late if the checker's clock is wrong.
๐Ÿ”Debugging
Logs from many machines are merged by timestamp. With skew, causes appear after their effects.
๐Ÿ”’Locks and leases
A lock that expires by time can be held by two clients if a clock jumps.
โš–๏ธCourts and finance
Some systems must prove the exact order of trades, so they pay for very accurate clocks.
You cannot make all clocks agree perfectly. Either buy better clocks and track the uncertainty, or stop using time to order events.

05Where Do We Use It?

๐Ÿ—„๏ธMulti-leader databases
Cassandra and others resolve conflicting writes with timestamps (last-write-wins). Clock skew can pick the wrong one.
๐Ÿ“œLog aggregation
Merging logs from many servers by time can misorder events. Trace IDs help.
๐Ÿ”‘Certificates and tokens
TLS certificates and JWTs have valid-from and valid-until times. A wrong clock makes valid ones fail.
โฒ๏ธLeases and timeouts
Leader leases and lock expiry depend on how long a node thinks has passed.
๐ŸŒGlobal databases
Google Spanner uses special clocks and tracks the uncertainty to order transactions worldwide.
๐Ÿ“ˆMetrics and monitoring
Graphs from many hosts line up only if their clocks do.

06Types / Parts / How It Works

Where clock errors come from

CauseWhat happensTypical size
DriftThe crystal ticks a little too fast or slow, and the error grows over timeAround 10 to 200 ppm, so a few seconds a day
Initial offsetA machine boots with the wrong timeCan be seconds, minutes or more
Network asymmetryNTP assumes equal delay both ways, but the paths differHalf of the difference, often a few ms
Virtual machinesA paused or migrated VM wakes up with an old clockCan be seconds
Leap secondsUTC adds a second, and some software repeats or skips it1 second
Clock stepsA sync can jump the clock backward, so time seems to go backWhatever the correction is

Ways to deal with it

Three families of answers
๐Ÿ”งSync betterNTP, PTP, GPS and atomic clocks
๐Ÿ“Track the errorSpanner TrueTime: wait out the uncertainty
๐Ÿ”ขDo not use wall timeLogical clocks (counters)
Pick by how much ordering your system really needs.
ApproachIdeaCost
NTPSync over the internet or a local serverCheap, but only milliseconds of accuracy
PTP (Precision Time Protocol)Hardware timestamps in the network cardsMicrosecond accuracy, needs special hardware
GPS / atomic clocksEach data centre has its own accurate referenceExpensive, used by the biggest systems
TrueTime (Spanner)A clock returns an interval [earliest, latest], and a commit waits out the intervalWaits a few ms per commit
Monotonic clockA clock that never jumps backward, only used for measuring durationsCannot compare across machines
Logical clocksOrder events by counters and messages, not by timeNot tied to real time
VisualizerLast-write-wins with a wrong clockServer B writes after Server A. Increase drift or time since sync, or switch off NTP, and watch B's timestamp slip behind A's. Then widen the real gap until the order is right again.
How is Server B's clock kept in time?

Server B's clock was never synced. It started 200 ms behind true time and then keeps drifting.

What really happened (true time). B wrote after A.
A writesB writes
What the clocks say (the timestamps stored with the data)
A writesB writes
Same scale on both lines. The further B's marker moves left of its true spot, the bigger the clock error.
B's clock error
290 ms
B is behind true time
Real gap
100 ms
B wrote later
Timestamps say
A is later
what last-write-wins sees
Safe only if gap is above
290 ms
the clock error
Wrong order! B really wrote 100 ms after A, but B's slow clock stamped it 190 ms earlier than A's write. Last-write-wins keeps A's older value and silently throws B's newer value away.

A simplified model with a fixed formula and no random numbers. Clock drift of 1 ppm means 1 microsecond of error for every second. Real clocks also change speed with temperature and load, and real NTP errors vary from one exchange to the next.

07How to Use It / Steps / Implementation

Living with imperfect clocks

  1. 1
    Run NTP everywhere
    Use at least a few time sources, and monitor the offset. Alert when a machine is off by more than your limit.
  2. 2
    Use the right clock for the job
    Use the monotonic clock to measure how long something took (timeouts, latency). Use the wall clock only to show a time to a human.
  3. 3
    Never order events by wall time alone
    If order really matters, use a logical clock, a version number, or a single sequencer such as a database auto-increment.
  4. 4
    Treat a timestamp as a range
    If two timestamps are closer than your clock error, treat them as unordered, or wait until the uncertainty has passed.
  5. 5
    Avoid last-write-wins for important data
    Prefer versions with conflict detection (vector clocks) or mergeable types (CRDTs).
  6. 6
    Leave margin on leases and tokens
    Make leases expire a bit early on the holder's side, so a clock error does not leave two holders.
  7. 7
    Smooth the leap second
    Some cloud providers โ€œsmearโ€ it over many hours so no clock repeats a second. Make sure all your machines use the same method.
๐Ÿ’กWall clock vs monotonic clock
The wall clock answers "what time is it?" and can jump forward or backward when it is corrected. The monotonic clock answers "how much time has passed?" and never goes backward. Use each for what it is good at.
โš ๏ธA backward jump breaks code
A timeout like end โˆ’ start using the wall clock can become negative if NTP steps the clock back in the middle. Use a monotonic clock for it.

08Key Terms to Know

TermMeaning in easy words
Clock skewThe difference between two clocks at the same moment
Clock driftThe rate at which a clock slowly gets ahead of or behind true time
ppmParts per million. 50 ppm means 50 microseconds of error for each second
NTPNetwork Time Protocol, which adjusts a clock using a time server
PTPPrecision Time Protocol, a hardware-assisted sync with microsecond accuracy
Wall clockThe time of day, which can jump when corrected
Monotonic clockA clock that only moves forward, good for measuring durations
Last-write-wins (LWW)A conflict rule that keeps the write with the largest timestamp
TrueTimeGoogle's clock API that returns a time range, not a single time
Leap secondAn extra second added to UTC to keep it close to Earth's rotation
Happened-beforeA cause-and-effect order between events that does not need clocks

09Pros, Cons and Trade-offs

โœ… Pros
  • Wall-clock time is easy to understand and show to people
  • Close to real time, so it works for logs, billing and expiry
  • NTP is cheap, standard and good enough for many jobs
  • Special hardware can give very tight bounds when needed
โš ๏ธ Cons
  • Never exactly equal on two machines
  • Can jump backward when corrected
  • Wrong ordering can silently lose data
  • Accuracy depends on the network and is hard to prove
  • Better accuracy needs costly hardware

Trade-offs

ChoiceWe gainWe lose
Wall-clock timestampsReal-world meaning and simple codeWrong order when clocks differ
Logical clocksCorrect cause-and-effect orderNo link to real time
Atomic clocks and GPSVery small errorCost and operations work
Waiting out uncertainty (TrueTime)Strong ordering across the globeEach commit waits a few ms
Last-write-winsVery simple conflict handlingLost updates when clocks are off
Frequent NTP syncSmaller driftMore traffic, and visible clock steps

10Common Problems and Mistakes

Common mistakes

  1. Trusting timestamps from different machines. Comparing them to find the newer write is a coin flip when they are close.
  2. Measuring durations with the wall clock. A clock step can make a timeout negative or very long.
  3. Assuming NTP is exact. It is only good to a few milliseconds, and can be far worse under load.
  4. No monitoring of clock offset. One bad machine can quietly corrupt data for weeks.
  5. Using timestamps as unique IDs. Two servers can create the same value at the same time.
  6. Forgetting VMs and containers. A paused VM resumes with a stale clock.
  7. Mixing time zones. Store UTC, and only convert when showing to a person.

Things to watch

โ†ฉ๏ธClock goes backward
After a sync step, new events can get older timestamps than old ones.
๐ŸงŠPaused processes
A long garbage collection pause can make a lease expire while the code still believes it holds it.
๐ŸชLeap seconds
Repeated seconds have crashed software. Smear them, and test.
๐Ÿ“กBad time source
A wrong or hijacked NTP server shifts every machine that trusts it. Use several sources.

11Real-World Examples

๐ŸŒGoogle Spanner
TrueTime uses GPS and atomic clocks, returns an interval, and waits out the error before committing.
๐ŸงฎCassandra
Uses write timestamps (last-write-wins). Operators are told to run NTP carefully to avoid lost writes.
โ˜๏ธAWS Time Sync Service
Gives instances a close time source, and smears leap seconds so clocks never repeat a second.
๐ŸฆTrading systems
Rules in some markets require clocks to be within microseconds of UTC, so they use PTP and GPS.
๐Ÿ“ŠCockroachDB
Uses hybrid clocks and a maximum allowed clock offset. A node that drifts too far shuts itself down.
๐Ÿ•ธ๏ธDistributed tracing
Trace IDs and parent IDs give the order of calls, not timestamps.
๐Ÿ“Note
Accuracy figures depend on hardware, network and configuration. Treat the numbers here as typical, and read the docs of the system you use.
Mini case: Spanner-style commit wait
๐Ÿ“Pick commit timelatest of the clock range
โ†’โ†“wait ~7 ms
โœ…Commit visiblereal time is now past it
Choose Wait out error Safe to show
Waiting for the clock uncertainty to pass makes the commit order match real time.
Share of the commit spent waiting out clock error (illustration)small, but paid every time

12Related Topics to Read Next

Logical Clocksโ†’

Order events by cause and effect, with no wall clock.

Lamport Timestampsโ†’

The simplest logical clock: one counter per machine.

Vector Clocksโ†’

Detect when two writes were concurrent instead of guessing a winner.

Challenges of Distributionโ†’

Unreliable clocks are one of several things that go wrong.

Consistency Modelsโ†’

Ordering rules are the heart of every consistency model.

CRDTsโ†’

Data types that merge without needing a trusted clock.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Problem: every machine has its own clock, and they never match exactly.
  • โœ”Skew vs drift: the gap now, versus how fast the gap grows.
  • โœ”NTP: fixes clocks to a few ms, not to zero. Half of the path asymmetry stays as error.
  • โœ”Danger: last-write-wins by timestamp can drop the newer write.
  • โœ”Rule: wall clock for humans, monotonic clock for durations.
  • โœ”Fix 1: better clocks and track the error (Spanner TrueTime).
  • โœ”Fix 2: stop using time to order events. Use logical clocks.
  • โœ”One line: โ€œA timestamp from another machine is a hint about the time, not a fact.โ€
โ† Previous
Consistency Models
Next โ†’
NTP: Network Time Protocol