Keyed Mutex for Per-Key Serialization

Serialize asynchronous work per string key while allowing different keys to run concurrently, with idle lock cleanup.

TypescriptResilience

Code

typescriptsnippet
32 lines
export class KeyedMutex {
  private readonly tails = new Map<string, Promise<void>>();

  async run<T>(key: string, task: () => Promise<T>): Promise<T> {
    if (typeof key !== "string" || key.length === 0) {
      throw new TypeError("key must be a non-empty string");
    }
    if (typeof task !== "function") throw new TypeError("task must be a function");
    const previous = this.tails.get(key) ?? Promise.resolve();
    let release: () => void = () => {};
    const current = new Promise<void>((resolve) => {
      release = resolve;
    });
    const tail = previous.then(() => current);
    this.tails.set(key, tail);
    await previous;
    try {
      return await task();
    } finally {
      release();
      if (this.tails.get(key) === tail) this.tails.delete(key);
    }
  }

  isLocked(key: string): boolean {
    return this.tails.has(key);
  }

  get size(): number {
    return this.tails.size;
  }
}

Inside the snippet

Keyed Mutex for Per-Key Serialization is built around the class KeyedMutex.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. TypeError is the guard’s signal — thrown at the branch, before any partial work happens.

What to watch for

  • The guard typeof key !== "string" || key.length === 0 short-circuits the flow with an early throw when its condition holds.

Using it

Import KeyedMutex from the file and call it — the rest of the code is implementation detail.

Key statements

private readonly tails = new Map<string, Promise<void>>();
const previous = this.tails.get(key) ?? Promise.resolve();
const current = new Promise<void>((resolve) => {
release = resolve;
});

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed.