Skip to content

perf_hooks: add node:perf_hooks/pprof time profiler - #67779

Open
jsumners-nr wants to merge 1 commit into
nodejs:mainfrom
jsumners-nr:bundle-pprof
Open

jsumners-nr wants to merge 1 commit into
nodejs:mainfrom
jsumners-nr:bundle-pprof

Conversation

@jsumners-nr

Copy link
Copy Markdown

👋 This PR starts the process of natively supporting profiling in the runtime. This is a port of the @datadog/pprof module. This specific PR limits the implementation to profiling the CPU wall time. Heap and context/label sampling, and source map support are left for subsequent PRs.

@mcollina and I discussed this at the OpenJSF conference in 2025. We agreed that this sort of thing should be provided by the runtime. In support of that assertion, I instructed Claude to review the dependents of the @datadog/pprof module and generate a report of how it is used across the ecosystem. This is what it came up with:

Ecosystem Report

How @datadog/pprof is used across the JavaScript observability ecosystem

Data collected 2026-11-25. Sources:

  • the npm dependents list for @datadog/pprof;
  • weekly downloads from api.npmjs.org, for the last week;
  • the latest manifest of each package;
  • a search of each published tarball for the @datadog/pprof APIs it calls.

Scale

  • @datadog/pprof is downloaded about 17.6 million times a week.
  • npm counts 32 dependents and lists 28 of them. The list leaves out Datadog's own tracer, dd-trace, because it declares @datadog/pprof as an optionalDependency. At about 15.2 million downloads a week, dd-trace accounts for most of the module's installs.
  • Excluding Datadog's tracer and its forks, the listed dependents total about 1.3 million downloads a week. Grafana Pyroscope makes up most of that.

Who uses it

Use Package Weekly downloads APIs used
Vendor APM agent dd-trace (Datadog) 15,235,791 Time and heap profilers, sampling contexts, source maps, logger
Continuous profiling agent @pyroscope/nodejs (Grafana) 1,071,311 Time profiler with CPU time and contexts, heap profiler, source maps
Continuous profiling agent @polarsignals/pprof (Polar Signals) 180,021 Heap profiler, out-of-memory monitoring, source maps
Developer tooling @platformatic/flame (Platformatic) 27,937 Source maps, encoding; CPU and heap flame graphs
OpenTelemetry profiling SDK @coralogix/opentelemetry-profiling (Coralogix) 18,702 Time profiler with contexts and line numbers, heap profiler, source maps
Application runtime @platformatic/wattpm-pprof-capture, @platformatic/watt-extra (Platformatic) 9,410 + 1,201 Time profiler with line numbers, source maps
Embedded in a database or application platform harperdb, @harperfast/harper-pro (Harper) 7,394 + 4,445 Time profiler with line numbers, source maps, encoding
In-house framework @rsdk/profiling.common (R-Vision) 1,277 Time profiler with CPU time and contexts, heap profiler, source maps
HTTP profiling endpoints flamegraph-middleware, express-pprof-middleware (Tesla) 1,267 + 33 time.profile(), heap profiler, encoding
OpenTelemetry resource bridge @beacon-observability/profiler-nodejs, @cloudcare/profiler-nodejs 387 + 9 Time profiler with CPU time and contexts, heap profiler
CLI wrapper pprof-it 178 Time profiler with line numbers, heap profiler, source maps

The remaining dependents each get fewer than 100 downloads a week:

  • republished forks of dd-trace (dd-trace-andreas, dd-trace-sbs-dl, @e-one/dd-trace, trace-ts);
  • forks of Pyroscope's agent (@rudderstack/pyroscope-nodejs, rudderstack-pyroscope-nodejs, @popfendicollars/pyroscope-nodejs);
  • small personal or project packages (@beincom/node-profile, @cornie-js/backend-monitoring, @yoniplayground/o11y, @swapnil454/tracepilot, perf-skill);
  • @chatlayer/tracer, which still pins the obsolete ^0.1.3.

Observations

  • It's the de facto Node.js profiler, beyond Datadog. Competing vendors ship it inside their own agents: Grafana Pyroscope, Polar Signals and Coralogix. So do runtimes and platforms (Platformatic, Harper) and tools that expose pprof endpoints. None of the other major vendors checked has a replacement:

    • Sentry ships its own native addon, @sentry/node-cpu-profiler.
    • Elastic's agents have no Node.js profiler.
    • OpenTelemetry has no Node.js profiler of its own. Its eBPF profiler's design doc for reading Node.js thread context cites DataDog/pprof-nodejs as prior art.
  • Everyone depends on one native addon. Each consumer inherits its prebuilt binaries, nan, and V8 workarounds that are specific to each Node.js major version. Several consumers pin exact versions, for example:

    • @pyroscope/nodejs pins 5.14.4;
    • @platformatic/flame and harperdb pin 5.15.1;
    • Pyroscope's forks pin 5.4.1.

    So the ecosystem gets fixes and new Node.js support unevenly.

  • The wall time profiler is the common core. Almost every agent and tool calls time.start()/time.stop() or time.profile(), then encodes the result as pprof. That's the part node:perf_hooks/pprof provides.

  • Many consumers also use features this port leaves out. The tarball search shows how often each one appears:

    • source maps (SourceMapper): most dependents;
    • the heap profiler: Pyroscope, Polar Signals, Coralogix, R-Vision, the middleware packages and pprof-it;
    • sampling contexts (withContexts, useCPED, time.setContext): Datadog, Pyroscope, Coralogix, R-Vision and Beacon.

    These features decide how many consumers could move to the core module without also keeping the addon.

A few caveats:

  • npm reports 32 dependents but lists only 28. I couldn't get the other four: npm's pagination returns nothing past the first page.
  • I matched API names in the published code, so it shows which features a package calls, not how heavily it uses them. The Harper counts in particular include bundled code.
  • @cloudcare/profiler-nodejs gives opentelemetry-js-contrib as its repository URL and has the same description as @beacon-observability/profiler-nodejs. It's probably a copy, not an OpenTelemetry package.

Additionally, Sentry has their own native module to accomplish the same goal:

I have reviewed all of the JavaScript code in this PR, mainly coercing useful jsdoc into the code. Everything seems reasonable to me. But I am unable to provide insight into the C++ code, as my knowledge there is basically zero. The C++ code was heavily rewritten, though. The original upstream code relied on Nan and node-gyp. By directly integrating this functionality into core, we are able to skip those requirements. I asked Claude for a description of what it changed, and it reported:

C++ Port Details

It was modified heavily. The C++ is a port of the upstream design and algorithms, rewritten against Node.js internals; very little was copied as is. I compared it with upstream at the commit it was ported from, 3905f38, just now.

Size and overlap

  • Size: upstream has 2,639 lines across five files (wall.cc, wall.hh, thread-cpu-clock.{cc,hh}, translate-time-profile.cc). The port has 1,660 lines across eight files (src/node_pprof.{cc,h} and src/pprof/).
  • Verbatim overlap: I stripped comments, whitespace, includes and lone braces, then compared the distinct lines. Only 75 of the port's 728 distinct lines (about 10%) also appear upstream.
  • What those shared lines are: mostly small pieces where there's one natural way to write it:
    • sigaction setup and its flags (SA_RESTART | SA_SIGINFO | SA_ONSTACK);
    • std::atomic_signal_fence calls;
    • Mach/Windows thread-time API calls;
    • a std::lock_guard and a set of profilers;
    • method names kept for compatibility, such as v8ProfilerStuckEventLoopDetected.

What changed

  • No nan or node-gyp. Upstream wall.cc has 75 Nan::/NAN_ uses; the port has none. WallProfiler is a BaseObject registered with SetProtoMethod as the internal pprof binding. Its lifetime is tied to the realm's cleanup, so workers and process exit tear it down.
  • Restructured. Upstream's single wall.cc was split up:
    • sigprof_handler.{h,cc}: the signal handler;
    • cpu_clock.{h,cc}: the thread CPU clocks;
    • time_profile.{h,cc}: sample attribution, with no dependency on V8, so cctest can test it;
    • node_pprof.{h,cc}: the binding.
  • Rewrites:
    • GetContextsByNode() became AttributeSamples(), a function that only takes and returns data.
    • The translation of V8 profiles now returns flat tables of typed arrays, instead of a tree of JavaScript objects.
  • Removed:
    • sampling contexts, CPED and AsyncContextFrame reads (upstream wall.cc mentions contexts 133 times);
    • async IDs, GC callbacks, metrics, and the per-Node-major #if branches.
  • Fixes and hardening:
    • macOS: upstream calls mach_thread_self(), which adds a reference to the thread port on each call and never releases it. The port uses pthread_mach_thread_np(pthread_self()), which doesn't (src/pprof/cpu_clock.cc:143-144).
    • Signal-handler chaining handles more cases: SA_SIGINFO vs sa_handler, SIG_DFL/SIG_IGN, and refusing to chain to itself. It also makes no V8 calls inside the handler.
    • MonotonicNowMicros() reimplements V8's TimeTicks::Now(). V8's base headers aren't available to node_lib, and upstream redeclares V8's symbols, which isn't acceptable in core.

Why the upstream headers stay

Because the logic is derived from upstream, the files keep the Apache-2.0 copyright headers, with a "Modified for inclusion in Node.js core" notice and a pinned link to what each was ported from. tools/license-builder.sh adds the license to LICENSE. That attribution is required whatever the amount of verbatim text.

The overlap figure is a rough line-level measure, not a formal similarity analysis, and I didn't compare the files line by line.


Claude Code Description

Adds an experimental node:perf_hooks/pprof module. It collects wall time profiles of the current thread and encodes them in the pprof format, so they can be used with the pprof command-line tool and continuous profiling services without a native addon. Loading the module emits an ExperimentalWarning; there is no flag.

Where it comes from

  • Wall time profiler: ported from @datadog/pprof (Apache-2.0).
    • The native profiler is in src/node_pprof.cc and src/pprof/, built on Node.js internals instead of nan and node-gyp.
    • The JavaScript is in lib/internal/perf/pprof/.
  • pprof protobuf encoder: ported from pprof-format (MIT). Only the encoding half is included.
  • Both licenses are added to LICENSE through tools/license-builder.sh.
  • Each ported file keeps its upstream copyright header and links to the source it was ported from, pinned to the commit that was ported.

API

  • time.start([options]), time.stop([restart]) and time.isStarted().
  • time.profile([options]), which profiles for durationMillis and can be stopped early with an AbortSignal.
  • time.v8ProfilerStuckEventLoopDetected() and time.constants.
  • encode(profile) and encodeSync(profile), which return a gzip-compressed pprof Buffer.
  • The option names of @datadog/pprof are kept (intervalMicros, durationMillis, lineNumbers, collectCpuTime, workaroundV8Bug) so users can migrate easily.

On POSIX systems, collectCpuTime attributes the thread's CPU time to samples by intercepting the SIGPROF signals of V8's sampler. The same interception works around a V8 bug that can leave the CPU profiler stuck when it is restarted. If restarting after that bug fails, stop(true) still returns the profile and leaves the profiler stopped.

The profiler owns its own v8::CpuProfiler, so it can run alongside v8.startCpuProfile() and the inspector's Profiler domain. It refuses to start while a startup snapshot is being built.

Not included

  • The heap profiler.
  • Sampling contexts and labels.
  • Source map support.

Tests

  • test/parallel/test-perf-hooks-pprof-*.js cover:
    • the module and its warning, and option validation;
    • the profile content, CPU time, line numbers and restarts;
    • recovery from a stuck V8 profiler;
    • encoding, and the normalizer and serializer, using synthetic profiles;
    • workers, including workers terminated while profiling;
    • running alongside v8.startCpuProfile() and the inspector;
    • exiting without stopping the profiler, and rejection while a snapshot is built.
  • test/cctest/test_pprof.cc covers sample attribution, the thread CPU clock and signal chaining.
  • test/common/pprof.js is a minimal pprof decoder, written independently of the encoder, so that tests check the encoded bytes. It also provides pprofTestBusyLoop(), a loop bounded by CPU time rather than wall time, so that it gets about as many samples on a loaded machine as on an idle one.
  • V8's sampler gives some of a function's samples to its callers, more so under load. The tests therefore check that a profiled function is present and that the total CPU time adds up, not how the samples are split between frames.

Docs

  • A pprof API section in doc/api/perf_hooks.md.
  • A type-map.json entry for pprof.Profile.

🤖 Generated with Claude Code

Add an experimental node:perf_hooks/pprof module that collects wall
time profiles of the current thread and encodes them in the pprof
format, so that they can be consumed by the pprof command-line tool and
continuous profiling services without a native addon.

The wall time profiler is ported from @datadog/pprof (Apache-2.0): the
native profiler now lives in src/node_pprof.cc and src/pprof/ on top of
Node.js internals instead of nan, and the JavaScript in
lib/internal/perf/pprof/. The pprof protobuf encoder is ported from the
pprof-format package (MIT). Both licenses are added to LICENSE.

Profiles can optionally attribute thread CPU time to samples on POSIX
systems, by intercepting the SIGPROF signals of V8's sampler, which is
also used to work around a V8 bug that can leave the profiler stuck
when it is restarted. The heap profiler, sampling contexts and source
map support of @datadog/pprof are not included.

The module emits an ExperimentalWarning when loaded.

Assisted-by: Claude Code
Signed-off-by: James Sumners <jsumners@newrelic.com>
@jsumners-nr
jsumners-nr marked this pull request as ready for review November 25, 2026 15:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant