Web Development Bug Report

Web Worker postMessage slow with large buffers: use transferables

Moving point-cloud processing into a Web Worker made our viewer slower, not faster. Every postMessage copied a 200 MB Float32Array twice. Transferring the buffer instead of cloning it cut message time from 180 ms to under 1 ms.

Marcus Lindqvist Marcus Lindqvist @marcuslindqvist · November 14, 2026 · 7 min read · 112 Views
567-web-worker-postmessage-slow-large-buffers-transferables

Our browser-based survey viewer loads LiDAR point clouds of construction sites: around 16 million points, stored as x, y, z, intensity floats. Filtering and decimating those points used to block the main thread for seconds, so we moved the work into a Web Worker. The page stopped freezing during the filter itself, but every slider change still produced a visible stall, and the Performance panel in Chrome DevTools showed long tasks on the main thread right around each postMessage call.

[Violation] 'message' handler took 214ms

Total time per filter change had gone up compared with doing it on the main thread.

Reproducing it

// main.js
const worker = new Worker(new URL('./filter.worker.js', import.meta.url), { type: 'module' });
const points = new Float32Array(16_000_000 * 4); // 256 MB in our test; ~200 MB typical

slider.addEventListener('input', () => {
  const t0 = performance.now();
  worker.postMessage({ points, minIntensity: slider.valueAsNumber });
  console.log('post took', performance.now() - t0, 'ms');
});

worker.onmessage = ({ data }) => render(data.points);
// filter.worker.js
self.onmessage = ({ data }) => {
  const out = filter(data.points, data.minIntensity);
  self.postMessage({ points: out });
};

On a 2023 laptop, post took printed 150 to 190 ms for every message, before the worker even started.

What we ruled out

  • Worker startup. We create the worker once at load. The cost repeated on every message.

  • The filter algorithm. Timing inside the worker showed the filter took about 45 ms.

  • Rendering. WebGL upload of the result took about 20 ms, measured separately.

  • Garbage collection. GC pauses existed but were a symptom: each message allocated a fresh 200 MB copy, on both sides.

Root cause

postMessage uses the structured clone algorithm. Without a transfer list, an ArrayBuffer (and the typed array on top of it) is copied byte for byte into the worker, and the result is copied again on the way back. Two copies of 200 MB per slider change cost more than the filtering we moved off the main thread, and the serialisation happens synchronously on the sending thread.

What is happening under the hood

Workers do not share memory with the main thread by default. Structured clone serialises the message into an engine-internal format, and the receiver deserialises it into new objects. That is cheap for small objects and linear in size for buffers.

Transferable objects avoid the copy. When you list an object in the transfer list, the engine moves ownership of the underlying memory to the receiver. On the sender, the buffer becomes detached: byteLength turns into 0 and any typed array view over it has length 0. Nothing is copied, so the cost is constant regardless of size.

Transferable types include ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas, ReadableStream, WritableStream, TransformStream, VideoFrame and AudioData.

Two details trip people up:

  • You transfer the buffer, not the typed array. Pass points.buffer in the transfer list.

  • If a typed array is a view onto part of a larger buffer, transferring hands over the whole buffer, including bytes the view did not cover.

Environment

Component

Version / value

Chrome

142, macOS 26 and Windows 11

Firefox

145

Safari

26.1

Hardware

2023 laptop, 16 GB RAM

Data

16 million points x 4 floats, ~200 to 256 MB per message

Bundler

Vite 7, module workers

Minimal reproduction

const big = new Float32Array(50_000_000); // 200 MB
const w = new Worker(URL.createObjectURL(new Blob(
  ['onmessage = (e) => postMessage(e.data.byteLength)'], { type: 'text/javascript' })));

let t = performance.now();
w.postMessage(big.buffer);                  // clone: copies 200 MB
console.log('clone', performance.now() - t);

t = performance.now();
w.postMessage(big.buffer, [big.buffer]);    // transfer: moves ownership
console.log('transfer', performance.now() - t, 'byteLength now', big.buffer.byteLength);

Typical output on our test machine:

clone 162.4
transfer 0.3 byteLength now 0

Who is affected

  • Any app sending large binary data to or from workers: images, audio, video frames, geometry, WebAssembly memory dumps, parsed files.

  • Code that sends the same buffer repeatedly, because each send is a fresh copy.

  • All browsers. Transfer semantics are part of the HTML standard and supported everywhere workers are.

The fix

Transfer buffers in both directions and design the data flow around ownership: one side owns the buffer at a time.

 slider.addEventListener('input', () => {
-  worker.postMessage({ points, minIntensity: slider.valueAsNumber });
+  if (!state.points) return; // buffer is in the worker; wait for it to come back
+  const msg = { points: state.points, minIntensity: slider.valueAsNumber };
+  worker.postMessage(msg, [state.points.buffer]);
+  state.points = null;
 });

-worker.onmessage = ({ data }) => render(data.points);
+worker.onmessage = ({ data }) => {
+  state.points = data.source;   // original returned to the main thread
+  render(data.filtered);
+};
 self.onmessage = ({ data }) => {
-  const out = filter(data.points, data.minIntensity);
-  self.postMessage({ points: out });
+  const filtered = filter(data.points, data.minIntensity);
+  self.postMessage(
+    { source: data.points, filtered },
+    [data.points.buffer, filtered.buffer],
+  );
 };

We use the options form in newer code because it reads better and matches structuredClone:

worker.postMessage(msg, { transfer: [msg.points.buffer] });

Because the buffer leaves the main thread while the worker uses it, we also coalesce slider events: if a message is in flight, we remember only the latest slider value and send it when the buffer returns. That removed the queue of stale filter jobs that built up during fast dragging.

Alternatives and trade-offs

  • Keep the data in the worker. Load the file directly inside the worker with fetch, keep the points there, and send only small results or render through OffscreenCanvas in the worker. This was our long-term design: the main thread never holds the full cloud.

  • SharedArrayBuffer. Both sides see the same memory with no transfer at all, but you need cross-origin isolation headers and must coordinate access with Atomics. Worth it for real-time pipelines, overkill for request and response.

  • Copy deliberately. If the main thread must keep using the buffer while the worker works, points.slice() once and transfer the copy. You pay one copy, not two.

How to test the fix

A micro benchmark in our test page records both paths, and a Playwright test asserts the message cost stays low:

test('posting point cloud is constant time', async ({ page }) => {
  await page.goto('/viewer?fixture=large');
  const ms = await page.evaluate(async () => {
    const t = performance.now();
    await (window as any).viewer.applyFilter(0.4);
    return performance.now() - t;
  });
  expect(ms).toBeLessThan(120); // filter + render, no copies
});
npx playwright test viewer-perf.spec.ts --project=chromium

We also check for detachment bugs: a unit test sends a buffer and asserts the sender no longer reads from it, which caught one place that still rendered from the old reference.

Confirming in production

We added performance.mark and performance.measure around each filter cycle and sent the measures to our analytics:

filter_cycle_ms_p50   before: 410   after: 72
filter_cycle_ms_p95   before: 980   after: 140
long_tasks_per_drag   before: 11    after: 0-1

Memory also became steady. The heap no longer jumped by hundreds of megabytes per slider move, which had triggered tab crashes on 8 GB machines.

Regression guard

  • A helper postBuffer(worker, msg, buffers) is the only way feature code sends binary data, and it requires an explicit transfer list (an empty array means "I really want a copy").

  • The Playwright performance test runs on every merge to main.

  • Dev builds wrap Worker.prototype.postMessage to warn when a message contains an ArrayBuffer over 10 MB that is not in the transfer list.

Security implications

None beyond normal worker hygiene. Transferring moves memory between threads of the same origin; it does not expose data to other origins. Validate messages from workers like any input: a worker that loads third-party code should not be able to send buffers the main thread trusts blindly. If you switch to SharedArrayBuffer, the required cross-origin isolation headers change how third-party embeds load, so test them.

Prevention checklist

  • List every large ArrayBuffer in the transfer list, in both directions.

  • Model ownership explicitly; never read a buffer after sending it.

  • Prefer keeping large data inside the worker and sending small results.

  • Measure message cost with performance.now() before and after moving work to a worker.

References

Add a label

#javascript #performance #web-workers #arraybuffer #structured-clone
Written by
Marcus Lindqvist @marcuslindqvist

I have spent most of the last decade on mobile teams, first native iOS, then React Native and Flutter for companies that needed one team to ship to both stores. The work I enjoy most is the unglamorous part between "it runs on my phone" and "it is live for a million users": code signing, release builds, store review, crash triage and background behaviour that differs on every Android vendor. Most of the bugs I write about here cost a release day. Each post shows the exact error, what we ruled out, the fix and how we proved it in the next build, so you can get your own release out the door sooner.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.