⚡ Web Locks Deadlocks: Global Lock Order Now (API)11 min read2,113 words

⚡ Web Locks Deadlocks: Global Lock Order Now (API)

Avoid Web Locks deadlocks with the Web Locks API: use multiple lock ordering, nested async patterns, fail-fast handling, and Web Locks testing for safer JS apps.

Web Locks deadlocksWeb Locks APImultiple Web LocksJavaScript lock orderingWeb Locks testing
⚡ Web Locks Deadlocks: Global Lock Order Now (API)

A Practical Pattern for Acquiring Multiple Web Locks Safely

When a browser app needs to update several shared resources, taking a Web Lock for each one can feel like the obvious way to avoid conflicts. The catch is that locking one resource doesn't automatically protect you from deadlocks that involve multiple resources.

If one tab holds settings while it waits for accounts, and another holds accounts while it waits for settings, neither side can move forward.

The fix isn't a special browser scheduling feature. It's an application-level rule: whenever an operation needs more than one lock, it must request them in the same global order every time. That only works if the lock stays held for the entire critical section - including any asynchronous work - and if every code path follows the rule. This guide explains how the deadlock happens, shows an ordered-lock wrapper, and covers what deterministic tests can (and can't) tell you about native browser behavior.

Why can multiple Web Locks deadlock?

A Web Lock coordinates access to a named resource. Within the same origin, tabs and workers can request the same name and avoid running conflicting critical sections at the same time. That covers contention for one resource.

It doesn't automatically prevent a deadlock cycle when a single operation needs two (or more) resources.

Take these two operations, both of which need accounts and settings:

  1. Context A acquires settings, then requests accounts.
  2. Context B acquires accounts, then requests settings.
  3. Each request waits for a lock held by the other context.

Both operations get stuck. The callback for the first lock doesn't finish, so that lock remains held while the code waits for the next request. The cycle is the key problem: A waits for B, and B waits for A. More retries - or even different lock names - won't fix the dependency.

Why single-resource safety is not enough

It's easy to audit each lock request in isolation and think "this is safe." You might be right for any single request, because the browser won't run two exclusive critical sections for the same lock name at the same time.

But deadlock is about the full acquisition graph. If two different code paths can take the same set of locks in different orders, each path can look locally correct while the system still can't make progress.

In practice, this often shows up as a hang rather than an error. A tab may wait indefinitely, a user action may never finish, or a background task may stop doing useful work. The browser can't guess the resource order your app intends, and it won't "reorder" your requests to save you.

A useful mental model

Treat each multi-lock operation like a transaction: it needs to collect all required resources first, then run the protected work. Every caller that participates in the transaction has to follow the same rule for collecting those resources. If one caller follows the rule and another manually requests locks in a different order, the deadlock path still exists.

So the practical consequence is simple: lock ordering has to be centralized, documented, and used consistently. Fixing only the one place where the hang first showed up usually isn't enough - check every spot that can acquire multiple lock names, including error handling and background flows.

How does a global lock order prevent deadlocks?

Pick one deterministic order for resource names, and require every multi-resource operation to acquire locks in that order. A lexical sort works: if an operation receives settings and accounts in either input order, it requests accounts first and then settings.

This removes the "circular wait" edge. If two contexts need the same set, they can't both end up holding different "first" locks while waiting for each other's "second" lock. One side may wait - but it won't be holding a lock that the other side needs to reach the same point in the sequence. The point isn't that everything runs immediately; it's that you eliminate this particular deadlock pattern by constraining acquisition order.

Make the rule an API, not a convention

A comment like "acquire alphabetically" gets missed. Instead, write a small application-owned wrapper that:

  • accepts the resource set,
  • validates it,
  • sorts it, and
  • owns the nested request() calls.

Then callers can't accidentally pick their own ordering unless they bypass the wrapper.

Before acquiring anything, validate the complete input:

  • require a non-empty array of non-empty string names,
  • sort a copy (so you don't mutate the caller's array),
  • reject duplicates (so you don't request the same named lock twice),
  • use one naming convention across the app.

This last part matters. Sorting only works if everyone means the same thing by a "resource name." For example, Accounts and accounts are different strings. If your product treats them as the same resource, canonicalize names before they reach the wrapper. Don't rely on ad hoc trimming/case folding in just one caller; define the naming rule in one place.

Be precise about what sorting means

Sorting is an application contract, not a scheduling hint to the browser. The browser still decides when requests are granted based on its native Web Locks behavior. Your code is only making sure every participant asks for locks in a consistent sequence.

Lexical ordering is appealing because it's deterministic and easy to inspect. A domain-specific order can also work, but it needs the same properties: it must cover every lock name that can appear in a combined operation, and every caller must use it. If the ordering function ever changes, treat that like a concurrency behavior change and re-test all multi-resource paths.

There's a trade-off: a global order can feel a little awkward when a workflow naturally thinks "do this resource first." Usually that's worth it. Explicit ordering is easier to reason about than intermittent hangs. If your resource relationships get complex, keep the order function in one place and test it, rather than letting each feature invent its own preference.

How do you hold multiple Web Locks safely across async work?

The wrapper has to preserve lock ownership while it acquires the full set and runs the protected work.

With Web Locks, a named lock stays held for the duration of its request() callback. For an asynchronous callback, that means the lock remains held until the callback's returned promise settles.

To make that lifetime clear, nest the callbacks:

  • request the first lock,
  • from inside that callback request the next lock,
  • keep going until all locks are granted,
  • then call the protected work.

The protected work runs while the nested callbacks are still active. When the work finishes (or throws), the promises settle and the locks are released as the call stack unwinds.

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;

}

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) => {

if (lock === null) return { acquired: false };

return acquire(index + 1, [...heldLocks, lock]);

});

}

return acquire(0, []);

}

Understand the failure and cancellation paths

With { ifAvailable: true }, a request doesn't wait for an unavailable lock. The callback receives null for that request. In this wrapper, that returns { acquired: false } without running the protected work. Then the earlier callbacks also return, releasing whatever locks were already acquired. That's a fail-fast path, not a retry strategy. Decide at the call site whether you want to show a conflict, try again later, or take some other action.

An abort signal is different: it lets a caller stop waiting when cancellation is requested. That can prevent wasted waiting when a user navigates away or a task becomes irrelevant - but it doesn't make opposite-order acquisition safe. Similarly, ifAvailable can avoid waiting for one request, but it doesn't replace a global order for operations that do wait.

Also separate the "ordering" problem from the "shared vs exclusive" choice. Use shared mode when multiple readers can run together, and exclusive mode when a writer needs sole access. Shared locks don't make inconsistent multi-lock order harmless, and an exclusive lock isn't a stand-in for releasing locks at the correct callback boundary.

How should you test lock ordering and browser behavior?

Separate two questions:

  1. Does your wrapper implement the application contract?
  2. Does the browser behave in a way that matches what your app assumes across real contexts?

A deterministic recording fixture is great for the first question. It can record which names were requested, when callbacks were entered/exited, and then verify sorting, duplicate rejection, and whether work runs only after the full lock chain is in place.

It can also test fail-fast unwinding. For example: make an early request succeed, then make a later request return null. Assert that work was never called and that the earlier callback returned. You should also test a failure in work itself, so the wrapper doesn't swallow errors and the request() callbacks still settle properly. These tests are fast and repeatable because the fixture controls its own behavior.

What a fixture cannot prove

A fake lock manager isn't a browser scheduler. It can't tell you how native Web Locks requests are coordinated across tabs or workers, how contention behaves in a specific browser, or whether your test setup truly matches the origin and execution conditions your app runs under.

So fixture tests can establish that your wrapper follows the logic you wrote. They don't establish native cross-context concurrency behavior.

Verify native behavior separately in a real browser using multiple same-origin tabs or workers in a secure context. A practical test should coordinate two operations that request the same resource set in opposite input orders, then record which locks are held and confirm that both calls end up using the same sorted acquisition sequence. Include a contention case plus the cancellation or fail-fast paths your product actually uses.

A review checklist

Before shipping a multi-resource lock path, check:

  • every multi-resource caller uses the same wrapper and naming rule,
  • names are validated and duplicates fail before any request() is made,
  • the protected work runs before the nested request callbacks return,
  • errors from work stay observable to the caller,
  • shared vs exclusive mode matches the data operation (not convenience),
  • ifAvailable and abort behavior are handled explicitly (not treated as deadlock prevention),
  • unit tests cover wrapper logic, and a real-browser test covers native cross-context behavior.

Keep these two kinds of evidence separate in your test reports. That way, if something breaks, you can tell whether it's a sorting regression in your code or a discrepancy in browser-level contention behavior.

Conclusion

Multiple Web Locks need an application-level acquisition rule. Validate resource names, reject duplicates, sort deterministically, and route every multi-resource operation through the same wrapper. Keep the protected work inside the nested request callbacks so the locks remain owned until the work settles.

Treat fail-fast options and cancellation as tools for managing waiting, not as substitutes for consistent ordering. Then test the wrapper with a deterministic fixture, and verify native coordination in real same-origin browser contexts. Keeping that split clear gives you useful evidence for both your code and the browser behavior it depends on.

Frequently Asked Questions

No. It prevents circular wait caused by acquiring the same named resources in inconsistent orders, provided every multi-resource caller follows the rule. Other deadlock causes, such as waiting on unrelated work while holding a lock, still need to be considered in the broader design.
No. It changes an unavailable request into a fail-fast result instead of waiting. That can help a caller avoid blocking, but it does not make inconsistent acquisition order safe for requests that do wait. Use one global order regardless of this option.
A lock is held for the lifetime of its request callback. Nesting requests keeps earlier locks owned while later locks are acquired and while the protected work runs. Starting dependent work after an outer callback has returned would release that earlier lock too soon.
No. A deterministic fixture can verify your wrapper's ordering, validation, and unwind logic. It cannot reproduce native coordination across tabs and workers. Test those behaviors separately in real same-origin browser contexts under the conditions your application supports.

Related articles