skip to content

Worker Threads

Real threads for CPU-bound work, each with its own V8 isolate and event loop, talking over message ports. Interviewers focus on postMessage copy cost and on pooling workers instead of one per request.

on this pageshow

explore

questions

5

In Node.js, what does worker.postMessage() do with the value you pass, and how does a transferList change the cost of sending an ArrayBuffer?

level: middleimportance: must knowfreq 62%

answer

  1. copy, move or share
  2. structured clone, not JSON
  3. sender's view goes empty
  4. pooled Buffers refuse transfer

basics

~20 s

postMessage() copies the value with the structured clone algorithm, paid by both threads. Listing an ArrayBuffer in transferList moves its memory instead: no copy, but the sender's views become unusable. Pooled Buffers cannot be transferred and are cloned with their whole pool.

solid answer

~40 s

`worker.postMessage(value)` serialises `value` immediately on the sending thread with the structured clone algorithm and deserialises it on the receiver, so a large object graph costs CPU on both sides and exists twice in memory. It handles cycles, `Map`, `Set` and typed arrays, but functions and some built-ins such as `URL` throw a `DataCloneError`, class instances arrive as plain objects, and a `Buffer` arrives as a plain `Uint8Array`. Passing `[buf.buffer]` as the `transferList` moves the `ArrayBuffer` without copying, and every view of it on the sender becomes empty. A small `Buffer.from()` or `Buffer.allocUnsafe()` buffer is a slice of Node's shared pool: transferring it throws, and cloning it copies the whole pool, 64 KiB by default since Node 24.18.0. A `SharedArrayBuffer` is neither copied nor transferred; both threads see it.

code

javascript · 18 lines
javascript
import { MessageChannel } from 'node:worker_threads';

const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
  console.log('received', msg.byteLength, 'bytes');
  port1.close();
});

const frame = new Uint8Array(16 * 1024 * 1024);
port2.postMessage(frame, [frame.buffer]);
console.log('sender length after transfer:', frame.length);

const small = Buffer.from('hello');
try {
  port2.postMessage(small, [small.buffer]);
} catch (err) {
  console.log('pooled Buffer:', err.name);
}

go deeper

for a junior

Recall that messages between Node threads are copies, not shared references, and that functions cannot be sent.

for a middle

Explain clone versus transfer versus share, which side pays the serialisation cost, and why every view over a transferred ArrayBuffer goes empty.

for a senior

Spot the production traps: pooled Buffers that refuse transfer and clone their whole pool, Buffers arriving as Uint8Array, and large messages showing up in CPU profiles.

for a principal

Set the message contract for a team's workers: small plain messages, transferred binary payloads, and shared memory only where the coordination cost is justified.

## What postMessage() actually sends Threads in `node:worker_threads` do not share ordinary JavaScript objects; each worker has its own heap. `worker.postMessage(value)`, `parentPort.postMessage(value)` and the `workerData` constructor option therefore have to turn `value` into bytes on one side and rebuild it on the other. Node uses the **HTML structured clone algorithm** for this, through the same serializer that `node:v8` exposes. Two consequences follow: - **The copy happens immediately.** The documentation says "the message object is cloned immediately, and can be modified after posting without having side effects". The sending thread pays the serialisation cost synchronously inside the `postMessage()` call. - **Both threads pay.** The receiver deserialises the data before its `'message'` listener runs, and until garbage collection both heaps hold a copy. For a 50 MB object graph that is 50 MB of extra memory and CPU time on two threads. ## What survives the clone and what does not Structured clone is richer than `JSON`: it keeps circular references, `Map`, `Set`, `RegExp`, `BigInt`, `Date`, typed arrays and `WebAssembly.Module` instances. It is still not a deep copy of arbitrary objects: - **Functions** cannot be cloned; the `workerData` documentation says an error is thrown if the value contains functions. - **Some built-ins** throw a `DataCloneError`; the docs use `new URL(...)` as the example. - **Prototypes, accessors and non-enumerable properties are dropped**, so a class instance arrives as a plain object and its methods are gone. - **A `Buffer` arrives as a plain `Uint8Array`**, because the `Buffer` prototype is not preserved. - **Native objects** are refused except a documented list that includes `MessagePort`, `FileHandle`, `KeyObject`, `CryptoKey`, `X509Certificate`, `net.BlockList` and `net.SocketAddress`; a TCP `net.Server` or `net.Socket` can move only when listed in `transferList`. ## Copy, transfer or share | How the bytes travel | What you write | Cost | Sender afterwards | |---|---|---|---| | **Clone** | `port.postMessage(u8)` | Full copy, serialise and deserialise | Keeps its data | | **Transfer** | `port.postMessage(u8, [u8.buffer])` | No copy of the bytes | Every view of that buffer is empty | | **Share** | `port.postMessage(new Int32Array(sab))` | No copy; same memory | Still reads and writes it | A **transfer** moves ownership of an `ArrayBuffer`'s memory to the receiving thread. The data is not copied, which is why it is the normal way to hand an image or a large binary frame to a worker. The catch is that the memory belongs to the `ArrayBuffer`, not to the view: transferring it makes **all** `TypedArray` and `Buffer` views over that same `ArrayBuffer` unusable on the sender. In the docs' example a `Uint16Array` sharing the buffer reports a length of 0 after its sibling view was transferred. A **`SharedArrayBuffer`** cannot appear in a transfer list at all. Posting it, or a view of it, gives the receiver access to the same memory, so nothing is copied and coordination becomes your job. ## The Buffer pool trap Node pre-allocates a pool and serves small allocations from slices of it. According to the `Buffer` documentation, `Buffer.allocUnsafe()`, `Buffer.from(string)`, `Buffer.from(array)` and `Buffer.concat()` use the pool when the size is below `Buffer.poolSize >>> 1`. Since **Node 24.18.0** `Buffer.poolSize` defaults to 65536 bytes (64 KiB, raised from 8192), so slices under 32 KiB come from the pool. Node marks its pool `ArrayBuffer`s with `markAsUntransferable()`, which has two effects: 1. Listing a pooled buffer's `.buffer` in a `transferList` throws a `DataCloneError` (an error has been thrown here since v21.0.0). 2. Posting the pooled buffer without a transfer list clones it, and the clone carries the whole underlying pool, which the documentation warns costs extra memory and can expose unrelated bytes to the receiver. The fixes are to allocate buffers you intend to transfer with `Buffer.alloc()` or `Buffer.allocUnsafeSlow()`, which own their `ArrayBuffer`, or to copy the bytes into a fresh `ArrayBuffer` before posting. Transferring such a buffer still empties every other view of it. ## Rules of thumb - Send **small, plain data**: identifiers, numbers, strings, and buffers you transfer. - **Transfer** large binary payloads such as image bytes, and do not touch them on the sender afterwards. - Do not post class instances or `Buffer`s and expect their methods on the other side; rebuild them on the receiver (`Buffer.from(u8.buffer, u8.byteOffset, u8.length)`). - Measure: if `postMessage()` shows up in a CPU profile, the message is too big or should be transferred.

  • A worker posts a Buffer back to the main thread, and the main thread calls buf.toString('hex') on it. What goes wrong, and how do you fix it?
    Structured clone does not preserve the `Buffer` prototype, so the main thread receives a plain `Uint8Array`. `Uint8Array.prototype.toString()` ignores the encoding argument and returns comma-separated numbers, so you get the wrong output rather than an error. Wrap it without copying: `Buffer.from(u8.buffer, u8.byteOffset, u8.length)`, then call `toString('hex')`.
  • When is cloning a message actually cheaper than restructuring code to transfer or share memory?
    When messages are small. Serialising a few hundred bytes of identifiers and numbers costs far less than the bookkeeping of transfers or the coordination a `SharedArrayBuffer` demands. Transfer pays off for large binary payloads, and sharing pays off when several threads repeatedly read the same large block.

  • Thinking postMessage() passes a reference to the same object to the worker
  • Believing structured clone keeps class methods and the Buffer prototype
  • Transferring an ArrayBuffer and then still reading it on the sending side
  • Assuming any Buffer can be transferred, including small pooled ones
  • Listing a SharedArrayBuffer in transferList to share it
  • Treating postMessage() as free because it is asynchronous

Assumes Node 24.18.0 or later, where Buffer.poolSize defaults to 64 KiB (8 KiB before); since v21.0.0 an untransferable object in a transfer list throws.

open as a page

A Node.js image-resizing endpoint creates a new worker_threads.Worker for every request, and under load latency and memory climb sharply. Why, and how should it be restructured?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Every new Worker boots a V8 isolate and Node environment and reloads its modules, and unbounded workers outnumber the cores and multiply heaps. Use a fixed pool of long-lived workers fed by a bounded queue, transfer image bytes, and replace workers that die.

open as a page

In Node.js, what happens to a worker_threads.Worker and to the main thread when code inside the worker throws an uncaught exception?

level: middleimportance: should knowfreq 45%

basics

~20 s

The worker thread is terminated and its Worker object emits 'error' with the exception, then 'exit' with code 1. The main thread keeps running only if something listens for 'error'; with no listener, the error is rethrown there and crashes the process.

open as a page

In Node.js 24, how do you cap a worker_threads.Worker's heap with resourceLimits, what happens when the worker exceeds it, and what does the cap not cover?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Pass resourceLimits such as maxOldGenerationSizeMb to new Worker(). Exceeding it terminates only that worker, which emits 'error' with ERR_WORKER_OUT_OF_MEMORY and then 'exit'. The cap covers the JS heap only, not ArrayBuffers or other external memory.

open as a page

In Node.js, how do the main thread and a worker_threads.Worker share a SharedArrayBuffer and signal each other with Atomics.wait and Atomics.notify, and why avoid Atomics.wait on the main thread?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Post a SharedArrayBuffer, or a typed-array view of it, through workerData or postMessage(); both threads then see the same memory. Atomics.wait blocks a thread until Atomics.notify wakes it. Node permits it on the main thread, but it freezes the whole event loop.

open as a page