javascriptfirebasefirebase-realtime-databasetransactionsmutex

Is it possible to use Firebase Realtime Database to implement a distributed mutex?


I was thinking of using a transaction like so to implement a kind of distributed lock:

const lockId = 'myLock';
const lockRef = firebaseAdmin.database().ref(`/locks/${lockId}`);
lockRef.transaction(function(current) {
  if (current === null) {
    return '1';
  }
}, function(error, committed) {
  if (committed) {
    // .... Do the synchronized work I need ...
    lockRef.remove();
  }
});

The question I have is: will the update function be called with null only if the data does not exist?

Generally, is this a valid way to implement a distributed lock?


Solution

  • A transaction will be called initially with the client's best guess to the current value. If the client doesn't have a current value in memory, its best guess is that there is no current value.

    That means that there is no guarantee whatsoever that no value actually exists in the database if you get a null.

    Also see: