Part of the alepha package. Import from alepha/lock.
npm install alepha
Lock a resource for a certain period of time.
This module provides a memory implementation of the lock provider. You probably want to use an implementation like RedisLockProvider for distributed systems.
Primitives are functions that define and configure various aspects of your application. They follow the convention of starting with $ and return configured primitive instances.
For more details, see the Primitives documentation.
Creates a distributed lock primitive for ensuring single-instance execution across processes.
Prevents multiple instances of the same operation from running simultaneously, essential for maintaining data consistency and preventing race conditions in distributed applications.
Key Features
Common Use Cases
1class TaskService { 2 // Basic scheduled task - only one server executes 3 dailyReport = $lock({ 4 handler: async () => { 5 const report = await this.generateDailyReport(); 6 await this.sendReportToManagement(report); 7 } 8 }); 9 10 // Migration with wait - all instances wait for completion11 migration = $lock({12 wait: true,13 maxDuration: [10, "minutes"],14 handler: async (version: string) => {15 await this.runMigrationScripts(version);16 }17 });18 19 // Dynamic lock keys for per-resource locking20 processFile = $lock({21 name: (fileId: string) => `file-processing:${fileId}`,22 gracePeriod: [5, "minutes"],23 handler: async (fileId: string) => {24 await this.processFileData(fileId);25 }26 });27}
Providers are classes that encapsulate specific functionality and can be injected into your application. They handle initialization, configuration, and lifecycle management.
For more details, see the Providers documentation.
A simple in-memory store provider.