alepha@docs:~/docs/packages/alepha/lock$
cat core.md
2 min read
Last commit:

#Alepha - Lock

#Installation

Part of the alepha package. Import from alepha/lock.

npm install alepha

#Overview

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.

#API Reference

#Primitives

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.

#$lock()

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

  • Distributed coordination across multiple processes, servers, and containers
  • Automatic expiration to prevent deadlocks
  • Configurable wait behavior (blocking vs. non-blocking)
  • Optional grace periods for lock extension after completion
  • Dynamic or static lock keys for fine-grained control

Common Use Cases

  • Database migrations and scheduled jobs
  • File processing and batch operations
  • Critical section protection and resource initialization
ts
 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

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.

#MemoryLockProvider

A simple in-memory store provider.

On This Page
No headings found...
ready
mainTypeScript
UTF-8packages_alepha_lock_core.md