← Back to Pull requests

src: experimental green threads implementation #67288

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 06, 2026 02:26 UTC
Author

~~This is an experiment... opening for feedback.~~ This is ready for review.

This implements green threads for Node.js. A green thread is a lightweight kind of worker. It has its own V8 isolate with no Node.js APIs. They run on a small pool of physical threads that they share, instead of each getting an OS thread and event loop like a worker thread. Each one gets work from the host through messages, RPC calls, or its module's exports, and every piece of work runs in an invocation context of its own. Each green thread can have limits on CPU time and memory, and the host can terminate it. This makes them cheap to start and to keep around in large numbers, and suited to running many small, untrusted pieces of code, such as plugins, per-tenant handlers, or user-supplied scripts.

const { GreenThread } = require('node:green_threads');

const greenThread = new GreenThread(`
  onmessage = ({ data }) => postMessage(data * 2);
`);
greenThread.on('message', (value) => {
  console.log(value);  // Prints: 42
  greenThread.terminate();
});
greenThread.postMessage(21);

For later, the plan is to add the following APIs (but not in this PR)

TextEncoder/TextDecoder
URL/URLSearchParams

  • structuredClone()
  • <details>

    Compared with worker threads

    Green threads have real advantages over workers, in specific areas:

  • Memory: 2–6× less per instance, depending on the build and the

  • isolate-group setting. A thousand tenants take about 1 GB instead of 6.7 GB.
  • Startup: up to about 80× faster with a warm pool (about 20 µs each).

  • Many instances: 1000 instances share 8 OS threads instead of using

  • 1000, and serve about 15–20% more requests per second.
  • Sandboxing: no Node.js APIs, plus per-instance CPU-time and memory

  • limits.

    They don't win on the speed of a single message, and they can't spread heavy
    computation across all cores, since the pool is capped at 8 threads.

    Setup for this performance comparison

  • Machine: 88 CPUs, 250 GB RAM, Linux x64.

  • Two builds:

  • - Release: the default build, without pointer compression. It doesn't
    support isolate groups, so every green thread is in V8's default group.
    - Pointer compression: supports isolate groups. By default, each green
    thread is in an isolate group of its own.
  • Green thread pool: 8 threads (kMaxPoolThreads).
  • Each measurement runs in a fresh child process, so that memory numbers don't
    include what earlier measurements left behind.

    Kinds of green threads measured:

    | Kind | Meaning |
    |---|---|
    | green | Default options: an isolate group of its own where supported |
    | green-default | isolateGroup: 'default', V8's default isolate group |
    | green-shared | One IsolateGroup shared by all instances |
    | green-warm | Default options, taken from a warm pool filled beforehand |

    Memory and startup

    1000 idle instances, started at once, measured once each has sent a message.

    | | RSS per instance | Starts per second | OS threads |
    |---|---|---|---|
    | Worker | 6.7–7.9 MB | ~720 | 1000 |
    | Green, Release build | 5.2 MB | ~750 | 8 |
    | Green, pointer compression (own isolate group) | 2.8 MB | ~1,220 | 8 |
    | Green, pointer compression (isolateGroup: 'default') | 2.6 MB | ~810 | 8 |
    | Green, shared IsolateGroup | 1.03 MB | ~1,590 | 8 |
    | Green, from a warm pool | same as cold | 44,000–66,000 | 8 |

  • Memory: a green thread uses 1.5× to 6.5× less memory than a worker. A

  • worker carries a whole Node.js environment, an event loop and an OS thread
    with its stack. A green thread is a V8 isolate with a small runtime.
  • Threads: green threads share a pool of 8 threads, however many there

  • are.
  • Warm pool: setWarmPoolSize(n) prepares isolates in advance, so

  • starting a green thread takes about 20 µs. Workers have no equivalent.
  • Cold start is only slightly faster than a worker's, except with a

  • shared isolate group.

    Speed

    ##### Message round trips

    Sequential round trips with one instance.

    | | Round trips per second | Latency |
    |---|---|---|
    | Green | ~57,000 | ~17.5 µs |
    | Worker | ~61,000 | ~16.5 µs |

    Workers are about 5% faster per message.

    ##### CPU-bound tasks

    2000 tasks of fib(27), each executor taking the next task once it's done.
    Release build.

    | | Tasks per second | Time |
    |---|---|---|
    | Green ×8 | 2,466 | 811 ms |
    | Green ×2000 (one per task) | 2,226 | 898 ms |
    | Worker ×8 | 2,478 | 807 ms |
    | Worker ×88 | 9,759 | 205 ms |

    At equal parallelism, CPU-bound code runs at the same speed. Green threads
    can't use more than 8 cores, though, so for heavy parallel computation
    workers win clearly. The cap is a choice in this implementation, not
    inherent, and could be made configurable.

    ##### Many tenants

    1000 tenants, each with code and state of its own, serving 50,000 requests
    spread over all of them, 64 at a time.

    | | All started | Requests per second | RSS total |
    |---|---|---|---|
    | Worker (Release) | 1,653 ms | ~129,000 | 7,974 MB |
    | Green (Release) | 1,332 ms | ~150,000 | 5,267 MB |
    | Worker (pointer compression) | 1,387 ms | ~126,000 | 6,725 MB |
    | Green (pointer compression) | 836 ms | ~149,000 | 2,883 MB |
    | Green, shared IsolateGroup | 632 ms | ~149,000 | 1,112 MB |

    Green threads serve about 15–20% more requests, since 8 pool threads don't
    compete for the CPU the way 1000 OS threads do.

    ##### Runaway code

    One of 100 tenants runs into an endless loop, while the others keep serving.

    | | Stopped by | Stopped after | Others served in 200 ms |
    |---|---|---|---|
    | Green | ERR_GREEN_THREAD_CPU_LIMIT (maxTaskCpuTimeMs: 50) | ~60 ms | ~35,000 |
    | Worker | A host timer, then terminate() | ~70 ms | ~31,500 |

    Both stop it. Green threads do it with a limit on CPU time, which the runtime
    enforces. Workers need a timer by wall time on the host, which also stops
    code that's only waiting.

    What's easier to build: a plugin host

    The same plugin host, built with each. It runs five plugins, which are ES
    modules exporting transform(text). Plugins can import a shared module, and
    call back into the host for configuration and logging. Three of them
    misbehave.

    | Plugin | Green threads | Workers |
    |---|---|---|
    | upper, reverse (well-behaved) | Work | Work |
    | spin (endless loop) | ERR_GREEN_THREAD_CPU_LIMIT after 100 ms of CPU time | The host's own wall-clock timeout, which also stops plugins that are only waiting |
    | hog (allocates ArrayBuffers) | Allocation fails at the 32 MB maxMemoryMb limit | Not limited, since resourceLimits only cover the JS heap. Reached 91 MB within the 100 ms timeout |
    | fail (throws with a code) | Error arrives with code: 'ERR_PLUGIN' | Only with hand-written error forwarding |

    The green thread version is 43 lines:

    const plugin = new GreenThread(source, {
      type: 'module',
      filename: `file:///plugins/${name}/index.js`,
      modules: plugins.shared,
      env: {
        async config(key) { return plugins.config[key]; },
        log(...args) { console.log(`[${name}]`, ...args); },
      },
      resourceLimits: { maxTaskCpuTimeMs: 100, maxMemoryMb: 32 },
    });
    const { transform } = await plugin.exports;
    console.log(await transform('hello world'));
    

    The worker version is 155 lines, since it has to build what green threads
    provide:

  • Module loading: workers load modules from files or URLs, so the

  • plugins are written to a temporary directory. Green threads take a
    modules bundle and resolve() / load() hooks.
  • Calls in both directions: workers need call IDs, a table of pending

  • calls, and error forwarding, roughly what Comlink does. Green threads get
    exports and env as RPC stubs.
  • Limits: workers have no CPU-time limit and no ArrayBuffer limit.

  • Green threads have both.
  • Isolation: worker plugins have all of Node.js' APIs, including

  • require('fs'). The permission model applies to the whole process, so it
    can't restrict a single worker. Green threads have no Node.js APIs at all:
    they can only do what the host passes them. This is the biggest
    qualitative difference.

    When to use which

    Use green threads for:

  • Multi-tenant or serverless-style hosting of many small handlers.

  • Plugin and extension systems that run untrusted code.

  • User-supplied scripts, rules, or transforms that need CPU and memory

  • limits.
  • Many short-lived or mostly idle units of code, where startup time and

  • memory per instance matter.

    Use workers for:

  • Code that needs Node.js' APIs (fs, net, child_process), or npm

  • packages that use them.
  • Heavy parallel computation across all cores, while the green thread pool

  • is capped at 8 threads.
  • Blocking code: Atomics.wait() and synchronous waits are disabled in green

  • threads, since a blocked isolate would hold up a shared pool thread.
  • A few long-lived instances, where the cost per instance doesn't matter.
  • Caveats

  • The pointer-compression numbers come from the build at f14fd2d7548,

  • which doesn't have the ES modules and errors commits. These scenarios don't
    use either.
  • The warm-pool numbers for the pointer-compression build come from a later

  • run than the rest of its table. The first run used a setting that bypassed
    the pool.
  • Worker startup throughput depends on the number of cores. On smaller

  • machines, the gap is likely larger.
  • Some JIT-compiled loops ignore termination, a V8 bug. Green threads rely on

  • a watchdog that abandons such isolates. Workers are affected by the same
    bug when terminated.

    </details>

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: bakkot Review duration: 35505m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #67288"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%
    Repository