Clock-Bound Wait

Wait to cover the uncertainty in time across cluster nodes before reading and writing values so that values can be correctly ordered across cluster nodes.

Problem

Both Alice and Bob can ask server Green for the latest version timestamp of the key they are trying to read. But that requires one extra round.

If Alice and Bob are trying to read multiple keys across a set of servers, they will need to ask the latest version for each and pick the maximum value.

Consider a key-value store where values are stored with a timestamp to designate each version. Any cluster node that handles a client request will be able to read the latest version using the current timestamp at the request processing node.

In Figure 24.1 , the value "Before Dawn" is updated to value "After Dawn" at time 2 as per Green’s clock. Both Alice and Bob are trying to read the latest value for "title" . While Alice’s request is processed by cluster node Amber, Bob’s request is processed by cluster node Blue. Amber has its clock lagging at 1, which means that when Alice reads the latest value, it delivers the value "Before Dawn" . Blue has its clock at 2, so when Bob reads the latest value, it returns the value as "After Dawn" .

Images

Figure 24.1 Clock skew leads to different readings by two users.

This violates what is known as external consistency. If Alice and Bob now make a phone call, Alice will be confused: Bob will tell her that the latest value is "After Dawn" , while her cluster node is showing "Before Dawn" .

The same is true if Green’s clock is fast and the writes happen in the future as per Amber’s clock.

This is a problem if system timestamp is used as a version for storing values, because system timestamps are not monotonic, as discussed in the sidebar “ Wall Clocks Are Not Monotonic ” of the Lease pattern. Clock values from two different servers cannot and should not be compared. When Hybrid Clock is used as a version in Versioned Value , it allows values to be ordered on a single server as well as on different servers which are causally related. However, hybrid clocks (or any other kind of Lamport Clock ) can only give partial order, as discussed in the section “ Partial Order ” of the Lamport Clock pattern. This means that any values which are not causally related and are stored by two different clients across different nodes cannot be ordered. This creates a problem when using a timestamp to read values across cluster nodes. If the read request originates on cluster nodes with lagging clocks, it probably won’t be able to read the most up-to-date versions of given values.

Solution

While reading or writing, cluster nodes wait until the clock values on every node in the cluster are guaranteed to be above the timestamp assigned to the value.

If the difference between clocks is very small, write requests can wait without adding a great deal of overhead. As an example, assume the maximum clock offset across cluster nodes is 10 ms. (This means that, at any given point in time, the slowest clock in the cluster is lagging behind the fastest one by at most 10 ms.) To guarantee that every other cluster node has its clock past time t , the cluster node that handles any write operation will have to wait until t + 10 ms before storing the value.

Consider a key-value store with Versioned Value where each update is added as a new value, with a timestamp used as a version. In the Alice and Bob example described above, the write operation storing title@2 will wait until all the clocks in the cluster are at 2. This makes sure that Alice will always see the latest value of the "title" even if the clock at the cluster node of Alice is lagging behind.

Consider a slightly different scenario. Philip is updating the "title" to "After Dawn" . Green’s clock has its time at 2. But Green knows that there might be a server with a clock lagging behind by up to 1 unit. It will therefore have to wait in the write operation for a duration of 1 unit ( Figure 24.2 ).

Images

Figure 24.2 Write request waits for clock offset.

While Philip is updating the "title" , Bob’s read request is handled by server Blue. Blue’s clock is at 2, so it tries to read the "title" at timestamp 2. At this point Green has not yet made the value available. This means Bob gets the value at the highest timestamp lower than 2, which is "Before Dawn" ( Figure 24.3 ).

Images

Figure 24.3 Bob reads the initial value.

Alice’s read request is handled by server Amber. Amber’s clock is at 1 so it tries to read the "title" at timestamp 1. Alice gets the value "Before Dawn" ( Figure 24.4 ).

Images

Figure 24.4 Alice reads the initial value.

Once Philip’s write request completes (after the wait of max_diff is over), if Bob now sends a new read request, server Blue will try to read the latest value according to its clock (which has advanced to 3); this will return the value "After Dawn" ( Figure 24.5 ).

Images

Figure 24.5 Bob reads the new value.

If Alice initializes a new read request, server Amber will try to read the latest value as per its clock, which is now at 2. It will therefore also return the value "After Dawn" ( Figure 24.6 ).

Images

Figure 24.6 Alice reads the new value.

The main problem when trying to implement this solution is that getting the exact time difference across cluster nodes is simply not possible with the date/time hardware and operating system APIs that are currently available. Such is the nature of the challenge that Google has its own specialized date-time API called TrueTime. Similarly, Amazon has AWS Time Sync Service 79 and a library called Clock Bound. 80 However, these APIs are very specific to Google and Amazon—they can’t be scaled beyond the confines of those organizations.

  1. [https://aws.amazon.com/about-aws/whats-new/2021/11/amazon-time-sync-service-generate-compare-timestamps](https://aws.amazon.com/about-aws/whats-new/2021/11/amazon-time-sync-service-generate-compare-timestamps)

  2. [https://github.com/aws/clock-bound](https://github.com/aws/clock-bound)

Typically, key-value stores use Hybrid Clock to implement Versioned Value. While it is not possible to get the exact difference between clocks, a sensible default value can be chosen based on historical observations. Observed values for maximum clock drift on servers across datacenters are generally between 200 ms and 500 ms. 81

  1. [https://www.yugabyte.com/blog/evolving-clock-sync-for-distributed-databases/](https://www.yugabyte.com/blog/evolving-clock-sync-for-distributed-databases/)

The key-value store waits for configured max offset before storing the value:

Click here to view code image

class KVStore...

  int maxOffset = 200;
  NavigableMap<HybridClockKey, String> kv = new ConcurrentSkipListMap<>();
  public void put(String key, String value) {
      HybridTimestamp writeTimestamp = clock.now();
      waitTillSlowestClockCatchesUp(writeTimestamp);
      kv.put(new HybridClockKey(key, writeTimestamp), value);
  }

  private void waitTillSlowestClockCatchesUp(HybridTimestamp writeTimestamp) {
      var waitUntilTimestamp = writeTimestamp.add(maxOffset, 0);
      sleepUntil(waitUntilTimestamp);
  }

  private void sleepUntil(HybridTimestamp waitUntil) {
      HybridTimestamp now = clock.now();
      while (clock.now().before(waitUntil)) {
          var waitTime = (waitUntil.getWallClockTime() - now.getWallClockTime()) ;
          Uninterruptibles.sleepUninterruptibly(waitTime, TimeUnit.MILLISECONDS);
          now = clock.now();
      }
  }

  public String get(String key, HybridTimestamp readTimestamp) {
      return kv.get(new HybridClockKey(key, readTimestamp));
  }

Read Restart

To wait 200 ms for every write request may be too much of an interval. This is why databases like CockroachDB or YugabyteDB implement a check in the read requests instead.

While serving a read request, cluster nodes check if there is a version available in the interval between readTimestamp and readTimestamp + maximum clock drift. If the version is available, the system assumes that the reader’s clock might be lagging, and asks it to restart the read request with that version:

Click here to view code image

class KVStore...

  public void put(String key, String value) {
      HybridTimestamp writeTimestamp = clock.now();
      kv.put(new HybridClockKey(key, writeTimestamp), value);
  }

  public String get(String key, HybridTimestamp readTimestamp) {
      checksIfVersionInUncertaintyInterval(key, readTimestamp);
      return kv.floorEntry(new HybridClockKey(key, readTimestamp)).getValue();
  }

  private void checksIfVersionInUncertaintyInterval(String key,
                                          HybridTimestamp readTimestamp) {
      var uncertaintyLimit = readTimestamp.add(maxOffset, 0);
      var versionedKey = kv.floorKey(new HybridClockKey(key,
              uncertaintyLimit));
      if (versionedKey == null) {
          return;
      }
      var maxVersionBelowUncertainty = versionedKey.getVersion();
      if (maxVersionBelowUncertainty.after(readTimestamp)) {
          throw new ReadRestartException(readTimestamp,
                  maxOffset,
                  maxVersionBelowUncertainty);
      }
      ;
  }

class Client...

  String read(String key) {
      int attemptNo = 1;
      int maxAttempts = 5;
      while(attemptNo < maxAttempts) {
          try {
              HybridTimestamp now = clock.now();
              return kvStore.get(key, now);
          } catch (ReadRestartException e) {
              logger.info(" Got read restart error " + e + "Attempt No. " + attemptNo);
              Uninterruptibles
                      .sleepUninterruptibly(e.getMaxOffset(), TimeUnit.MILLISECONDS);
              attemptNo++;
          }
      }
      throw new ReadTimeoutException("Unable to read after " + attemptNo + " attempts.");
  }

In the Alice and Bob example above, if there is a version for "title" available at timestamp 2, and Alice sends a read request with read timestamp 1, a ReadRestartException will be thrown asking Alice to restart the read request at timestamp 2 ( Figure 24.7 ).

Images

Figure 24.7 Read restart due to clock skew

Read restarts only happen if there is a version written in the uncertainty interval. Write requests do not need to wait.

It’s important to remember that the configured value for maximum clock drift is an assumption, not a guarantee. A bad server can have a clock drift more than the assumed value. In such cases, the problem will persist. 82

  1. [https://docs.yugabyte.com/latest/benchmark/resilience/jepsen-testing-ysql/#rare-occurrence-of-causal-reversal](https://docs.yugabyte.com/latest/benchmark/resilience/jepsen-testing-ysql/#rare-occurrence-of-causal-reversal)

Using Clock-Bound APIs

Cloud providers such as Google and Amazon implement clock machinery with atomic clocks and GPS to make sure that the clock drift across their cluster nodes is kept below a few milliseconds. As we’ve just discussed, Google has TrueTime; AWS has Time Sync Service and Clock Bound library.

There are two key requirements for cluster nodes to make sure these waits are implemented correctly.

  • The clock drift across cluster nodes is kept to a minimum. Google’s TrueTime keeps it below 1 ms in most cases, 7 ms in the worst cases.

  • The possible clock drift is always available in the Date-Time API, so programmers don’t need to guess the value.

The clock machinery on cluster nodes computes error bounds for date-time values. If there is a possible error in timestamps returned by the local system clock, the API makes the error explicit. It will give the lower and upper bounds on clock values. The real time value is guaranteed to be within this interval and the time span between the lower and upper bounds defines the uncertainty interval.

Click here to view code image

public class ClockBound {
    public final long earliest;
    public final long latest;

    public ClockBound(long earliest, long latest) {
        this.earliest = earliest;
        this.latest = latest;
    }

    public boolean before(long timestamp) {
        return timestamp < earliest;
    }

    public boolean after(long timestamp)   {
        return timestamp > latest;
    }

As explained in AWS blog, 83 the error is calculated at each cluster node as ClockErrorBound . The real time value will always be within ClockErrorBound from the local clock time.

  1. [https://aws.amazon.com/blogs/mt/manage-amazon-ec2-instance-clock-accuracy-using-amazon-time-sync-service-and-amazon-cloudwatch-part-1](https://aws.amazon.com/blogs/mt/manage-amazon-ec2-instance-clock-accuracy-using-amazon-time-sync-service-and-amazon-cloudwatch-part-1)

The error bounds are returned whenever date and time values are asked for.

public ClockBound now() {
    return now;
}

There are two properties guaranteed by the Clock-Bound API:

  • Clock bounds should overlap across cluster nodes.

  • For two time values t1 and t2 , if t1 is less than t2 , then clock_bound(t1).earliest is less than clock_bound(t2).latest across all cluster nodes.

Imagine we have three cluster nodes: Green, Blue, and Amber. Each node might have a different error bound. Let’s say the error on Green is 1, on Blue, 2, and on Amber, 3. Figure 24.8 shows the clock bounds across the cluster nodes at time = 4.

Images

Figure 24.8 Clock bounds across cluster nodes

In this scenario, two rules need to be followed to implement the commit-wait.

  • For any write operation, the clock bound’s latest value should be picked as the timestamp. This will ensure that it is always higher than any timestamp assigned to previous write operations (considering the second rule below).

  • Before storing the value, the system must wait until the write timestamp is less than the clock bound’s earliest value.

    This is because the earliest value is guaranteed to be lower than clock bounds’ latest values across all cluster nodes. This write operation will be accessible to anyone reading with the clock-bound’s latest value in the future. Also, this value is guaranteed to be ordered before any other write operation that may happen in the future.

Click here to view code image

class KVStore...

  public void put(String key, String value) {
      ClockBound now = boundedClock.now();
      long writeTimestamp = now.latest;
      addPending(writeTimestamp);
      waitUntilTimeInPast(writeTimestamp);
      kv.put(new VersionedKey(key, writeTimestamp), value);
      removePending(writeTimestamp);
  }

  private void waitUntilTimeInPast(long writeTimestamp) {
      ClockBound now = boundedClock.now();
      while(now.earliest < writeTimestamp) {
          Uninterruptibles
                  .sleepUninterruptibly(now.earliest - writeTimestamp,
                          TimeUnit.MILLISECONDS);
          now = boundedClock.now();
      }
  }

  private void removePending(long writeTimestamp) {
      try {
          lock.lock();
          pendingWriteTimestamps.remove(writeTimestamp);

          //Signal to any waiting read requests.
          cond.signalAll();
      } finally {
          lock.unlock();
      }
  }

  private void addPending(long writeTimestamp) {
      try {
          lock.lock();
          pendingWriteTimestamps.add(writeTimestamp);
      } finally {
          lock.unlock();
      }
  }

To return to the Alice and Bob example above, when the new value for "title" , "After Dawn" , is written by Philip on server Green, the put operation on Green waits until the chosen write timestamp is below the earliest value of the clock bound. This guarantees that every other cluster node has a higher timestamp for the latest value of the clock bound. Figure 24.9 illustrates the following scenario. Green has an error bound of ± 1. So, with a put operation that starts at time 4 when it stores the value, Green will pick the latest value of the clock bound, which is 5. It then waits until the earliest value of the clock bound is above 5. Essentially, Green waits for the uncertainty interval before actually storing the value in the key-value store.

Images

Figure 24.9 Writes wait to cover the uncertainty interval.

When the value is made available in the key-value store, the clock bound’s latest value is guaranteed to be higher than 5 on each and every cluster node. This means that Bob’s request handled by Blue ( Figure 24.10 ), as well as Alice’s request handled by Amber ( Figure 24.11 ), are guaranteed to get the latest value of the "title" .

Images

Figure 24.10 Bob reads the new value following the uncertainty interval.

Images

Figure 24.11 Alice reads the new value following the uncertainty interval.

We achieve the same outcome if Green has larger error bounds ( Figure 24.12 ). A larger error bound results in a longer waiting period. Let’s consider an error bound of ± 3. For a write occurring at time 4 on server Green, the clock bound values are (1, 7). The write timestamp is chosen as 7, and the write operation waits until the earliest clock bound value on Green exceeds 7. Neither Amber nor Blue can access the value before this point. Now, let’s say Alice’s read request is handled by Amber, which has an error bound of ± 2. Alice receives the latest value only when Amber can use a read timestamp of 7. At this juncture, every other cluster node is guaranteed to receive it at their respective server’s clock bound’s latest time value.

Images

Figure 24.12 Larger error bound causes longer wait.

Read-Wait

When reading the value, the client will always pick the maximum value from the clock bound on its cluster node.

The cluster node that is receiving the request needs to make sure that once a response is returned at a specific request timestamp, there are no values written at that timestamp or a lower timestamp.

If the timestamp in the request is higher than the timestamp at the server, the cluster node will wait until the clock catches up before returning the response.

It will then check if there are any pending write requests at a lower timestamp which are not yet stored. If there are, then the read requests will pause until the requests are complete.

The server will then read the values at the request timestamp and return the value. This ensures that once a response is returned at a particular timestamp, no values will ever be written at a lower timestamp.

Click here to view code image

class KVStore...

  final Lock lock = new ReentrantLock();
  Queue<Long> pendingWriteTimestamps = new ArrayDeque<>();
  final Condition cond  = lock.newCondition();

  public Optional<String> read(long readTimestamp) {
      waitUntilTimeInPast(readTimestamp);
      waitForPendingWrites(readTimestamp);
      Optional<VersionedKey> max = kv.keySet().stream().max(Comparator.naturalOrder());
      if(max.isPresent()) {
          return Optional.of(kv.get(max.get()));
      }
      return Optional.empty();
  }

  private void waitForPendingWrites(long readTimestamp) {
      try {
          lock.lock();
          while (pendingWriteTimestamps
                  .stream()
                  .anyMatch(ts -> ts <= readTimestamp)) {

              cond.awaitUninterruptibly();
          }
      } finally {
          lock.unlock();
      }
  }

As a final example shown in Figure 24.13 , if Alice’s read request at time 4 is handled by server Amber with an error bound interval of 3, it picks the latest time as 7 to read the "title" . Meanwhile, Philip’s write request is handled by Green with an error bound interval of 1, which picks 5 as the timestamp to store the value. Alice’s read request waits until the earliest time at Green is past 7 and the pending write request is complete. It then returns the latest value with a timestamp below 7.

Images

Figure 24.13 Read requests wait for pending writes.

Examples

  • Google’s TrueTime API provides a clock bound. Google Spanner uses it to implement commit-wait.

  • AWS Time Sync Service ensures minimal clock drifts. It is possible to use the Clock Bound library 84 to implement waits to order the events across the cluster.

    1. [https://github.com/aws/clock-bound](https://github.com/aws/clock-bound)
  • CockroachDB implements read restart. It also has an experimental option to use commit-wait based on the configured maximum clock drift value.

  • YugabyteDB implements read restart based on the configured maximum clock drift value.