async-mutex-v2
v2.1.0
Published
A fast, lightweight, Promise-based mutex for JavaScript and TypeScript applications.
Downloads
448
Readme
async-mutex-v2
A fast, lightweight, Promise-based mutex for JavaScript and TypeScript applications.
async-mutex-v2 is a modern synchronization library designed for asynchronous JavaScript environments. It provides a simple, reliable way to protect critical sections of code, preventing race conditions when multiple asynchronous operations compete for shared resources.
Whether you're building trading bots, API services, distributed workers, task schedulers, or high-concurrency applications, async-mutex-v2 helps ensure that sensitive operations execute safely and sequentially.
Why async-mutex-v2?
JavaScript is single-threaded, but asynchronous operations frequently execute concurrently. When multiple tasks modify the same resource simultaneously, unexpected behavior can occur.
async-mutex-v2 serializes access to critical sections, ensuring that only one asynchronous operation holds the lock at any given time.
Without a Mutex
Task A
Task B
Task C
Shared balance:
100
+20
-10
+50
Final balance may become incorrect.With async-mutex-v2
Task A acquires lock
Task A completes
Task B acquires lock
Task B completes
Task C acquires lock
Task C completes
Shared resource remains consistent.Features
- Lightweight with minimal overhead
- Promise-based API
- Zero runtime dependencies
- Automatic lock management
- Manual lock acquisition support
- TypeScript support
- CommonJS and ES Module compatible
- Predictable FIFO lock queue
- Suitable for high-concurrency workloads
- Easy integration into existing projects
Installation
npm install async-mutex-v2or
yarn add async-mutex-v2or
pnpm add async-mutex-v2Quick Start
Using runExclusive()
const { Mutex } = require("async-mutex-v2");
const mutex = new Mutex();
await mutex.runExclusive(async () => {
console.log("Protected code");
});Manual Lock
const { Mutex } = require("async-mutex-v2");
const mutex = new Mutex();
const release = await mutex.acquire();
try {
console.log("Critical section");
}
finally {
release();
}Example
Imagine several requests attempting to update the same database record.
const { Mutex } = require("async-mutex-v2");
const mutex = new Mutex();
let counter = 0;
async function increment() {
await mutex.runExclusive(async () => {
const current = counter;
await new Promise(resolve => setTimeout(resolve, 100));
counter = current + 1;
});
}
await Promise.all([
increment(),
increment(),
increment(),
increment(),
increment()
]);
console.log(counter);Output
5Without synchronization, the result could be unpredictable.
API Reference
new Mutex()
Creates a new mutex instance.
const mutex = new Mutex();acquire()
Acquires the mutex.
Returns a Promise that resolves to a release function.
const release = await mutex.acquire();
try {
// Critical section
}
finally {
release();
}runExclusive(callback)
Runs a callback while holding the mutex.
The lock is automatically released when the callback completes or throws an error.
await mutex.runExclusive(async () => {
// Protected code
});TypeScript
import { Mutex } from "async-mutex-v2";
const mutex = new Mutex();
await mutex.runExclusive(async () => {
console.log("TypeScript supported");
});Real-World Use Cases
async-mutex-v2 is commonly useful in applications such as:
- Cryptocurrency trading bots
- Prediction market bots
- Automated arbitrage systems
- REST API servers
- Express.js middleware
- Database transaction coordination
- Redis cache synchronization
- Background workers
- Queue processors
- Payment systems
- File processing pipelines
- Scheduled jobs
- Inventory management
- Financial applications
- Distributed task execution
Best Practices
- Keep critical sections as short as possible.
- Always release manually acquired locks inside a
finallyblock. - Avoid performing unnecessary I/O while holding a lock.
- Prefer
runExclusive()for cleaner, safer code. - Create separate mutexes for unrelated shared resources.
Performance
async-mutex-v2 is designed with performance in mind.
- Lightweight implementation
- Minimal memory footprint
- Efficient Promise queue
- FIFO lock scheduling
- Suitable for long-running Node.js services
Compatibility
| Runtime | Supported | | ----------- | --------- | | Node.js 16+ | ✅ | | Node.js 18+ | ✅ | | Node.js 20+ | ✅ | | Node.js 22+ | ✅ | | CommonJS | ✅ | | ES Modules | ✅ | | TypeScript | ✅ |
Contributing
Contributions are welcome.
If you discover a bug, have an idea for a new feature, or want to improve the documentation, feel free to open an issue or submit a pull request.
License
MIT License
Copyright (c) 2026
Keywords
mutex
async
lock
synchronization
promise
queue
typescript
nodejs
javascript
concurrency
race-condition
critical-section