@origins-digital/concurrency-handler
v0.2.0
Published
Concurrency package
Readme
@origins-digital/concurrency-handler
A simple and lightweight concurrency control package for Node.js applications that provides a function for managing concurrent operations.
Installation
npm install @origins-digital/concurrency-handlerFeatures
- Simple concurrency control function
- Automatic lock management
- TTL (Time To Live) configuration for locks
- Context-aware locking
Usage
Basic Usage
The concurrentRequestsHandler function ensures that only one instance of an operation runs at a time:
import { concurrentRequestsHandler } from '@origins-digital/concurrency-handler';
async function updateUser(id: string, data: any) {
return concurrentRequestsHandler(
`user:${id}`,
async () => {
// This will only execute if no other instance is running
return userRepository.update(id, data);
},
30000, // Lock for 30 seconds (optional)
);
}Handler Parameters
The function accepts the following parameters:
concurrentRequestsHandler<T>(
keyOpts: string | Context | (() => string), // Lock key or function that generates the key
resolver: () => Promise<T>, // The operation to execute
timeoutMs?: number // Time to live in milliseconds for locks (defaults to 30 seconds)
): Promise<T>Response Format
The handler returns a promise that resolves to the original operation's result.
Error Handling
The package uses standard JavaScript Error for error handling in the following scenarios:
- When a lock cannot be acquired
- When the timeout is reached
- When invalid options are provided
Best Practices
- Always set appropriate timeout values for locks to prevent deadlocks
- Use meaningful key patterns that include unique identifiers
- Monitor lock statistics for performance optimization
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
