ZooKeeper - Lock Support

less than 1 minute read

The following pseudo logic shows how ZooKeeper is supporting a lock.

1
2
3
4
5
6
7
8
9
10
11
void acquire_lock() {
  while (true) {
    if create('f', ephem=true) {
      return;
    }

    if exist('f', watch=true) {
      wait until file f has gone
    }
  }
}

Another way to lock with a sequential file type in ZooKeeper.

1
2
3
4
5
6
7
8
9
10
11
12
void acquire_lock() {
  create seq('f', ephem=true)
  while (true) {
    list 'f*'
    if no lower #file
      return;
    
    if exists(next lower #file, watch=true) {
      wait
    }
  }
}

Even though Zookeeper provides a locking mechanism it does not support transaction so if one of clients modified state then crashed, there is no easy way to recover the modified invariant by next client which acquired lock.

Categories:

Updated: