async-lock vs async-mutex
Concurrency Control in Node.js and Browser Environments
async-lockasync-mutexSimilar Packages:

Concurrency Control in Node.js and Browser Environments

async-lock and async-mutex are both JavaScript libraries designed to manage concurrent access to shared resources in asynchronous environments. While async-mutex provides a classic mutex (mutual exclusion) primitive often used to protect a single critical section, async-lock specializes in domain-based locking, allowing developers to manage multiple independent locks keyed by string identifiers within a single instance. Both tools help prevent race conditions when handling async operations, but they differ in how they organize and scope those locks.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
async-lock042618.3 kB53 years agoMIT
async-mutex01,43463 kB153 years agoMIT

async-lock vs async-mutex: Concurrency Control Compared

Both async-lock and async-mutex solve the same fundamental problem: preventing race conditions in asynchronous JavaScript code. However, they approach the solution from different angles. async-lock focuses on managing many locks by name, while async-mutex focuses on providing robust primitive locks for specific resources. Let's look at how they handle real-world engineering challenges.

🔑 Lock Scoping: Key-Based vs Instance-Based

The biggest difference lies in how you organize your locks.

async-lock uses a single instance to manage many locks by string keys.

  • You don't create a new lock for every resource.
  • You just call the manager with a resource ID (like a user ID).
  • Great for dynamic resources where you don't know all IDs upfront.
// async-lock: One manager for all users
const Lock = require('async-lock');
const lock = new Lock();

async function updateUser(userId, data) {
  await lock.acquire(userId, async () => {
    // Only this userId is locked
    await db.update(userId, data);
  });
}

async-mutex requires a distinct instance for each independent resource.

  • You create a Mutex object for the specific thing you are protecting.
  • If you need to lock by user ID, you must manage a map of mutexes yourself.
  • Better for static, known resources like a single database connection.
// async-mutex: One instance per resource
const { Mutex } = require('async-mutex');
const userMutexes = new Map();

async function updateUser(userId, data) {
  if (!userMutexes.has(userId)) {
    userMutexes.set(userId, new Mutex());
  }
  const mutex = userMutexes.get(userId);
  
  const release = await mutex.acquire();
  try {
    await db.update(userId, data);
  } finally {
    release();
  }
}

🏃 Execution Style: Callback Wrapping vs Manual Release

How you run your protected code differs slightly between the two.

async-lock encourages wrapping your logic in a function passed to the lock.

  • The lock handles start and end automatically.
  • Less chance of forgetting to release the lock.
  • Cleaner syntax for simple tasks.
// async-lock: Automatic release
await lock.acquire('resource-key', async () => {
  await doSomething();
  // Lock released automatically after promise resolves
});

async-mutex gives you manual control over the release function.

  • You call acquire() to get a release function.
  • You must call release() in a finally block.
  • More verbose but allows complex control flow outside the lock.
// async-mutex: Manual release
const release = await mutex.acquire();
try {
  await doSomething();
} finally {
  release(); // Must call explicitly
}

Note: async-mutex also has runExclusive(), which works like async-lock's wrapper, but the manual pattern is more common in advanced use cases.

// async-mutex: Wrapper style (similar to async-lock)
await mutex.runExclusive(async () => {
  await doSomething();
});

🚦 Concurrency Limits: Mutex vs Semaphore

Sometimes you don't want to block everyone — you just want to limit how many run at once.

async-lock is strictly a mutex (one at a time per key).

  • It does not support semaphores out of the box.
  • If you need to allow 5 concurrent tasks, you need a different tool.
// async-lock: Only 1 at a time per key
await lock.acquire('key', async () => {
  // No concurrency allowed for this key
});

async-mutex includes a Semaphore class in the same package.

  • You can allow N concurrent tasks easily.
  • Useful for rate limiting or pool management.
// async-mutex: Allow 5 concurrent tasks
const { Semaphore } = require('async-mutex');
const semaphore = new Semaphore(5);

await semaphore.acquire();
try {
  await doSomething();
} finally {
  semaphore.release();
}

⏳ Timeout and Error Handling

Both libraries handle timeouts, but the configuration differs.

async-lock supports timeouts per acquisition.

  • You can pass options to acquire to fail if waiting too long.
  • Prevents deadlocks from hanging forever.
// async-lock: Timeout option
await lock.acquire('key', async () => {
  // ...
}, {
  timeout: 5000 // Fail if waiting more than 5s
});

async-mutex supports timeouts via options on the instance or acquire call.

  • Similar capability but configured on the Mutex or Semaphore.
  • Throws an error if the lock cannot be acquired in time.
// async-mutex: Timeout option
const mutex = new Mutex();

try {
  const release = await mutex.acquire({ timeout: 5000 });
  try {
    // ...
  } finally {
    release();
  }
} catch (e) {
  // Handle timeout
}

🧩 Real-World Scenarios

Scenario 1: Processing User Requests

You have an API where multiple requests might update the same user profile.

  • ✅ Best choice: async-lock
  • Why? You can lock by userId without managing a map of locks manually.
// async-lock
await lock.acquire(req.userId, async () => {
  await profileService.update(req.userId, req.body);
});

Scenario 2: Protecting a Singleton Connection

You have one shared WebSocket connection that must not write simultaneously.

  • ✅ Best choice: async-mutex
  • Why? It's a single static resource. A single Mutex instance is clear and explicit.
// async-mutex
const connectionMutex = new Mutex();

await connectionMutex.runExclusive(async () => {
  await ws.send(data);
});

Scenario 3: Rate Limiting API Calls

You need to call an external API but are limited to 10 concurrent requests.

  • ✅ Best choice: async-mutex (Semaphore)
  • Why? async-lock cannot limit concurrency to >1. Semaphore handles this perfectly.
// async-mutex
const semaphore = new Semaphore(10);

const release = await semaphore.acquire();
try {
  await externalApi.call();
} finally {
  release();
}

📊 Summary: Key Differences

Featureasync-lockasync-mutex
Lock Management🔑 Key-based (one instance)🧩 Instance-based (per resource)
Semaphore Support❌ No✅ Yes (built-in)
API Style📦 acquire(key, fn)🔓 acquire() + release()
Best ForDynamic resources (IDs, paths)Static resources, pools
Overhead📉 Low (internal map)📈 Higher (if managing many)

💡 The Big Picture

async-lock is like a receptionist at a large office 🏢.

  • You tell them which room (key) you need.
  • They manage access to all rooms for you.
  • Perfect when you have many rooms and don't want to carry keys for each.

async-mutex is like a physical key 🔑 for a specific safe.

  • You hold the key (instance) for that specific safe.
  • You decide exactly when to lock and unlock.
  • Perfect when you have one important safe or need to limit how many people enter (Semaphore).

Final Thought: If your problem involves dynamic identifiers (like user IDs, file names, or URLs), async-lock saves you from building your own lock manager. If you need strict control over a single resource or need semaphores, async-mutex is the more powerful primitive.

How to Choose: async-lock vs async-mutex

  • async-lock:

    Choose async-lock if you need to manage concurrency for multiple distinct resources (like user IDs or file paths) using a single lock manager instance. It is ideal for scenarios where you want to prevent concurrent access to specific keys without creating a new lock object for every resource. This approach reduces memory overhead and simplifies code when dealing with dynamic resource identifiers.

  • async-mutex:

    Choose async-mutex if you need a strict mutual exclusion primitive for a specific shared resource or if you require a semaphore to limit concurrency to a fixed number of workers. It is better suited for protecting a single global state, a singleton connection, or when you need fine-grained control over the acquire and release lifecycle without the overhead of key-based management.

README for async-lock

async-lock

Lock on asynchronous code

Build Status

  • ES6 promise supported
  • Multiple keys lock supported
  • Timeout supported
  • Occupation time limit supported
  • Execution time limit supported
  • Pending task limit supported
  • Domain reentrant supported
  • 100% code coverage

Disclaimer

I did not create this package, and I will not add any features to it myself. I was granted the ownership because it was no longer being maintained, and I volunteered to fix a bug.

If you have a new feature you would like to have incorporated, please send me a PR and I will be happy to work with you and get it merged. For any bugs, PRs are most welcome but when possible I will try to get them resolved as soon as possible.

Why do you need locking on single threaded nodejs?

Nodejs is single threaded, and the code execution never gets interrupted inside an event loop, so locking is unnecessary? This is true ONLY IF your critical section can be executed inside a single event loop. However, if you have any async code inside your critical section (it can be simply triggered by any I/O operation, or timer), your critical logic will across multiple event loops, therefore it's not concurrency safe!

Consider the following code

redis.get('key', function(err, value) {
	redis.set('key', value * 2);
});

The above code simply multiply a redis key by 2. However, if two users run concurrently, the execution order may like this

user1: redis.get('key') -> 1
user2: redis.get('key') -> 1
user1: redis.set('key', 1 x 2) -> 2
user2: redis.set('key', 1 x 2) -> 2

Obviously it's not what you expected

With asyncLock, you can easily write your async critical section

lock.acquire('key', function(cb) {
	// Concurrency safe
	redis.get('key', function(err, value) {
		redis.set('key', value * 2, cb);
	});
}, function(err, ret) {
});

Get Started

var AsyncLock = require('async-lock');
var lock = new AsyncLock();

/**
 * @param {String|Array} key 	resource key or keys to lock
 * @param {function} fn 	execute function
 * @param {function} cb 	(optional) callback function, otherwise will return a promise
 * @param {Object} opts 	(optional) options
 */
lock.acquire(key, function(done) {
	// async work
	done(err, ret);
}, function(err, ret) {
	// lock released
}, opts);

// Promise mode
lock.acquire(key, function() {
	// return value or promise
}, opts).then(function() {
	// lock released
});

Error Handling

// Callback mode
lock.acquire(key, function(done) {
	done(new Error('error'));
}, function(err, ret) {
	console.log(err.message) // output: error
});

// Promise mode
lock.acquire(key, function() {
	throw new Error('error');
}).catch(function(err) {
	console.log(err.message) // output: error
});

Acquire multiple keys

lock.acquire([key1, key2], fn, cb);

Domain reentrant lock

Lock is reentrant in the same domain

var domain = require('domain');
var lock = new AsyncLock({domainReentrant : true});

var d = domain.create();
d.run(function() {
	lock.acquire('key', function() {
		//Enter lock
		return lock.acquire('key', function() {
			//Enter same lock twice
		});
	});
});

Options

// Specify timeout - max amount of time an item can remain in the queue before acquiring the lock
var lock = new AsyncLock({timeout: 5000});
lock.acquire(key, fn, function(err, ret) {
	// timed out error will be returned here if lock not acquired in given time
});

// Specify max occupation time - max amount of time allowed between entering the queue and completing execution
var lock = new AsyncLock({maxOccupationTime: 3000});
lock.acquire(key, fn, function(err, ret) {
	// occupation time exceeded error will be returned here if job not completed in given time
});

// Specify max execution time - max amount of time allowed between acquiring the lock and completing execution
var lock = new AsyncLock({maxExecutionTime: 3000});
lock.acquire(key, fn, function(err, ret) {
	// execution time exceeded error will be returned here if job not completed in given time
});

// Set max pending tasks - max number of tasks allowed in the queue at a time
var lock = new AsyncLock({maxPending: 1000});
lock.acquire(key, fn, function(err, ret) {
	// Handle too much pending error
})

// Whether there is any running or pending async function
lock.isBusy();

// Use your own promise library instead of the global Promise variable
var lock = new AsyncLock({Promise: require('bluebird')}); // Bluebird
var lock = new AsyncLock({Promise: require('q')}); // Q

// Add a task to the front of the queue waiting for a given lock
lock.acquire(key, fn1, cb); // runs immediately
lock.acquire(key, fn2, cb); // added to queue
lock.acquire(key, priorityFn, cb, {skipQueue: true}); // jumps queue and runs before fn2

Changelog

See Changelog

Issues

See issue tracker.

License

MIT, see LICENSE