Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Worker thread
- An operating-system thread running its own JavaScript environment and event loop, created with new Worker.
- Structured clone
- The serialization rules used by workerData and postMessage. Supported ordinary object data is copied; functions cannot be cloned, and prototypes/accessors are not generally preserved. Shared memory is a separate case.
- Transfer
- Handing over an eligible ArrayBuffer through a transfer list, detaching the sender’s buffer and all its views. This changes ownership rather than retaining two independent buffers; physical implementation costs are not measured here.
- SharedArrayBuffer
- A backing memory region that can be shared across worker environments. Disjoint ranges avoid conflicting element accesses; overlapping communication needs a suitable Atomics protocol.
CPU work across JavaScript environments
An async function can suspend while waiting, but its synchronous JavaScript still occupies the thread running it. Parallel CPU work needs another execution thread. In Node, a worker runs a separate JavaScript environment, so moving a calculation also means deciding how its inputs and outputs cross that boundary.
The data design has three choices: copy supported values into an independent environment, transfer ownership of an eligible buffer, or deliberately share backing memory. These choices impose different ownership and coordination obligations. Starting workers alone establishes neither a useful division of work nor that every result is ready to read.
01Separate worlds
A worker is another JavaScript environment
A Node payments service stops answering health checks while it scores a batch of card transactions for fraud risk, and the load balancer takes it out of rotation. The team moves scoring to a worker. Now health checks pass, but the batch comes back unscored, and splitting it across four workers makes it worse. How does single-threaded JavaScript use several cores, and what actually reaches the other thread?
A Worker runs its script with a separate JavaScript global environment and event loop on another thread. With enough CPU resources, workers can execute JavaScript in parallel. Ordinary objects are not shared by reference across those environments. Messages serialize supported values; shared memory must be arranged explicitly.
02Copy, transfer or share
What the other thread receives
This program holds risk scores for a batch of three transactions in an Int32Array, all -1 (not scored yet), and sends it to a worker three ways: plainly, with its buffer in the transfer list, and backed by a SharedArrayBuffer. Each time the worker scores transaction 0 as 99, and the main thread looks at its own array afterwards.
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
/** Start a worker that scores transaction 0 as 99 (high risk), and wait until it has. */
function run(scores: Int32Array, transfer: ArrayBuffer[] = []): Promise<void> {
const worker = new Worker(process.argv[1]!, { workerData: scores, transferList: transfer });
return new Promise((resolve) => worker.once('message', () => resolve()));
}
async function main(): Promise<void> {
// Risk scores for a batch of three transactions; -1 means not scored yet.
const copied = new Int32Array(3).fill(-1);
await run(copied);
console.log(`copied: main sees ${copied[0]}, length ${copied.length}`);
const transferred = new Int32Array(3).fill(-1);
await run(transferred, [transferred.buffer]);
console.log(`transferred: main sees length ${transferred.length}`);
const shared = new Int32Array(new SharedArrayBuffer(12)).fill(-1);
await run(shared);
console.log(`shared: main sees ${shared[0]}, length ${shared.length}`);
}
if (isMainThread) {
void main();
} else {
(workerData as Int32Array)[0] = 99;
parentPort!.postMessage('done');
}
npx tsc --noEmit --strict main.ts && node main.ts
03Practice
Score without freezing
The lab uses native Node worker threads, while its fraud rule is authored arithmetic: 2,000 rounds per transaction, not a fixed duration or a real fraud detector. A 10 ms timer samples main-loop callback opportunities; it sends no network health request. The caller also records any riskScore calls on the main thread, so adding a later delay cannot disguise main-thread scoring. Fast batches may finish before three timer opportunities. A position-weighted checksum summarizes scores but is not a collision-free proof of every element.
The fraud-scoring batch
Score a batch of thousands of transactions while the service keeps answering health checks. Offload to a worker, get in-place results back, then let four workers score one batch.
Check this idea later
In the frontend A subarray view is not a separately owned buffer. Optional
A scoring-preview panel sends two selected bytes from a six-byte packet to a browser worker. The worker handles one message and closes. The panel expects to retain the other four bytes for its preview.
On the first click, what does the sender’s byte-length readout show? Which part of the packet can the receiver access through selection.buffer, beyond selection’s own bounds? This diagnostic uses an ordinary fresh buffer, not a pooled Node Buffer or shared memory.
"use client";
import { useState } from "react";
export default function ScoringPreview() {
const [remaining, setRemaining] = useState<number | null>(null);
function sendSelection() {
const packet = Uint8Array.from([10, 20, 30, 40, 50, 60]);
const selection = packet.subarray(2, 4);
const worker = new Worker(new URL("./scoring-preview-worker.ts", import.meta.url), {
type: "module"
});
worker.postMessage({ selection }, [selection.buffer]);
setRemaining(packet.byteLength);
}
return (
<section>
<button onClick={sendSelection}>Send selected bytes</button>
<output>Sender packet bytes: {remaining ?? "not sent"}</output>
</section>
);
}
The handler is under review. Transfer detaches the whole backing buffer and every sender view, even though selection covers two bytes. The receiver’s view keeps its bounds, but its backing buffer includes the surrounding bytes too.
Sign in to keep your read marks on every device. Sign in
Was this helpful?