Worker Mastery 4: Mutexes, recovery, and production
Protect a complete summary invariant, understand the limits of synchronization, and ship a worker engine with bounded failure and honest performance measurements.
Local Orders Lab can now partition work across workers and coordinate through atomic control words. Suppose a live summary stores both paid-order count and revenue. A display that reads count after one update and revenue before the other can show an average that never existed. Making each update atomic does not make the pair one indivisible operation. We need a protocol that protects the relationship between fields.
A mutex provides mutual exclusion: one participant enters a protected critical section at a time. It does not place a physical fence around the bytes. Every participant, including readers that require a coherent snapshot, must honor the same protocol. The MDN coordination guideexplains this distinction and develops locks, semaphores, and deadlock examples.
Key Insight
The production default for our aggregate remains local partials followed by a merge. The mutex lab deliberately introduces shared mutable summary state so we can learn when a multi-field invariant needs protection and what that protection costs.
Read Part 3 before this lesson. We will use its compare-and-swap, conditional waiting, and publication ideas. After this chapter, continue with WebAssembly Masteryto add a real compiled library without confusing native code with automatic threading.
1. Define exactly what the lock protects
Each worker computes a batch summary locally. Only the final addition to the shared pair is protected. If a batch contains two paid orders totaling 3,799 cents, the transition is from one coherent pair to another: count increases by two and revenue by 3,799 together. A snapshot reader may see the pair before or after that transition, but it must not observe half of it.
The following teaching layout uses 8 bytes for two integer control words and 16 bytes for two floating-point storage slots. The numeric slots still contain integer counts and cents within JavaScript's safe integer range. We use a lock because ordinary access to a Float64Array is not an atomic multi-field transaction.
summary-layout.js
export const LOCK = 0;
export const CANCEL = 1;
export function createSummaryState() {
const buffer = new SharedArrayBuffer(24);
const control = new Int32Array(buffer, 0, 2);
const totals = new Float64Array(buffer, 8, 2);
return { buffer, control, totals };
}
Offset 8 is correctly aligned for a 64-bit view. Both views share the allocation but refer to nonoverlapping regions. Newly allocated bytes start at zero: the lock is initially free, cancellation is off, and both totals are zero. Publish this state before starting workers and never reset it while old workers might still access it. See the SharedArrayBuffer constructorand typed-array reference.
Note
The live stress lab uses a more compact Int32 control layout for its repeated 1,299-cent orders. Its maximum four workers times 100,000 updates produce 519,600,000 cents, which fits that layout. The separate Float64 payload above demonstrates how the same mutex protects integer totals with a larger safe range. Do not swap these layouts without updating every participant's views and offsets.
2. Acquire with compare-and-swap, sleep on contention
Zero means unlocked and one means locked. A worker atomically changes zero to one. If the previous value was zero, it owns the lock. Otherwise it waits while the word still contains one, then retries. Waking does not grant ownership; the next successful compare-and-swap does. A deadline bounds a stuck wait, and a cancellation flag allows cooperative exit.
mutex.js
import { LOCK, CANCEL } from "./summary-layout.js";
export function lock(control, timeoutMs = 2000) {
const deadline = performance.now() + timeoutMs;
for (;;) {
if (Atomics.load(control, CANCEL) !== 0) {
throw new DOMException("Run cancelled", "AbortError");
}
if (Atomics.compareExchange(control, LOCK, 0, 1) === 0) return;
const remaining = deadline - performance.now();
if (remaining <= 0) throw new Error("Lock deadline exceeded");
Atomics.wait(control, LOCK, 1, Math.min(remaining, 50));
}
}
export function unlock(control) {
Atomics.store(control, LOCK, 0);
Atomics.notify(control, LOCK, 1);
}
export function requestCancellation(control) {
Atomics.store(control, CANCEL, 1);
Atomics.notify(control, LOCK);
}
The short timed waits make cancellation checks possible even if a notification occurs before a worker actually sleeps. Releasing stores the free state before notifying a waiter. A new contender might acquire the lock before that waiter is scheduled, which is why the loop matters. This lock is intentionally small and worker-only: Atomics.wait cannot block a browser window. See waitand notify.
Worker A
Ready to acquire
+1 order, +1299 cents
Worker B
Ready to acquire
+1 order, +2500 cents
Lock ownerNone
Count0
Sum in cents0
The committed pair can be read after acquiring the free lock.
Both workers are ready.
A mutex protects one combined updateEach worker changes count and sum under the same lock. Any reader requiring a consistent pair must acquire that lock too. Notification wakes a waiter; the waiter must still retry acquisition.
The diagram uses two explanatory paid records, 1,299 and 2,500 cents, whose combined pair is count 2 and revenue 3,799. Waiting and owning are distinct states. A worker can be awake without owning the critical section. The protected data is accessible only during ownership, and release transfers no payload by itself. It permits another participant to acquire and inspect a coherent state.
Warning
This mutex does not track the owner's ID, support reentry, guarantee fairness, or recover a dead owner. Calling unlock from the wrong worker breaks the protocol. Calling lock again while already owning it waits on yourself. These are explicit limits of the teaching implementation, not browser guarantees.
Both functions run in workers. The UI asks a worker for a snapshot and renders the copied response. Alternatively, the UI can read the final values after every worker has acknowledged completion and no writer remains. It must not bypass the lock and directly poll the pair while writers are active. The lock only works if readers participate too.
Compute the expensive batch before acquiring the lock. Inside the critical section, validate the combined result and write the two fields. Do not perform fetches, wait for messages, render UI, or call arbitrary callbacks while holding it. An asynchronous suspension can keep everyone else waiting for a long time and complicate reentrancy. Short critical sections make both reasoning and throughput better.
A thrown JavaScript exception runs the finally block, which releases the lock. Abrupt termination does not. If a worker disappears between the two writes, releasing the lock from another context would expose a potentially inconsistent pair. Correct recovery needs to consider data validity, not merely clear a stuck integer.
4. Understand the other synchronization tools
Choose the primitive that matches the invariant
Primitive
What it coordinates
Orders Lab example
Atomic counter
One integer operation
Claim a unique chunk start
Mutex
One participant in a critical section
Update count and revenue together
Semaphore
A bounded number of available permits
Limit concurrent buffer users
Barrier
All required participants finish a phase
Complete a preprocessing phase before analysis
Condition protocol
Wait until protected state permits progress
Wait for a free queue slot
Message channel
Explicit ownership or completion messages
Send a completed batch result
A semaphore counts available permits; it does not identify which specific buffer a worker owns. Resource assignment still needs its own rule. A barrier also needs a failure rule: if one participant exits, the others cannot wait forever for its arrival. Our shared-input initialization happens before worker startup, so no runtime barrier is required for that phase. Avoid introducing a primitive when ownership already supplies the necessary ordering.
Conditions need a predicate and a wakeup protocol
A condition such as "the queue is not empty" is state, not an event. A consumer checks the predicate, waits, and rechecks after waking. If you release a mutex before sleeping, a producer could publish and notify in that gap. A version counter or a carefully designed expected-value wait prevents losing that transition. Holding the mutex while waiting for a producer that needs the same mutex deadlocks immediately.
A single-producer, single-consumer ring buffer can assign each cursor to one writer: the producer writes a payload slot before publishing its write cursor; the consumer reads it before publishing its read cursor. Capacity and wraparound rules prevent overwriting unread data. Multiple producers require a different reservation and publication protocol; incrementing a write cursor before the payload exists can expose an uninitialized slot. Treat that as a separate data-structure design task.
Safety is different from progress
Safety says bad states do not occur, such as two mutex owners or a half-written snapshot. Liveness says useful progress eventually occurs. Deadlock means participants wait in a cycle. Starvation means one participant keeps losing access. Livelock means participants keep acting without completing useful work. A lock can preserve the data invariant and still have a progress failure.
A lock-free algorithm aims for system-wide progress even when a particular contender retries. A wait-free algorithm bounds the steps needed by each operation under its model. Neither term means "there is an Atomics call" or "no mutex variable appears." ABA, where a value changes from A to B and back to A between observations, can defeat a compare-and-swap design that mistakes equality for unchanged history. Generation counters and safe reclamation require a full protocol, including counter wraparound.
JavaScript provides low-level atomic and waiting primitives, not a built-in general semaphore or robust owner-recovering mutex. The coordination guideand memory-model specificationare useful foundations for evaluating a library's stronger abstractions.
5. Plan for deadlock and a disappearing owner
A two-lock cycle and its prevention
Step
Worker A
Worker B
1
Acquires summary lock
Acquires export lock
2
Waits for export lock
Waits for summary lock
3
Cannot reach release
Cannot reach release
Prevention
Acquire summary before export
Acquire summary before export
A global lock order removes this particular cycle when every participant follows it. Better still, reduce the number of locks or avoid holding one while requesting another. Message protocols can deadlock too: A waits for B's reply while B waits for a message that A will send only after receiving that reply. Draw the dependency, not merely the list of API calls.
For Local Orders Lab, the recovery unit is a complete run. If a worker crashes, a lock deadline expires, or cancellation cannot finish cooperatively, the coordinator stops all workers in that generation, rejects the pending result, discards its shared state, and starts a new generation with fresh buffers when requested. Because the operation is pure analysis over retained or reproducible input, recomputation is a defensible recovery strategy.
Warning
Do not forcibly set the lock word to zero while another worker may still be inside the critical section. Two owners could then write at once. Do not reuse a buffer while any old worker might still hold a reference. Timeouts detect a failure to make progress; they do not prove that the previous owner has stopped or its data is consistent.
A robust application tracks run ID, worker ID, job ID, attempt, and terminal state. Accept one terminal transition per job. Resolve or reject every pending request when closing the engine. Progress from an old generation is ignored. This is also the right boundary for a React cleanup function: removing a component must not leave a detached coordinator mutating application state through late callbacks.
6. Inspect the protected-summary lab
The mutex playground uses repeated paid orders of 1,299 cents so every coherent snapshot has the invariant totalCents = count multiplied by 1,299. This focused fixture differs from the four-order, 8,798-cent fixture used elsewhere in the series. Inspect the final pair and compare it with a local reduction of these repeated orders. Cancel a run and start a fresh one, watching for a clean terminal state and a new result. The code in the embedded editor shows where the lock is acquired, released, and abandoned during whole-run teardown.
The source, controls, and measured output are in the playground below. Shared-memory modes need an isolated top-level page. Open the runnable lab in a separate tab.
Editable example loads when this section enters view.
Choose the injected owner-failure scenario to deliberately throw after acquiring the lock, before the protected cleanup block. The expected outcome is an error and whole-run teardown, not a successful total. Then select the normal scenario and run again. Fresh workers and fresh memory must make the previous abandoned lock irrelevant.
The control-plane diagram is a deterministic explanation of ownership. The playground executes real workers when the environment permits shared memory. Treat those as different evidence: the diagram helps reason about the protocol, while the live result exercises one execution in your browser. Neither a beautiful diagram nor one successful run proves every possible schedule correct.
7. Deploy the capability without breaking the rest of the app
Configure headers on the actual HTML response and compatible policies on worker and resource responses. A standalone isolated lab commonly begins with the following policy. This is a deployment example, not an instruction to apply it blindly to every route in an existing application.
Cross-origin resources fetched without CORS need an appropriate CORP policy under this COEP setting. Module imports and fetches need their own correct origin and CORS behavior. An iframe requires a compatible embedding chain and permissions policy; isolating only its own response is insufficient. COOP can also sever opener relationships that popup-based login flows rely on. Inspect those dependencies before changing a site's policy. See the isolation deployment guide.
Check CSP, origins, and resource URLs
The page's worker-src directive governs which worker URLs it can create. A blob-based editor preview needs a policy compatible with its execution design; fixed application workers can use same-origin files. A fetched worker script can have its own response CSP. Do not assume that a successful module import in the page proves the worker's dependency graph will load under its policy. See worker-srcand the worker CSP guide.
Inspect the Network panel for script status, content type, blocked resources, and final redirected URLs. Verify crossOriginIsolated both in the document and in the worker. Exercise the same check in the actual embedded playground, because a top-level test can succeed while the iframe environment differs.
Note
A separate top-level isolated lab can be appropriate when a host application cannot adopt the required embedding policy. Keep an explicit open-lab route and a working nonshared fallback. Do not describe a disabled shared-memory button as a working demonstration or silently replace its result with a simulation.
8. Measure the architecture and debug the failure boundary
Record cold startup, input preparation, bytes copied or transferred, queue delay, worker compute duration, merge duration, and time until the UI can display the answer. Separately measure interaction responsiveness. The end-to-end result matters more than an isolated inner-loop number. Use several runs with the same data, report variation, and include the one-worker baseline instead of presenting the fastest sample alone.
More workers can create memory pressure or compete for bandwidth. False sharing can occur when independent frequently written controls occupy the same hardware cache line; those controls need not be the same variable to interfere. Padding and batched updates are hypotheses to measure, not universal constants to copy from a tutorial. A long critical section serializes workers regardless of core count. Partitioning state often offers a larger benefit than making the lock implementation more clever.
Diagnose the layer that failed
Symptom
First questions
Useful evidence
No worker response
Did the script load? Did a handler install?
Network, error event, request deadline
SharedArrayBuffer unavailable
Is this context isolated? Is an ancestor blocking it?
Headers and capability checks in each context
Wrong totals
Are ranges duplicated, skipped, or misdecoded?
Tiny fixture, job IDs, baseline comparison
Cancel appears stuck
Is the worker computing or synchronously waiting?
Chunk boundaries, shared cancel flag, wake location
Workers slower than baseline
Is transfer, startup, contention, or merging dominant?
Separate phase timings and worker-count sweep
Name workers, attach IDs to logs, and inspect the worker's own execution context in developer tools. Keep clocks comparable: compute durations within one context, or normalize cross-context timestamps using performance.timeOrigin. Instrumentation should not post a message for every order, because the measurement itself can become the bottleneck.
9. Test invariants, schedules, and cleanup
The fixture gives a small independent oracle: three paid orders, 8,798 cents, and the known regional totals. Generate larger bounded inputs and compare each implementation to a straightforward single-thread reference. Change worker count, batch size, and completion order while preserving the same input. The answer must remain the same.
Cover zero rows, one row, an unpaid-only batch, a short final batch, and the maximum accepted input.
Force out-of-order responses and verify each batch contributes exactly once.
Cancel before startup, during computation, and during a wait; every promise must settle.
Inject a worker failure and a deadline expiry; discard that generation and verify a fresh run works.
Run the controlled lost-update schedule to expose the unsafe variant, then verify the atomic repair.
Read protected summaries while batches commit and assert the chosen pair invariant.
Exercise the nonisolated environment and verify the honest fallback and capability message.
These tests target behavior, not the implementation's spelling. Stress tests explore schedules but cannot prove the absence of every race. Combine them with a written ownership argument: immutable input, uniquely claimed ranges, local partials, protected snapshots, and no reuse while old owners exist. That argument also makes code review much more precise than asking whether the example "uses Atomics correctly."
Check your understanding
Why does finally not make this mutex recover from worker termination?
Finally handles control flow and exceptions while the JavaScript agent is running. Termination can stop it immediately, including halfway through a protected update. Our recovery discards the whole run after stopping all participants instead of trusting the abandoned data.
Which design would you choose for a final revenue report with no live shared snapshot?
Partition input, calculate local partials, and merge them. There is no need for a mutex around a result that each worker owns independently. The simplest protocol that satisfies the actual requirement is easier to validate and often faster.
Does WebAssembly make the mutex or worker architecture unnecessary?
No. A synchronous WebAssembly call occupies its calling agent. Shared memory still requires ownership and synchronization, and a compiled library must support the intended threading model. The next series applies those boundaries to an existing WebAssembly library rather than assuming compilation supplies parallelism.
Tip
Explain this project in an interview by following one order: how it is represented, which worker owns its processing, how its contribution is published once, how a reader obtains a consistent answer, and what happens if that worker dies. Each answer names a concrete invariant instead of merely listing concurrency vocabulary.