Multithreaded JavaScript without copying data: how Erik Arvidsson built shared-memory threads three timesLongread · digest for December 5
Isometric risograph illustration of four parallel JavaScript threads working directly on a shared memory region without copying data
Longread6 sections≈ 18 min

Multithreaded JavaScript without copying data: how Erik Arvidsson built shared-memory threads three times

You send an array of a hundred thousand objects to a Web Worker so your UI doesn't freeze. You write worker.postMessage(data) and expect a second CPU core to crunch through it right away. Under the hood, something very different happens.

The engine runs the structured clone algorithm. It walks every object and array by reference, serializes the whole tree into bytes, sends it to the worker, and rebuilds a copy from scratch. Every browser Web Worker and every Node.js worker_threads instance has its own isolated heap, global object, and module graph. Threads can't share objects by reference. You either copy them or pack raw bytes into a SharedArrayBuffer using typed arrays and Atomics.

If the worker's actual job is small, copying takes longer than the math itself. At that point, it's tempting to give up and leave heavy work on the main thread. Still, the idea of giving JavaScript real shared-memory threads like Go or Java has never gone away.

Why a shared heap doesn't have to slow down normal code

In a shared-everything model, all threads live in one process and see the same global object, loaded modules, and shared heap. You create a plain object, spawn a thread, and both threads read and update it directly by reference:

// The object lives in a shared heap accessible to all threads
const o = { value: 1 };

const t = new Thread(() => {
  console.log(o.value); // 1
  o.value = 2;
});

// While the thread runs, this could print 1 or 2
console.log(o.value);

// Wait for the thread to finish without blocking the event loop
await t.asyncJoin();
console.log(o.value); // 2

It looks almost too simple. No postMessage, no manual buffer offsets, and no JSON rebuilding. This raises the main question: what does it cost normal single-threaded code? If the engine took a mutex on every property read, JavaScript would crawl.

Back in August 2017, WebKit engineer Filip Pizlo explained how to avoid this trap in Concurrent JavaScript: It can work!. His design relies on four rules that keep single-threaded code nearly as fast as before.

First, property reads are always lock-free. No thread ever takes a mutex just to read a field. Second, each object header stores a lock word holding the ID of the owning thread. As long as the creator thread writes to the object, the engine does one quick tag check and updates the field with zero locks.

Third, real locking only kicks in on contention. If another thread tries to write to someone else's object, it requests a takeover. The owner hands over the object at the next clean safepoint (like a loop iteration or when sleeping in join or Atomics.wait), and only then does the lock word switch to a normal lock.

Fourth, the model allows data races, but forbids crashes and torn reads. A torn read happens when one thread writes half of a 64-bit value while another reads a mix of old and new bits. In Pizlo's model, a reader may see the old value or the new value, but never garbage, never a crash, and never corrupted neighbor properties.

WebKit's segmented object model for safe lock-free multithreaded reads (Source: webkit.org)

WebKit's diagram shows why reads stay safe without locks: property values sit in 64-bit slots read atomically in one step, while the object layout rests on an immutable butterfly spine. When an object grows, the engine allocates a new block and leaves the old one valid until garbage collection, so readers never hit broken pointers.

In summer 2026, Bun creator Jarred Sumner revisited this architecture and opened experimental PR #249 for shared-memory threads in JavaScriptCore. Seeing that PR, engineer Erik Arvidsson decided to test the idea hands-on and ended up building multithreaded JavaScript three separate times. Each new attempt traded away part of the ideal model so the code could run in regular browsers today.

Phase 1: forking the Porffor compiler with multithreaded GC

Hacking V8 or JavaScriptCore alone takes months because those codebases are huge. For his first attempt, Arvidsson picked Oliver Medhurst's Porffor. It's a compact AOT compiler that turns JavaScript into C and compiles it to WebAssembly or native binaries. Porffor has a simple object layout and its own garbage collector, making it realistic to implement Pizlo's model.

Thread support in his arv/shared-everything-threads branch took about 2,300 lines of code. If a program doesn't use Thread, the threading runtime isn't even included in the final binary. The public API is clean: new Thread(fn) with join() and asyncJoin(), new Lock() with lock.hold(fn), new Condition() with wait(lock, timeoutMs?), plus SharedArrayBuffer and Atomics.

Here is how four threads push to one shared array and increment a shared counter at the same time:

// Plain array and object are shared across all threads without copying
const results = [];
const lock = new Lock();
const stats = { done: 0 };
const threads = [];

for (let id = 0; id < 4; id++) {
  threads.push(
    new Thread(() => {
      // Built-in array sync guarantees no push is lost
      results.push(id);
      // Protect read-modify-write with a mutex
      lock.hold(() => {
        stats.done++;
      });
      return id * 2;
    }),
  );
}

// Wait for all threads and collect their return values
console.log(threads.map(t => t.join())); // [0, 2, 4, 6]

Notice the difference between those two lines inside the thread. results.push(id) is thread-safe in the runtime itself, so no element is lost and the array won't corrupt. stats.done++, however, reads, adds, and writes back. Without lock.hold, two threads could read the same number and lose an increment.

Under the hood, everything follows Pizlo's textbook. Every value in Porffor is a 64-bit NaN-boxed word read atomically by the CPU. Plain object properties live in a separate buffer behind a single header word holding the pointer, size, and capacity. Readers load that header in one lock-free step. When an object needs to grow, the writer copies entries to a new buffer and leaves the old one for GC.

Arrays work the same way, while complex containers like Map, Set, promises, and generators lock the container. Native builds use process memory for the shared heap, and browsers use Wasm shared memory.

The trickiest part is the garbage collector. In a single-threaded runtime, GC pauses the program and scans memory. With multiple threads, you can't freeze a thread mid-pointer-write. So the Porffor fork uses stop-the-world GC with safepoints: GC signals a pause, and each thread parks itself at the next allocation or loop back-edge. Threads already sleeping in join or Atomics.wait count as parked. Once all threads stop, GC scans their stacks and registers, collects garbage, and resumes them.

ThreadSanitizer (--tsan) passed cleanly except for one intentional race built into the design. Single-threaded overhead was low: builds with threads run 0–7% slower, and only about 1% slower on the v8-v7 benchmark suite. In the browser Porffor playground, the compiler runs inside WebAssembly, compiles your JS to Wasm on the fly, and runs it on workers. The Mandelbrot demo speeds up roughly 7x on 8 threads on machines with at least 8 performance cores.

Phase 2: @arv/threads, data ownership, and the TypeScript 7.1 API

Porffor has one big downside: as an engine, it's still much slower than V8, JavaScriptCore, and SpiderMonkey, and it doesn't cover all of ECMAScript. Arvidsson wanted similar multithreading on top of fast everyday browser engines.

Diagram of the three ownership categories in @arv/threads: exclusive transfer Sending<T>, frozen shared data Shared<T>, and mutable cells in SharedArrayBuffer

His first idea looked tempting: write a TypeScript transpiler that finds objects crossing thread boundaries and moves them into SharedArrayBuffer automatically. That failed quickly against the reality of a dynamic language. Statically, you can't prove an arbitrary object won't leak to another thread through some helper function. So the compiler had to rewrite every unknown object just in case, which tanked normal code speed.

After talking with Justin Fagnani about the Zena language for WasmGC and its threading plans, Arvidsson flipped the approach. Instead of guessing, he built @arv/threads with explicit type annotations and a Rust-style static ownership checker.

All memory in @arv/threads falls into three value categories:

  1. Move ownership (Sending<T>): an object belongs to one thread at a time. Once you send it to another thread, the old owner loses access.
  2. Deeply frozen data (Shared<T>): read-only values that can be shared safely across any number of threads.
  3. Shared memory cells: struct, SharedArray, SharedMap, Lock, and Channel. Only these live in SharedArrayBuffer, and only these can be mutated in place by threads.

On top of TypeScript types sits a custom analyzer, @arv/threads-check. It started as a forked TypeScript compiler with lifetime tracking, which was later archived. When TypeScript 7.1 (the native Go port from Project Corsa) shipped its official API (typescript/sync, typescript/async, typescript/fs, typescript/ast), both the checker and compiler moved onto it.

The analyzer catches bugs regular TypeScript ignores: reading an object after sending it (use-after-send), using an alias reference to a sent object, casting Shared<T> to mutate it, or calling blocking operations inside an async function.

Speed comes from a compiler pass. It lays out declared structs in SharedArrayBuffer at fixed offsets and rewrites field access like b.x into direct typed-array indexing like __F64[(b >> 3) + 1]. Along with 64-bit floats (f64), struct fields support i32, u8, bool, str, and ref<T>(). For i32 or u8 fields, the checker forces explicit integer conversion via x | 0, Math.round(x), or integer math.

Here is an N-body physics step for 800 bodies, where threads update their own slices of a shared struct array in parallel:

import {
  f64,
  scope,
  SharedArray,
  struct,
  type Struct,
} from '@arv/threads';

// Define a struct with a fixed layout in shared memory
const Body = struct({ x: f64, y: f64, vx: f64, vy: f64, m: f64 });
type Body = Struct<typeof Body>;

// Each thread updates its index range in place
function step(bodies: SharedArray<Body>, lo: number, hi: number) {
  for (let i = lo; i < hi; i++) {
    bodies[i].x += bodies[i].vx;
  }
}

export function main(threads: number) {
  const bodies = new SharedArray(Body, 800);

  // scope automatically waits for all spawned threads to finish
  scope(s => {
    for (let t = 0; t < threads; t++) {
      s.spawn(
        step,
        bodies,
        Math.floor((t * 800) / threads),
        Math.floor(((t + 1) * 800) / threads),
      );
    }
  });
}

It reads almost like plain TypeScript, while the compiler handles all buffer indexing. You can try it in the browser @arv/threads playground, which runs official TypeScript 7.1 in WebAssembly and shows the generated __F64 JavaScript side by side.

N-body benchmarks and real limits of @arv/threads

The stopwatch tells the story. The same 800-body N-body step ran across plain single-threaded JS objects and compiled @arv/threads on one, two, four, and eight threads.

N-body step time for 800 bodies (lower is better)

On one thread, the compiled version is slightly slower than plain JS objects due to buffer overhead. By two threads, it beats single-threaded JS, then scales nearly linearly to four and eight threads until sync overhead dominates on this small dataset.

One more number didn't even fit on the chart. If you run the exact same @arv/threads code without the compiler pass (stripping TypeScript types and using runtime wrappers), one thread takes 1,820 ms. That's over 60x slower than the compiled version. Without rewriting field reads into direct typed-array indexes, shared memory in the browser falls flat.

@arv/threads is honestly labeled experimental and has real limits. The shared heap is capped at 256 MB, and much of it isn't freed yet. You can't pass closures that capture outer variables across threads. SharedMap uses one global mutex for the whole table, so eight threads writing heavily will line up behind it. Also, browsers still require COOP and COEP headers before SharedArrayBuffer works at all.

Phase 3: @arv/structs, the TC39 draft, and the Proxy trick

Looking at structs and SharedArray from phase two, Arvidsson noticed they closely matched the TC39 Structs proposal at Stage 2 (led by Shu-yu Guo and Ron Buckton). Instead of inventing a custom ownership system, he could focus on implementing the upcoming JavaScript standard as closely as possible. That became @arv/structs.

Architecture diagram of @arv/structs: one-way references from local worker heaps into SharedArrayBuffer, cached Proxy instances, and a direct fast path

TC39 Structs introduces objects with fixed fields where properties can't be added or deleted dynamically. A plain struct lives on the standard heap, while a shared struct lives in shared memory across workers. Two core rules apply: any operation that looks atomic in code (like reading a property) must be atomic under the hood, and references can point from a local heap into the shared heap, never the reverse.

@arv/structs bundles a spec-aligned runtime and a syntax compiler (struct, shared struct, SharedArray, Atomics.Mutex, Atomics.Condition, Atomics overloads for struct fields, and Reflect.canBeShared). Compilation is required because browsers don't understand shared struct yet. The compiler parses code with the TypeScript 7 API, edits source with magic-string, strips types with OXC, and supports on-the-fly loading in Node.js via --import.

Here is an example from the repo where four workers increment a shared counter to one million using a spec mutex:

// main.js
import { startWorker } from '@arv/structs/agent';

// Declare a struct that lives in shared memory
shared struct Tally {
  count = 0;
  mutex = new Atomics.Mutex();
}

const tally = new Tally();
const done = [];

for (let i = 0; i < 4; i++) {
  const w = startWorker(new URL('./worker.js', import.meta.url));
  // agent passes a reference to the same memory block, not a copy
  w.postMessage({ tally, n: 250_000 });
  done.push(new Promise(resolve => (w.onmessage = resolve)));
}

await Promise.all(done);
console.log(tally.count); // 1000000

// worker.js
import { parent } from '@arv/structs/agent';

parent.onmessage = ({ tally, n }) => {
  for (let i = 0; i < n; i++) {
    // using automatically unlocks at the end of each iteration
    using _ = Atomics.Mutex.lock(tally.mutex);
    tally.count++;
  }
  parent.postMessage('done');
};

Three neat details hide here. First, @arv/structs/agent starts workers attached to the same SharedArrayBuffer, so postMessage shares a reference instead of cloning. Second, using from Explicit Resource Management guarantees the mutex unlocks at the end of each loop step or on an exception, so you can't forget to unlock.

Third, workers notify the main thread with 'done' and await Promise.all(done). You can't use Atomics.Condition on the main thread because browsers block Atomics.wait there to keep pages from freezing.

Inside @arv/structs, the phase-two trick still runs, but strictly opt-in. Only shared struct code gets rewritten, so surrounding JS loses zero speed. Each shared struct is wrapped in a Proxy over its SharedArrayBuffer slice inside each worker. To preserve a === b for two references to the same struct, the runtime caches one Proxy per memory block per worker.

Of course, Proxy is still slow in hot loops. For TypeScript, the compiler enables a fast path: if a field is typed as : number, access goes directly to a typed array and skips Proxy. Repo benchmarks show 10 million increments take 18 ms with direct access versus 360 ms via Proxy (a 20x difference). On N-body, pure Proxy stretches the run to 7 seconds compared to 0.045 seconds on plain objects.

The docs also note a few gaps against the future spec. Interned strings, object shapes, symbols, and BigInt values outside -(2^60) to 2^60 - 1 aren't freed in shared memory yet. Also, a shared struct is only garbage-collected after every worker holding a local Proxy returns to its event loop and lets its local GC collect that Proxy. You can test the compiler and view generated JS in the @arv/structs playground.

All three approaches side by side, the AI-wrapper myth, and Bun's PR

All three tools solve the same problem at different layers of the stack. Putting them side by side makes the trade-offs clear.

ApproachMemory modelWhere it runsSpeed and overheadMain limits
Porffor (arv/shared-everything-threads)Shared heap for all objects (Pizlo model)Custom AOT compiler to Wasm or native0–7% single-thread overhead (~1% on v8-v7), ~7x on 8 threads (Mandelbrot)Base engine slower than V8/JSC/SpiderMonkey, incomplete ECMAScript
@arv/threadsSending<T> moves, Shared<T> frozen, cells in SharedArrayBufferStandard browsers and Node.js (on TS 7.1)6 ms on 8 threads vs 25 ms plain JS (N-body), 1,820 ms uncompiled256 MB heap cap, no cross-thread closures, single SharedMap lock, needs COOP/COEP
@arv/structsTC39 Structs draft (shared struct + Proxy over SharedArrayBuffer)Standard browsers and Node.js (TS 7 + OXC)Direct : number access 20x faster than Proxy (18 ms vs 360 ms for 10M ops)Requires build step, strings/large BigInt not freed, needs COOP/COEP

Both browser options (@arv/threads and @arv/structs) force you to decide upfront what data is shared and wrap it in special types. Porffor removes that barrier: any plain object or array already lives in one heap.

People often bring up a popular vibe-coding argument here: why care if SharedArrayBuffer is awkward when AI can generate all the byte-packing and worker boilerplate in ten seconds? The problem is that AI saves you from typing boilerplate, but it doesn't remove serialization and decoding costs at runtime. The CPU still burns milliseconds moving bytes back and forth, and heavy apps regularly bottleneck on that hidden tax.

To get a simple shared heap at industrial engine speed, the engine itself has to ship it. Right now, all eyes are on PR #249 in Bun's WebKit fork. Concurrent JavaScript already runs through all four tiers of JavaScriptCore's JIT without a global lock and passes the threading test suite. Still, there is a long road ahead: ThreadSanitizer cleanup, fuzzing, one benchmark that's still over budget, and long stress tests. Even Jarred Sumner warns in the PR description that the patch might never land in main.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 8