Lamport Clock

Use logical timestamps as a version for a value to allow ordering of values across servers

Problem

When values are stored across multiple servers, there needs to be a way to know which values were stored before the other. The system timestamp cannot be used, because they are not monotonic and clock values from two different servers should not be compared.

The system timestamp, which represents the time of the day, is measured by clock machinery generally built with a crystal oscillator. The known problem with this mechanism is that it can drift away from the actual time of the day. To fix this, computers typically have a service such as NTP which synchronizes the computer clock with reference time sources on the Internet. Because of this, two consecutive readings of the system time on a given server can have time going backwards.

As there is no upper bound on clock drift across servers, it is impossible to compare timestamps on two different servers

Solution

A Lamport clock maintains a single number to represent timestamps: Every cluster node maintains an instance of a Lamport clock.

Whenever a server carries out any write operation, it should advance the Lamport clock using the `tick()` method:

class LamportClock

  public int tick(int requestTime) {
      latestTime = Integer.max(latestTime, requestTime);
      latestTime++;
      return latestTime;
  }

This way, the server can be sure that the write is sequenced after the request and after any other action the server has carried out since the request was initiated by the client. The server returns the timestamp that was used for writing the value to the client. The requesting client then uses this timestamp to issue any further writes to other set of servers. This way, the causal chain of requests is maintained.

for more details go to Chapter 22 of the online ebook at oreilly.com

This pattern is part of Patterns of Distributed Systems

23 November 2023