Keyed Async Locks Serialize Same Keys
Keep one tail promise per key so same-key tasks serialize while different keys run concurrently; failures never poison the chain and idle keys clean up.
Code
// Keyed async locks: one tail promise per key. Same-key callers queue
// behind the previous holder; different keys never wait on each other.
class KeyedLocks {
#tails = new Map();
get size() {
return this.#tails.size;
}
runExclusive(key, task) {
const previous = this.#tails.get(key) ?? Promise.resolve();
const run = previous.then(() => task());
// The stored tail swallows rejections so one failing holder
// cannot poison the next waiter on the same key
const tail = run.catch(() => {});
this.#tails.set(key, tail);
tail.then(() => {
if (this.#tails.get(key) === tail) this.#tails.delete(key);
});
return run;
}
}
const locks = new KeyedLocks();
const order = [];
function hold(key, ms, label) {
return locks.runExclusive(key, async () => {
order.push(`${label} start`);
await new Promise((resolve) => setTimeout(resolve, ms));
order.push(`${label} end`);
});
}
async function main() {
await Promise.all([
hold('account:42', 30, 'a1'),
hold('account:42', 10, 'a2'),
hold('account:7', 10, 'b1'),
]);
// Let settlement bookkeeping microtasks finish before reading size
await new Promise((resolve) => setTimeout(resolve, 0));
for (const line of order) console.log(line);
console.log('idle keys left:', locks.size);
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
a1 start
b1 start
b1 end
a1 end
a2 start
a2 end
idle keys left: 0How the snippet works
Keyed Async Locks Serialize Same Keys comes down to the class KeyedLocks and the functions hold and main.
Iteration happens inside for (const line of order) console.log(line); — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Watch out for
- No third-party code is loaded at any point while this runs.
Applying it
The main signature, verbatim, is function hold(key, ms, label)
The demo output is labeled (idle keys left:), so the printed lines read as a trace of the operations that ran.
There are 1 call inside main — hold — executed top to bottom.
Statements that carry the weight
await new Promise((resolve) => setTimeout(resolve, ms));
await new Promise((resolve) => setTimeout(resolve, 0));
const previous = this.#tails.get(key) ?? Promise.resolve();
Interactive Tools for This Topic
FAQ
- What does Keyed Async Locks Serialize Same Keys print when run?
- Run it as a complete program — the output lines carry labels such as `idle keys left:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.