A mutex lock implementation leveraging DynamoDB. Useful for AWS Lambda
A mutex implementation leveraging AWS DynamoDB
Although this was built for use in AWS Lambda, note that you can use this mutex implementation in any context - even outside AWS.
sudo pip install dyndbmutex
or checkout this repository and run python setup.py
. Or download a release from the releases page and go from there.
Let’s say you want to ensure that only 1 python function can access a resource (for example an AWS instance i-8abd82c31
) at a time
from dyndbmutex.dyndbmutex import DynamoDbMutex
# at the beginning of your function
# generate a unique name for this process/thread
my_name = str(uuid.uuid4()).split("-")[0]
m = DynamoDbMutex('i-8abd832c32', holder=my_name, timeoutms=200 * 1000)
locked = m.lock()
if locked:
# critical section begin
......
# critical section end
m.release()
You can also use the with
pattern:
from dyndbmutex.dyndbmutex import DynamoDbMutex, AcquireLockFailedError
my_name = str(uuid.uuid4()).split("-")[0]
m = DynamoDbMutex('i-8abd832c32', my_name, 200 * 1000)
try:
with m:
# critical section
except mutex.AcquireLockFailedError:
#m will be released at this point
Uses DynamoDb conditional write as an atomic compare-and-swap operation to implement a mutex.
Since the conditional write is atomic (test and set), this works very well. In fact the code doesn’t even read the table, only writes to it.
(We could even make the lock re-entrant since we have the owner/holder information, but leave a note/issue if this is important for your usecase)
The default name for the Mutex table in DynamoDB is ‘Mutex’. You can change this by setting an environment variable:
export DD_MUTEX_TABLE_NAME=FancyPantsMutex
The code will auto-create the mutex DynamoDB table, but this could take at least 20 seconds. As an alternative, use the create-table
script in the scripts directory before using this mutex library.
Although the code is general-purpose and can be used outside of AWS Lambda, note the following limitations:
ttl_minutes
in the constructor to choose a different TTL