distributed mutexes using cassandra



Distributed mutexes using Cassandra


This is just a proof of concept implementation of Lamport’s_Bakery_Algorithm.

It uses Cassandra to store and operate on the locks, instead of local shared memory. This is feasible because the Bakery algorithm (awesomely?) does not rely on a CAS primitive.

It supports any number of locks because they are just Cassandra rows.


# Sets up column families used for the lock data
CassandraLock.keyspace = "MyApp"
CassandraLock.host = ""

# Initialize a lock called "foo" with a maximum of 10 workers
CassandraLock.setup_lock("foo", 10)

# Create a corresponding lock handle with worker id 1 (ids start at 1, not 0)
handle = CassandraLock::Handle.new("foo", 1)

# Normal lock/unlock (waits if the lock is not available)

# Acquire, yield, and release
handle.synchronize {

# Only do something if the lock is immediately available
if handle.try_lock
  raise "couldn't acquire lock!"

Problems (lots)

  • The lock must have it's maximum number of workers predefined.

  • Workers using the lock must know their unique worker ID.

  • It has to use quorum reads and writes to be coherent.

  • It's inefficient, taking 5 or so exchanges with Cassandra just to acquire a free lock.

  • Acquisition time increases significantly with some correlation to the number of active workers.

  • A crashed worker can leave the mutex locked. This is probably addressable with Cassandra TTLs.

  • Locking in a distributed database…hmm.

Implemented by Jake Douglas at RightScale, Inc. Concept from Thorsten von Eicken.