Skip to content

Instantly share code, notes, and snippets.

@kevcodez
Last active August 28, 2022 15:31
Show Gist options
  • Save kevcodez/796737bd2930d66a8082e7445664a585 to your computer and use it in GitHub Desktop.
Save kevcodez/796737bd2930d66a8082e7445664a585 to your computer and use it in GitHub Desktop.
Simple Distributed Lock with Mongo
async function acquireLock(name) {
// Open connection to database
const collection = await db.collection('locks');
try {
// Insert an entry to the database, using the _id field, which already has a unique key constraint
await collection.insertOne({ _id: name });
// No exception was thrown, so we successfully acquired a lock
return true;
} catch (ex) {
// 11000 means duplicate key error, which is expected on an active lock
if (ex.code !== 11000) {
// Uh-Oh, this is not an exception error
throw ex;
}
return false;
}
}
async function acquireAndExecute(name, fn) {
const locked = await acquireLock(name);
if (!locked) {
// Lock could not be acquired
return;
}
await fn();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment