Skip to content

processLock

Keyed mutual exclusion across the main thread and its worker threads.

withProcessLock serializes callbacks that share a key: one runs at a time, the rest queue in arrival order, and different keys proceed concurrently. Unlike a plain in-module Promise chain, the queue is shared by every thread wired up through processLockWorkerOptions, so a worker pool cannot run two callbacks for the same key at once.

The name says process: this coordinates the THREADS of one Node process. It is not cross-process and not cross-host - a second node invocation, or a second app replica, has its own coordinator and shares nothing. When the scope is a deployment rather than a process, use @dbx-tools/postgres’s withAdvisoryLock, which puts the arbiter in PostgreSQL where every replica can see it.

The main thread owns the only coordinator. Each participating thread gets one MessagePort to it, and a lock is granted by a message back over that port. Consequently:

  • the lock is ADVISORY, like Postgres advisory locks - it protects a critical section only insofar as every writer takes the same key;
  • fairness is FIFO per key, since the coordinator queues waiters in the order their requests arrive;
  • a thread that dies while holding a lock releases it, because its port closing is what hands the key to the next waiter (see LockCoordinator.removePort).