Pular para o conteúdo
Português (BR)

acquireLock

Este conteúdo não está disponível em sua língua ainda.

acquireLock(cache, key, ttlMs): Promise<Option<CacheLock>>

Defined in: src/cache/CacheLock.ts:97

Take a mutually-exclusive lock on key, held for at most ttlMs.

A thin, honest wrapper over Cache.setIfAbsent — that method is already atomic on every backend, so this adds no exclusion the cache did not have. What it adds is the release half, which callers otherwise write themselves and usually write wrong: a random token is stored as the value, and release deletes the key only if that token is still the one there.

const lock = await acquireLock(cache, 'lock:nightly-report', 30_000);
if (lock.isNone()) return; // someone else is on it
try {
await generateReport();
} finally {
await lock.value.release();
}

ttlMs is required, deliberately. The lock’s only recovery path from a holder that crashed, stalled past its deadline, or lost the network is expiry; an infinite lock is a lock that wedges forever the first time a process dies at the wrong moment. Size it above the realistic worst-case duration of the critical section — too short and the TTL lapses mid-work, which is precisely the case release reports as false.

What this is not. The compare-and-delete in release is a get followed by a delete, not one atomic step — the Cache surface has no compare-and-delete primitive, and adding one (a Redis Lua script) would not be implementable on Memcached at all. The residual window is narrow and strictly better than the alternative: an unconditional delete is wrong for the entire span after the TTL lapses, whereas this is wrong only if the lock lapses and is re-acquired in the gap between our own get and delete. It is not a distributed-consensus lock either: correctness still rests on the backend being a single logical keyspace, and on clocks not drifting far enough to make a TTL mean different things to different holders. For anything where two concurrent holders would be a correctness bug rather than wasted work, guard the resource with a fencing token and not with this.

Cache

string

number

Promise<Option<CacheLock>>

Some(lock) when the lock was taken, None when someone else holds it. Throws CacheError on a non-positive or non-finite ttlMs, matching every other TTL-taking method.