Understanding the Web Locks API: Concepts, Usage, and Risks
The article explains the concept of locks, introduces the Web Locks API for synchronizing resource access across scripts, details its request workflow, optional parameters, potential risks such as deadlocks, and notes browser compatibility, providing code examples for practical use.
What Are Locks?
As computers become more powerful and can run multiple CPU threads, concurrent access to shared resources can cause synchronization problems. A lock is a synchronization primitive that restricts concurrent access to a resource, optionally allowing multiple readers but preventing simultaneous writers.
What Is the Web Locks API?
The Web Locks API brings the concept of locks to web applications. It lets a script asynchronously hold a lock on a named resource until its work completes, preventing other scripts in the same origin from acquiring the same lock (except for a special shared‑lock case).
Execution Flow
Request a lock.
Perform work while the lock is held.
The lock is released automatically when the task finishes.
Other scripts may then request the lock.
If a lock is already held, subsequent requests are queued and granted in order when the lock is released.
Scope of Locks
Locks are scoped to the same origin; a lock obtained on example.com does not affect example.org .
Each user agent (browser profile) is treated as a separate agent, so even same‑origin tabs in different profiles do not share locks.
Incognito sessions are also isolated.
Scripts running in the same origin and same browsing context share the lock manager.
All same‑origin pages and workers that belong to the same user agent share the lock manager.
Why Coordinate Resources?
Simple web apps rarely need coordination, but complex applications that run in multiple tabs or workers and perform CRUD operations must keep state synchronized to avoid conflicts, such as duplicate stock trades or inconsistent document edits. Traditional communication APIs (SharedWorker, BroadcastChannel, localStorage, etc.) have drawbacks, making the standardized Web Locks API attractive.
Using the Web Locks API
The primary method is navigator.locks.request(name, options?, callback) . It takes three arguments:
name (string) – the resource identifier.
callback (function) – an async function that runs while the lock is held.
options (object, optional) – additional settings described below.
The method returns a promise that resolves with the callback’s return value. You can handle it with .then() / .catch() or await .
const requestForResource1 = async () => {
if (!navigator.locks) {
alert("Your browser does not support Web Locks API");
return;
}
try {
const result = await navigator.locks.request('resource_1', async lock => {
// lock acquired
await doSomethingHere();
await doSomethingElseHere();
// optional return value
return "ok";
// lock is released here
});
} catch (exception) {
console.log(exception);
}
};Optional Parameters
Mode
Two modes are supported:
exclusive (default) – only one holder.
shared – multiple holders may read simultaneously.
Signal
A signal (AbortSignal) can abort a pending request, useful for time‑outs.
const controller = new AbortController();
setTimeout(() => controller.abort(), 400); // wait at most 400 ms
try {
await navigator.locks.request('resource1', { signal: controller.signal }, async lock => {
await doSomethingHere();
});
} catch (ex) {
// ex is an AbortError if the timer fired
}ifAvailable
If true , the request succeeds only when the lock can be granted immediately; otherwise it returns null without queuing.
await navigator.locks.request('resource', { ifAvailable: true }, async lock => {
if (!lock) {
// lock not obtained – handle accordingly
return;
}
// lock obtained – proceed
});Risks of Using Locks
Deadlock
Deadlocks occur when multiple tasks wait on each other’s locks, halting progress. Avoid nested locks, enforce a consistent lock acquisition order, and consider using the signal option to time‑out requests.
Unresponsive Tabs
If a tab holding a lock becomes unresponsive, the lock can block other tabs. The optional steal flag (default false ) can force‑release existing locks, but should be used sparingly.
Debugging Difficulty
The lock manager’s state can be inspected via navigator.locks.query() , which returns the current held and pending locks. However, this snapshot reflects a moment in time and should not be used for making decisions that affect lock release.
Browser Compatibility
The Web Locks API is supported in modern Chromium‑based browsers; other browsers may lack support or require polyfills, which are no longer maintained.
Despite limited support, the API provides a standardized way to coordinate resource access in complex web applications, and developers should be aware of its usage and pitfalls.
Resources
MDN Docs – https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API
Web Locks Explainer – https://github.com/WICG/web-locks/blob/main/EXPLAINER.md
Demo – https://mahdhir.github.io/Web-Locks-API-demo/
Source Code – https://github.com/Mahdhir/Web-Locks-API-demo
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.