Prerequisites: running in a secure context (HTTPS) and code that may run in multiple same‑origin contexts (two tabs, a tab + worker, or multiple workers). Familiarity with async/await and the principle of keeping critical sections short.
Implementation decision: Use navigator.locks.request() with a minimal critical section inside the callback. Choose mode: "exclusive" for single‑writer tasks (index rebuilds, migration markers, reconciliation) or "shared" for concurrent readers where writers must wait. Perform expensive validation and idempotent work before calling request(), then acquire the lock and perform only the unsafe mutations inside the callback. The server will insert the verified implementation example for the pattern.
Expected result: The browser enforces a named lock per origin. Exclusive callers run one at a time in queue order; shared callers can overlap with other shared holders but exclusive waiters run only after shared holders finish. ifAvailable returns null instead of waiting when the lock is busy; steal forces takeover (use with caution).
One limitation: The lock serializes ownership but does not provide transactional guarantees for durable writes. Your callback must still make durable progress and handle retries or reconciliation for partial results. Also, the shim and tests model queueing and ordering deterministically for development; they do not simulate browser crashes or process restarts. Use storage-level recovery if jobs can leave partial durable state.
Follow the pattern: prepare outside the lock, mutate inside it, and record progress so recovery is possible. The server will inject the working example showing the pattern and the shim used for deterministic tests.
Working example
class Deferred {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
function normalizeRequestArgs(optionsOrCallback, maybeCallback) {
if (typeof optionsOrCallback === 'function') {
return { options: {}, callback: optionsOrCallback };
}
return { options: optionsOrCallback ?? {}, callback: maybeCallback };
}
export function createInMemoryLockManager() {
const state = new Map();
let nextToken = 1;
function getEntry(name) {
if (!state.has(name)) {
state.set(name, { holders: [], queue: [] });
}
return state.get(name);
}
function canGrant(entry, mode) {
if (entry.holders.length === 0) return true;
if (mode === 'shared' && entry.holders.every((h) => h.mode === 'shared')) return true;
return false;
}
function scheduleFlush(name) {
queueMicrotask(() => flush(name));
}
function grant(entry, name, request) {
entry.holders.push({ token: request.token, mode: request.mode });
const finish = async () => {
try {
const result = await request.callback({ name, mode: request.mode });
request.deferred.resolve(result);
} catch (error) {
request.deferred.reject(error);
} finally {
entry.holders = entry.holders.filter((holder) => holder.token !== request.token);
scheduleFlush(name);
}
};
finish();
}
function flush(name) {
const entry = getEntry(name);
while (entry.queue.length > 0 && canGrant(entry, entry.queue[0].mode)) {
const request = entry.queue.shift();
grant(entry, name, request);
if (request.mode === 'exclusive') break;
}
}
async function request(name, optionsOrCallback, maybeCallback) {
const { options, callback } = normalizeRequestArgs(optionsOrCallback, maybeCallback);
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
const mode = options.mode ?? 'exclusive';
const ifAvailable = Boolean(options.ifAvailable);
const steal = Boolean(options.steal);
if (ifAvailable && steal) {
throw new Error('NotSupportedError: ifAvailable and steal cannot both be true');
}
if (mode !== 'exclusive' && mode !== 'shared') {
throw new Error('mode must be "exclusive" or "shared"');
}
const entry = getEntry(name);
const token = nextToken++;
if (steal) {
entry.holders.length = 0;
entry.queue.length = 0;
}
if (ifAvailable && !canGrant(entry, mode)) {
return callback(null);
}
if (canGrant(entry, mode)) {
const deferred = new Deferred();
const requestRecord = { token, mode, callback, deferred };
grant(entry, name, requestRecord);
return deferred.promise;
}
const deferred = new Deferred();
entry.queue.push({ token, mode, callback, deferred });
return deferred.promise;
}
return { request };
}
export async function runExclusiveTask(lockManager, lockName, work) {
return lockManager.request(lockName, { mode: 'exclusive' }, async (lock) => work(lock));
}
export async function runSharedTask(lockManager, lockName, work) {
return lockManager.request(lockName, { mode: 'shared' }, async (lock) => work(lock));
}
export { Deferred };
Read the full article: https://chriseugenerodriguez.com/blog/when-to-use-lockmanager-request-across-tabs