Glossary / Worker messaging
Worker messaging
Worker messaging transfers data and control between JavaScript agents, commonly between a browser main thread and Worker, between workers, or between Node worker threads. postMessage dispatches a message event asynchronously. The payload is processed using structured clone, with selected transferable objects moved rather than copied; shared memory is a separate model requiring synchronization.
Message protocol design
worker.postMessage({ type: "search", requestId: 12, query });
worker.addEventListener("message", ({ data }) => {
if (data.requestId !== currentRequestId) return; // stale response
render(data.results);
});
Define message types, versioning, correlation IDs, error representation, cancellation, and backpressure. Messages can arrive after the caller no longer cares; request IDs or Abort-like messages help reject stale results. Do not send functions, DOM nodes, or arbitrary class instances expecting their behavior to survive cloning. Validate messages as untrusted inputs, especially across extension, iframe, or process boundaries.
Large structured-clone payloads can consume CPU and memory. Transfer an ArrayBuffer when ownership can be relinquished; use SharedArrayBuffer only with cross-origin isolation/security requirements and a correct atomic protocol. MessagePort provides a dedicated two-way channel. Close ports and terminate workers according to lifecycle.
Interview questions
- Is postMessage synchronous? No; delivery is asynchronous through message events.
- What does structured clone preserve? Supported data values/graphs, not arbitrary functions, DOM nodes, or prototypes.
- Why use request IDs? To correlate replies and discard stale/out-of-order responses.
- Copy versus transfer? Copy retains source and duplicates data; transfer moves ownership and may detach source.