Skip to content

new_module_registry increases Worker startup time; about 10 ms of it appears only with nodejs_compat #8365

Open

Description

@rikbrown

Summary

When we add new_module_registry to compatibility_flags and change nothing else, the "Worker Startup Time" that
wrangler deploy reports goes up. On a production account, all 24 Workers built as one esbuild bundle increased
(median +50 ms, largest +400 to +530 ms), and so did the 4 Workers built by Vite with code-split chunks. Workers
deployed in the same run without the flag change did not change.

A local reproduction with generated Workers shows the same direction:

  • An empty Worker with nodejs_compat uses about 10.7 ms more CPU at load with the flag. Without nodejs_compat, the
    difference is 0.5 ms.
  • Above that fixed cost, the increase grows with the size of the JavaScript that is evaluated at startup: about +12 ms
    for a 1 MB module, +27 ms for a 6 MB module, +20 ms for 300 modules (2.4 MB in total).
  • Modules that are only reachable through import() cost less with the flag than without it, as expected from lazy
    loading.
  • wrangler check startup does not show the fixed cost (details below).

The new registry becomes the default for compatibility dates on or after 2026-11-17. We would like to know if this cost
is expected, and if it will change.

We use the flag because it fixes #7779 (with the legacy registry, a dynamic import() started in a request that ends
first never settles). To keep that fix, we must accept the startup cost.

Environment

  • Production: compatibility dates 2026-07-01 to 2026-08-01, nodejs_compat. Wrangler 4.157.0. Startup times are the
    "Worker Startup Time" lines of wrangler deploy.
  • Local: workerd 1.20261103.1 (workerd --version: workerd 2026-11-03), wrangler 4.157.0, macOS 27.0.1, Apple M4 Max.

Production observations

Each "before" is 3 to 5 deploys of the same Worker. Each "after" is 1 deploy. For the single-bundle Workers, the
bundles were byte-identical before and after: only compatibility_flags changed.

Worker Before (ms) After (ms)
GraphQL API, single esbuild bundle, plus one Wasm module (resvg) and a .ttf Data module 157–287 685
Single esbuild bundle 65–89 219
Single esbuild bundle 43–64 155
Single esbuild bundle 36–41 118
Single esbuild bundle, GraphQL API with pg 361 376
Vite build, about 80 code-split chunks 39 69
Two Vite builds (TanStack Start) 20–44 85–94
Vite build, Durable Object Worker, 62 modules, 27 of them Text modules (.sql) 177–201 398
  • All 24 single-bundle Workers increased, median +50 ms. The pg Worker above is not one of the 24.
  • 6 Workers in the same deploy run without the flag change: median −3 ms.

The production increases are larger than the local ones. We do not know which part of the production startup time
the local measurement covers.

Reproduction

The generator writes each variant twice, to workers/<variant>/off and workers/<variant>/on. The files are
byte-identical. Only compatibility_flags differs. Compatibility date 2026-08-01. All variants except
a0-empty-no-nodejs-compat use nodejs_compat. All JS is generated (functions with object and string literals).

Variant Content
a0-empty-no-nodejs-compat Empty Worker, no nodejs_compat
a0-empty Empty Worker
a1-single-1mb One 1 MB ES module
a2-single-6mb One 6 MB ES module
b1-modules-20 Entry + 20 ES modules of 8 KB, imported statically
b2-modules-100 Entry + 100 ES modules of 8 KB, imported statically
b3-modules-300 Entry + 300 ES modules of 8 KB, imported statically
b4-modules-100-lazy Entry + 100 ES modules of 8 KB, reachable only through import() in fetch
c1-wasm-data Wasm module (3.0 MB: 200k small functions, 1 MB data segment) + two 1 MB Data modules
d1-text-30 Entry + 30 Text modules (.sql, about 10 KB each), imported statically

Steps:

npm install wrangler@4.157.0          # brings workerd 1.20261103.1
node gen.mjs                          # writes ./workers
python3 run-workerd-cpu.py 21         # 21 runs per mode, off and on alternate

run-workerd-cpu.py runs workerd test --experimental config.capnp in each directory. The test handler is empty, so
the process only creates the isolate, loads the modules and evaluates the top level. It opens no sockets. The script
records the CPU time of the process (user + sys of all threads, from wait4) and the wall time. --experimental is set
in both modes because workerd refuses new_module_registry without it.

gen.mjs
// Generates the Worker variants of the reproduction into ./workers/<variant>/{off,on}/.
// Each variant has the same files twice; only `compatibility_flags` differs.
// Usage: node gen.mjs
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const OUT = new URL("./workers/", import.meta.url).pathname;
const COMPAT_DATE = "2026-08-01";

// Deterministic pseudo-random bytes, so every run generates the same files.
function prng(seed) {
  let s = seed >>> 0;
  return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32);
}

// ~`bytes` of plain JS: functions with object literals and string constants, all reachable from `run()`.
function jsBlob(prefix, bytes, seed) {
  const rnd = prng(seed);
  const parts = [];
  let size = 0;
  let i = 0;
  while (size < bytes) {
    const words = Array.from({ length: 12 }, () => Math.floor(rnd() * 1e9).toString(36)).join(" ");
    const fn = `function ${prefix}_${i}(x){const o={id:${i},label:${JSON.stringify(words)},v:[${i},${i * 3},${i * 7}]};return o.v[x%3]+o.label.length+x;}\n`;
    parts.push(fn);
    size += fn.length;
    i++;
  }
  parts.push(`export function ${prefix}_run(x){let t=0;for(const f of [${Array.from({ length: i }, (_, k) => `${prefix}_${k}`).join(",")}])t+=f(x);return t;}\n`);
  return parts.join("");
}

function leb(n) {
  const out = [];
  do {
    let b = n & 0x7f;
    n >>>= 7;
    if (n !== 0) b |= 0x80;
    out.push(b);
  } while (n !== 0);
  return out;
}
function section(id, payload) {
  return [id, ...leb(payload.length), ...payload];
}

// A valid Wasm module: `fnCount` small functions (i32)->i32 plus a `dataBytes` data segment.
function wasmModule(fnCount, dataBytes) {
  const rnd = prng(7);
  const typeSec = section(1, [1, 0x60, 1, 0x7f, 1, 0x7f]);
  const funcSec = section(3, [...leb(fnCount), ...new Array(fnCount).fill(0)]);
  const pages = Math.ceil(dataBytes / 65536) + 1;
  const memSec = section(5, [1, 0, ...leb(pages)]);
  const exportName = [...Buffer.from("f0")];
  const exportSec = section(7, [1, ...leb(exportName.length), ...exportName, 0, 0]);
  const bodies = [];
  for (let k = 0; k < fnCount; k++) {
    const body = [0, 0x20, 0, 0x41, ...leb(k & 0x3fff), 0x6a, 0x0b];
    bodies.push(...leb(body.length), ...body);
  }
  const codeSec = section(10, [...leb(fnCount), ...bodies]);
  const data = Array.from({ length: dataBytes }, () => Math.floor(rnd() * 256));
  const dataSec = section(11, [1, 0, 0x41, 0, 0x0b, ...leb(dataBytes), ...data]);
  return Buffer.from([0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0, ...typeSec, ...funcSec, ...memSec, ...exportSec, ...codeSec, ...dataSec]);
}

function randomBytes(n, seed) {
  const rnd = prng(seed);
  return Buffer.from(Array.from({ length: n }, () => Math.floor(rnd() * 256)));
}

const variants = {
  // Control: an empty Worker.
  // Control without nodejs_compat: separates the cost of the built-in node: modules.
  "a0-empty-no-nodejs-compat": () => ({
    "index.js": `export default { fetch() { return new Response("ok"); } };\n`,
  }),
  "a0-empty": () => ({
    "index.js": `export default { fetch() { return new Response("ok"); } };\n`,
  }),
  // One large single-file bundle, as esbuild produces.
  "a1-single-1mb": () => singleFile(1_000_000),
  "a2-single-6mb": () => singleFile(6_000_000),
  // Code-split output: N small ES modules, all imported statically by the entry.
  "b1-modules-20": () => manyModules(20, false),
  "b2-modules-100": () => manyModules(100, false),
  "b3-modules-300": () => manyModules(300, false),
  // The same 100 modules, imported only through dynamic import() that startup does not run.
  "b4-modules-100-lazy": () => manyModules(100, true),
  // One Wasm module (3.0 MB: 200k functions + 1 MB data segment) and two 1 MB Data modules.
  "c1-wasm-data": () => ({
    "index.js": [
      `import wasm from "./engine.wasm";`,
      `import fontA from "./font-a.bin";`,
      `import fontB from "./font-b.bin";`,
      `export default { async fetch() {`,
      `  const inst = await WebAssembly.instantiate(wasm);`,
      `  return new Response(String(inst.exports.f0(1) + fontA.byteLength + fontB.byteLength));`,
      `} };`,
      ``,
    ].join("\n"),
    "engine.wasm": wasmModule(200_000, 1_000_000),
    "font-a.bin": randomBytes(1_000_000, 11),
    "font-b.bin": randomBytes(1_000_000, 12),
  }),
  // 30 Text modules (~10 KB of SQL each), imported statically by the entry.
  "d1-text-30": () => {
    const files = {};
    const imports = [];
    for (let k = 0; k < 30; k++) {
      const name = `migration-${String(k).padStart(3, "0")}.sql`;
      files[name] = Array.from({ length: 150 }, (_, r) => `INSERT INTO t_${k} (id, value) VALUES (${r}, 'row ${r} of table ${k}');`).join("\n") + "\n";
      imports.push(`import sql${k} from "./${name}";`);
    }
    files["index.js"] = [
      ...imports,
      `const all = [${Array.from({ length: 30 }, (_, k) => `sql${k}`).join(",")}];`,
      `export default { fetch() { return new Response(String(all.reduce((n, s) => n + s.length, 0))); } };`,
      ``,
    ].join("\n");
    return files;
  },
};

function singleFile(bytes) {
  return {
    "index.js": jsBlob("f", bytes, 1) + `export default { fetch() { return new Response(String(f_run(1))); } };\n`,
  };
}

function manyModules(count, lazy) {
  const files = {};
  const perModule = 8_000;
  for (let k = 0; k < count; k++) {
    files[`chunks/chunk-${k}.js`] = jsBlob(`m${k}`, perModule, 100 + k);
  }
  const names = Array.from({ length: count }, (_, k) => `m${k}_run`);
  if (lazy) {
    files["index.js"] = [
      `const loaders = [${Array.from({ length: count }, (_, k) => `() => import("./chunks/chunk-${k}.js")`).join(",\n")}];`,
      `export default { async fetch(req) {`,
      `  const n = Number(new URL(req.url).searchParams.get("n") ?? 0) % loaders.length;`,
      `  const m = await loaders[n]();`,
      `  return new Response(String(m[\`m\${n}_run\`](1)));`,
      `} };`,
      ``,
    ].join("\n");
  } else {
    files["index.js"] = [
      ...Array.from({ length: count }, (_, k) => `import { ${names[k]} } from "./chunks/chunk-${k}.js";`),
      `const runs = [${names.join(",")}];`,
      `export default { fetch() { return new Response(String(runs.reduce((t, f) => t + f(1), 0))); } };`,
      ``,
    ].join("\n");
  }
  return files;
}

function config(name, flags) {
  return {
    name,
    main: "index.js",
    compatibility_date: COMPAT_DATE,
    compatibility_flags: flags,
    // Upload the files as they are, so both configs upload byte-identical modules.
    no_bundle: true,
    find_additional_modules: true,
    rules: [
      { type: "ESModule", globs: ["**/*.js"] },
      { type: "CompiledWasm", globs: ["**/*.wasm"] },
      { type: "Data", globs: ["**/*.bin"] },
      { type: "Text", globs: ["**/*.sql"] },
    ],
  };
}

const base = (variant) => (variant.endsWith("no-nodejs-compat") ? [] : ["nodejs_compat"]);

// The same modules as a workerd config, for `workerd test` (no sockets).
function capnp(files, flags) {
  const kind = (path) =>
    path.endsWith(".js") ? "esModule" : path.endsWith(".wasm") ? "wasm" : path.endsWith(".bin") ? "data" : "text";
  const paths = ["index.js", ...Object.keys(files).filter((p) => p !== "index.js")];
  const modules = paths.map((p) => `      (name = "${p}", ${kind(p)} = embed "${p}")`).join(",\n");
  return `using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
  services = [ (name = "main", worker = .w) ],
);
const w :Workerd.Worker = (
  compatibilityDate = "${COMPAT_DATE}",
  compatibilityFlags = [${flags.map((f) => JSON.stringify(f)).join(", ")}],
  modules = [
${modules}
  ],
);
`;
}

rmSync(OUT, { recursive: true, force: true });
for (const [variant, make] of Object.entries(variants)) {
  const files = make();
  // `workerd test` calls the `test` handler; it does nothing, so the run measures load and top-level evaluation.
  files["index.js"] = files["index.js"].replace("export default { ", "export default { test() {}, ");
  for (const [mode, flags] of [
    ["off", base(variant)],
    ["on", [...base(variant), "new_module_registry"]],
  ]) {
    const dir = join(OUT, variant, mode);
    for (const [path, content] of Object.entries(files)) {
      const full = join(dir, path);
      mkdirSync(join(full, ".."), { recursive: true });
      writeFileSync(full, content);
    }
    writeFileSync(join(dir, "wrangler.json"), JSON.stringify(config(`nmr-${variant}`, flags), null, 2) + "\n");
    writeFileSync(join(dir, "config.capnp"), capnp(files, flags));
  }
  console.log(variant);
}
run-workerd-cpu.py
# Runs `workerd test --experimental config.capnp` for each variant, flag off and on, and records the
# process CPU time (user + sys, all threads, from wait4) and wall time. CPU time depends less on machine load.
# Runs alternate off/on. Usage: python3 run-workerd-cpu.py [runs=21]
import json, os, subprocess, sys, time, statistics
from pathlib import Path

runs = int(sys.argv[1]) if len(sys.argv) > 1 else 21
here = Path(__file__).resolve().parent
workerd = (here / "node_modules/workerd/bin/workerd").resolve()
pkg = next((here / "node_modules/@cloudflare").glob("workerd-*/bin/workerd"))
root = here / "workers"

def once(d):
    t0 = time.perf_counter()
    p = subprocess.Popen([str(pkg), "test", "--experimental", "config.capnp"], cwd=d,
                         stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
    _, status, ru = os.wait4(p.pid, 0)
    wall = (time.perf_counter() - t0) * 1000
    if status != 0:
        raise SystemExit(f"{d}: status {status}: {p.stderr.read().decode()}")
    return {"cpu": (ru.ru_utime + ru.ru_stime) * 1000, "wall": wall}

def summ(xs):
    return {"median": round(statistics.median(xs), 1), "min": round(min(xs), 1), "max": round(max(xs), 1), "n": len(xs)}

variants = sys.argv[2:] or sorted(p.name for p in root.iterdir())
results = {}
for v in variants:
    once(root / v / "off"); once(root / v / "on")
    off, on = [], []
    for _ in range(runs):
        off.append(once(root / v / "off")); on.append(once(root / v / "on"))
    results[v] = {"off": off, "on": on}
    print(v, json.dumps({k: {"off": summ([r[k] for r in off]), "on": summ([r[k] for r in on])} for k in ("cpu", "wall")}), flush=True)
(here / "results-workerd-cpu.json").write_text(json.dumps(results, indent=2))

Local results (workerd test, 21 runs per mode, ms)

Variant CPU off: median (range) CPU on: median (range) CPU Δ Wall Δ
a0-empty-no-nodejs-compat 14.0 (13.2–16.0) 14.5 (12.4–16.0) +0.5 −0.9
a0-empty 15.1 (14.2–17.3) 25.8 (23.7–31.0) +10.7 +12.8
a1-single-1mb 23.7 (20.6–30.8) 35.8 (33.5–41.8) +12.1 +12.8
a2-single-6mb 76.0 (65.8–90.4) 103.3 (91.9–116.1) +27.3 +32.1
b1-modules-20 17.2 (15.2–21.1) 29.0 (26.6–33.9) +11.8 +18.7
b2-modules-100 26.3 (24.7–30.8) 39.3 (38.1–42.0) +13.0 +16.5
b3-modules-300 47.2 (44.6–61.2) 67.4 (63.3–78.9) +20.2 +36.2
b4-modules-100-lazy 27.4 (24.3–31.6) 31.3 (28.4–37.5) +3.9 +8.2
c1-wasm-data 158.5 (51.8–208.9) 155.0 (114.9–216.9) (−3.5) +16.9
d1-text-30 18.0 (14.5–23.8) 29.1 (25.8–36.1) +11.2 +16.2

Δ is median on minus median off. The machine had a high load average during the runs, so wall times have a wide
range (full ranges are in the results file). CPU time is less sensitive to load. For c1-wasm-data, CPU time is not
usable: Wasm compilation runs on background threads that the exit interrupts at different points.

What the numbers show:

  1. A fixed cost of about 10 ms with nodejs_compat. The empty Worker goes from 15.1 to 25.8 ms CPU. Without
    nodejs_compat it does not change. The Worker imports no node: module.
  2. A cost that grows with the evaluated JavaScript. Above the fixed cost: +1.4 ms for 1 MB, +16.6 ms for 6 MB, +9.5
    ms for 300 modules of 8 KB (2.4 MB). The module count alone has a small effect: 20 and 100 modules are within
    about 1 ms of the empty Worker.
  3. Text modules add nothing measurable above the fixed cost (30 modules, 300 KB: +11.2 ms).
  4. Modules that startup does not import cost less with the flag. b4-modules-100-lazy is +3.9 ms: the legacy
    registry pays about 12 ms for the 100 unused modules, and the new registry does not, which offsets most of the
    fixed cost.

wrangler check startup does not show the fixed cost

wrangler check startup (7 runs per mode) gives "Active" deltas of +22 ms (1 MB), +62 ms (6 MB), +29 ms (300 modules),
+34 ms (Wasm + Data) and +12 ms (30 Text modules), but 0 ms for the empty Worker. Wrangler 4.157.0 profiles only a
dynamic import() of the main module from a wrapper entry, after Miniflare is ready. Work that workerd does when it
loads the Worker is outside the profile. With the legacy registry, more of the work happens at load, so this tool
compares the two registries on different parts of startup. (#6544 describes a related gap.)

Questions

  1. Is a startup increase with new_module_registry expected? Is the fixed cost with nodejs_compat (built-in node:
    modules) expected even when the Worker imports no node: module?
  2. Does the production "Worker Startup Time" include work that the local workerd test run does not, for example
    compilation of Wasm or Data modules? Our largest production increase (+400 to +530 ms) is a Worker with a Wasm
    module and a Data module.
  3. Does the cost scale with module count, module size, Wasm modules or Text modules in production? Locally, it scales
    with the size of the evaluated JavaScript, not with module count.
  4. Is a change to this cost planned before the default on 2026-11-17, or after it? If not, is
    legacy_module_registry the recommended way to keep the current startup time, and is a fix for 🐛 Bug Report — Runtime APIs: a dynamic import() started in a request never settles if that request ends first (legacy module registry) #7779 on the legacy
    registry planned?

Related: #7779, #2372 (startup cost of unused modules with the legacy registry).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions