Help me choose
Book/Designing Data Intensive Applications

[DDIA-II] The trouble with distributed systems

by hajinny 2021. 11. 30.

1 Clocks

Clock is how many times a quartz (a unit that physically vibrates) has vibrated from a set point in time.

 

NTP is network time protocol that adjusts clocks. We have two kinds of clocks for two different kind of uses, and in both cases, NTP adjusts the clock. However, the clock adjustment strategy is differnet for each.

 

1. When we have two computers and see which one clicked a button first, we want to get time from computer 1 and computer 2 and compare them - that's where we use time-of-day clocks, as it tries to measure the absolute point in time from the common reference point in time.

 

2. When we want to see how long a process took to run on a machine, we want to sample a time right before process execution and right after process ends, and that's where we use monotonic clocks. Time is measured from an arbitrary point in time.

 

1.0 Problem with clocks on different machines

If you have two machines, they have different quartz, they vibrate at slightly different rates, and hence the incrementing rate of time is not the same across those machiens. This results in different clocks.

1.1 Time-of-day clocks

Semantically, it means the 'absolute time'. What is the time now? The reference point is fixed for any Time-of-day clocks, which is January 1970. As time passes, time returned by this clock can go back or forth in time, as opposed to monotonic clocks.

 

Under Time-of-day clocks, a computer tries to catch up to the right clock by going back or forward in time. If an application has to display time, the user will notice it flicking back or front, hence it is unreliable. However, it tries to synchronise clocks of multiple machines, which is important in distributed systems (where it's important to know which machine did an action first).

 

Java provides 'System.currentTimeMillis()'.

1.2 Monotonic clocks 

Monotonic clocks, as the name suggests, will only increase in its value as time passes. However, the frequency at which the clock ticks to increment the time can change, which slows time down to match with other clocks. (why? eg if you have multiple CPU and a process switches the CPU it runs on every now and then, then even if you try using monotonic clock, monotocity might not be guaranteed if those CPUs don't share the same clock)