@upstash/lock
offers a distributed lock implementation using Upstash Redis.
NPM
npm install @upstash/lock
PNPM
pnpm add @upstash/lock
Bun
bun add @upstash/lock
To create the Redis instance, you can use the Redis.fromEnv()
method to use an Upstash Redis instance from environment variables. More options can be found here.
import { Lock } from '@upstash/lock';
import { Redis } from "@upstash/redis";
async function handleOperation() {
const lock = new Lock({
id: "unique-lock-id",
redis: Redis.fromEnv(),
});
if (await lock.acquire()) {
// Perform your critical section that requires mutual exclusion
await criticalSection();
await lock.release();
} else {
// handle lock acquisition failure
}
}
new Lock({
id: string,
redis: Redis, // ie. Redis.fromEnv(), new Redis({...})
lease?: number, // default: 10000 ms
retry?: {
attempts?: number, // default: 3
delay?: number, // default: 100 ms
},
})
Attempts to acquire the lock. Returns true
if the lock is acquired, false
otherwise.
You can pass a config
object to override the default lease
and retry
options.
async acquire(config?: LockAcquireConfig): Promise<boolean>
Attempts to release the lock. Returns true
if the lock is released, false
otherwise.
async release(): Promise<boolean>
Attempts to extend the lock lease. Returns true
if the lock lease is extended, false
otherwise.
async extend(amt: number): Promise<boolean>
Returns whether the lock is ACQUIRED
or FREE
.
async getStatus(): Promise<LockStatus>
Option | Default Value | Description |
---|---|---|
lease |
10000 |
The lease duration in milliseconds. After this expires, the lock will be released |
retry.attempts |
3 |
The number of attempts to acquire the lock. |
retry.delay |
100 |
The delay between attempts in milliseconds. |