How do I prevent deadlocks when acquiring multiple Web Locks?
Use a consistent acquisition order for multiple Web Locks. The example tests an application-owned ordering wrapper; verify native browser scheduling separately.
Web Locks are designed for coordination across same-origin tabs and workers, but that does not automatically make multi-resource code safe. If one context grabs resource A and waits for B while another grabs B and waits for A, the browser can faithfully queue both requests and still leave the application stuck. The fix is not to abandon Web Locks; it is to treat lock ordering as part of the application contract.
This article uses a small deterministic fixture to show the failure pattern, then repairs it by sorting named resources into one global order and keeping the protected work inside the LockManager.request() callback chain. Along the way, it explains exclusive and shared requests, the callback release boundary, and how ifAvailable and signal change waiting behavior without solving ordering for you.
The failure is circular wait, not missing mutual exclusion
The deadlock problem appears only after an application starts coordinating more than one named resource with the Web Locks API. One tab or worker holds lock A and waits for lock B, while another holds B and waits for A. Neither request can be granted because each callback is waiting on the other callback to finish. That is the classic circular-wait condition, and the browser is doing exactly what the API says it should do: queue requests by name and release each lock only when its callback returns.
That matters because Web Locks already gives you origin-wide mutual exclusion, including across tabs and workers, but it does not invent a resource ordering for you. If your code acquires one lock and then requests another inside the first callback, you have turned a single lock into a dependency graph. The browser can serialize a single name, but it cannot infer which of your named resources should come first. When the graph cycles, progress stops even though the browser itself is healthy.
The right mental model is not “Web Locks are flaky.” It is “the application owns the order in which it asks for independent resources.” Once you accept that, the fix becomes a design rule rather than a workaround. The implementation in this article chooses a single lexical order for resource names and refuses duplicate names, because the same named lock should never be treated as two separate acquisitions in the same operation.
// This is an application-owned ordering wrapper. It does not emulate or prove
// browser Web Locks scheduling; run the same calls in same-origin browser tabs
// or workers to verify real navigator.locks behavior.
/**
* Returns the one global order used by every multi-resource operation.
* Duplicate names are rejected: requesting the same named lock twice is not a
* second independent resource acquisition.
*/
export function orderedResourceNames(resources) {
if (!Array.isArray(resources) || resources.length === 0) {
throw new TypeError("resources must be a non-empty array");
}
const names = resources.map((name) => {
if (typeof name !== "string" || name.length === 0) {
throw new TypeError("every resource name must be a non-empty string");
}
return name;
});
const ordered = [...names].sort();
for (let index = 1; index < ordered.length; index += 1) {
if (ordered[index] === ordered[index - 1]) {
throw new RangeError(`duplicate resource name: ${ordered[index]}`);
}
}
return ordered;
}
/**
* Acquires named locks in lexical order and runs work while every callback is
* still active. Each LockManager.request() releases its lock when its callback
* returns, so the nested callbacks are the critical-section boundary.
*
* With { ifAvailable: true }, a null lock prevents work from running and the
* already-entered callbacks return, releasing any earlier locks.
*/
export async function withOrderedLocks(lockManager, resources, work, options = {}) {
if (!lockManager || typeof lockManager.request !== "function") {
throw new TypeError("lockManager must provide request()");
}
if (typeof work !== "function") {
throw new TypeError("work must be a function");
}
const names = orderedResourceNames(resources);
async function acquire(index, heldLocks) {
if (index === names.length) {
return { acquired: true, value: await work(heldLocks) };
}
return lockManager.request(names[index], options, async (lock) => {
// Native Web Locks supplies null for an unavailable ifAvailable request.
if (lock === null) return { acquired: false };
return acquire(index + 1, [...heldLocks, lock]);
});
}
return acquire(0, []);
}
SourcesMDN: Web Locks API (opens a new tab)MDN: LockManager.request() (opens a new tab)
A recording fixture checks the wrapper’s acquisition order
The supplied example is a unit fixture for the application-owned wrapper, not a two-context deadlock reproduction. It injects a recording lock manager whose request method records entry and exit and calls the supplied callback. There are no tabs, workers, competing browser queues or native navigator.locks calls in this test suite. The browser scenario explains why an acquisition order matters; the fixture checks that this particular wrapper follows that rule. Keeping those two kinds of evidence separate prevents a passing Node test from being mistaken for a measurement of browser scheduling.
In the success case, the caller supplies settings before accounts. The wrapper sorts the names before requesting either one. The test checks that work receives accounts and then settings, and that both callback-entry events have already been recorded when work runs. After the operation returns, it checks the reverse callback-exit order. These assertions exercise the implementation’s recursive await and return structure. They establish the application’s ordering and callback nesting, without claiming that the recording dependency implements the browser’s contention or release algorithm.
The unavailable-lock test supplies null for settings after the accounts callback has been entered. It checks that the wrapper returns acquired: false, does not run the protected work, and allows the recording callbacks to return. A separate test rejects duplicate resource names. Those are useful failure policies owned by the application. MDN documents the native ifAvailable convention; the test supplies that input explicitly to verify the wrapper’s response. A real cross-context integration check would still need same-origin secure-context tabs or workers using navigator.locks, and that integration check is not part of the supplied example.
Prevent cycles by making every multi-lock operation ask in one global order
The smallest safe repair is to sort the requested resource names and acquire them in that order every time. A stable global order removes the possibility of a cycle because every participant makes the same first choice. If every operation requests accounts before settings, then no operation can ever hold settings while waiting for accounts, because settings is never allowed to come first in that same code path.
That is why the example exposes an application-owned helper that returns orderedResourceNames() and rejects duplicates. Sorting is not a cosmetic choice. It is the contract that prevents two same-origin contexts from choosing opposite lock acquisition paths. Duplicate names are rejected because asking for the same named lock twice is not a second resource acquisition; it is a signal that the caller has modeled the work incorrectly. Requiring one order also keeps the repair visible in the call site instead of hiding it in an incidental implementation detail.
This approach is intentionally narrower than “never nest locks.” Nested requests are still possible, but only if they follow the same order everywhere. That is important when the protected work really does need more than one browser-coordinated resource. The article’s helper keeps the code honest by sorting the names before any request happens and by running the work only after every lock callback in the chain has been entered.
SourcesMDN: Web Locks API (opens a new tab)MDN: LockManager.request() (opens a new tab)
Keep the critical section inside the request callback
The callback boundary is the most important part of the API contract. MDN is explicit that the lock is released when the callback returns, and that an async callback keeps the lock until its promise settles. That means the callback is not just a notification that the lock exists; it is the ownership boundary for the critical section. If work that depends on the lock runs after the callback finishes, the browser is free to grant the same named lock to someone else.
The implementation in this article keeps the useful work inside the nested callback chain by returning the next acquisition from each request callback. That ensures the earlier lock is still held while the later one is acquired, and it ensures the actual work runs only after all required resources have been acquired. This is the point where many incomplete fixes fail: they ask for the first lock, queue the second request, and then perform the state update after one callback has already returned. That breaks the single ownership story and reintroduces the race you were trying to eliminate.
The helper also returns the held locks to the work function, which makes the ownership explicit in the application code. The work receives the acquired locks in order, and it can only run if every request succeeded. That shape is useful because it avoids pretending that the lock manager knows what the application intends to protect. It only knows whether a named lock has been granted; the application still decides what counts as the protected operation.
Read the tests as a boundary check, not as a browser scheduler claim
The provided Node tests prove three useful things. First, they prove that the helper sorts names into one order before any request is made. Second, they prove that the work function receives the acquired locks only after the nested callbacks have been entered. Third, they prove that the ifAvailable path can unwind without running the work. Those are exactly the application-owned rules that prevent the deadlock pattern from being encoded into the codebase.
What the tests do not prove is live browser scheduling across tabs and workers. They use a recording lock manager so the sequence is deterministic and inspectable under Node. That is an appropriate unit boundary because the article’s fix is about the application’s ordering and callback discipline, not about implementing the browser’s queue. To verify browser behavior itself, run the same acquisition pattern in a secure-context page or worker and observe the cross-context coordination described in the MDN docs.
There are two practical limits worth keeping in view. One is that this pattern only solves deadlocks caused by your own named Web Locks; it does not help if the protected operation itself can hang or if some other shared resource is involved. The other is that ifAvailable and signal are not substitutes for order. They are guardrails around waiting, not a different way to make opposite-order acquisitions safe. The useful rule is still simple: choose one order, keep the critical section inside the callback, and make bounded waiting an explicit choice rather than an accident.
import test from "node:test";
import assert from "node:assert/strict";
import { orderedResourceNames, withOrderedLocks } from "./main.mjs";
function recordingLockManager(unavailableName) {
const events = [];
return {
events,
async request(name, options, callback) {
events.push(["enter", name, options.mode ?? "exclusive"]);
const result = await callback(name === unavailableName ? null : { name });
events.push(["exit", name]);
return result;
},
};
}
test("withOrderedLocks uses one order and keeps work inside all lock callbacks", async () => {
const locks = recordingLockManager();
const result = await withOrderedLocks(
locks,
["settings", "accounts"],
async (held) => {
assert.deepEqual(held.map((lock) => lock.name), ["accounts", "settings"]);
assert.deepEqual(locks.events, [
["enter", "accounts", "exclusive"],
["enter", "settings", "exclusive"],
]);
return "updated";
},
{ mode: "exclusive" },
);
assert.deepEqual(result, { acquired: true, value: "updated" });
assert.deepEqual(locks.events, [
["enter", "accounts", "exclusive"],
["enter", "settings", "exclusive"],
["exit", "settings"],
["exit", "accounts"],
]);
});
test("orderedResourceNames rejects duplicate resources instead of nesting one lock twice", () => {
assert.throws(
() => orderedResourceNames(["accounts", "accounts"]),
{ name: "RangeError", message: "duplicate resource name: accounts" },
);
});
test("ifAvailable path skips work and unwinds earlier callbacks when a later lock is unavailable", async () => {
const locks = recordingLockManager("settings");
let workRan = false;
const result = await withOrderedLocks(
locks,
["settings", "accounts"],
async () => {
workRan = true;
},
{ ifAvailable: true },
);
assert.deepEqual(result, { acquired: false });
assert.equal(workRan, false);
assert.deepEqual(locks.events, [
["enter", "accounts", "exclusive"],
["enter", "settings", "exclusive"],
["exit", "settings"],
["exit", "accounts"],
]);
});
SourcesMDN: Web Locks API (opens a new tab)MDN: LockManager.request() (opens a new tab)


