A slow request does not necessarily spend its time executing JavaScript. It may be waiting for a database, a remote service, or available capacity. Collect evidence that identifies CPU work before optimizing the function that happens to look expensive during code review.
Start with a controlled Node.js 24 process and a hypothesis about the affected workload. The collection exercise below verifies that a CPU profile can be produced; the surrounding experiment design explains what additional evidence is needed before attributing request latency to a sampled function.
Confirm that CPU is the question to investigate
Start with the affected user operation and its observable symptom. Record latency distribution, throughput, error behavior, process CPU use, and relevant dependency timing under a defined workload. Determine whether the problem appears during startup, sustained traffic, or a specific input shape.
The Node.js profiling guide explains CPU profiling as a way to investigate where execution work occurs. The Node.js flame graph guide describes visualizing CPU work in stack form. Use that evidence for the CPU question without treating it as a full explanation of every request delay.
In a synthetic search service, slow requests may coincide with high CPU during result serialization. Another workload may show low CPU while waiting on the database. Those are different investigations. Avoid applying the same optimization simply because the endpoint name is the same.
Define the hypothesis narrowly enough to disprove. For example, a repeated transformation may consume a material portion of CPU work for a large result set. A profile that shows little execution in that path should change the next step.
Build a workload that represents the affected operation
Record runtime version, operating system, available CPU, memory limits, application build mode, dependency state, and input distribution. Preserve the source revision and lockfile identity. These inputs make later comparisons interpretable.
Use synthetic data with representative size and structure. A tiny result set may miss the serialization behavior you need to study, while a single enormous request may measure a workload the service does not support. State the intended range and include the problematic shape deliberately.
Separate initialization and warm-up from steady-state collection where the hypothesis concerns sustained service behavior. If cold startup is the actual problem, measure it explicitly instead of warming away the behavior under investigation.
Control dependencies sufficiently to reproduce the experiment, but retain their relevant effects. Replacing a database with an immediate in-memory result can isolate application CPU, while a separate integrated run is needed to understand the full user path. Label those experiments according to what they establish.
Capture a bounded profile using supported tooling
For Node.js 24, the built-in CPU profiler can write a .cpuprofile file when a controlled process exits. The Node CLI reference documents --cpu-prof, its output directory, and naming options. The following synthetic workload is a smoke test of collection, not a model of production request traffic or an optimization benchmark. Save it as profile-workload.mjs in a disposable directory:
import { createHash } from "node:crypto";
let total = 0;
for (let index = 0; index < 100_000; index += 1) {
const digest = createHash("sha256").update(`record-${index}`).digest();
total += digest[0];
}
process.stdout.write(`${total}\n`);
With an existing empty profiles directory, this command works in Bash and PowerShell:
node --cpu-prof --cpu-prof-dir=profiles --cpu-prof-name=baseline.cpuprofile profile-workload.mjs
The process should finish, print one integer, and leave a nonempty profile containing sampled execution data. Use a fresh output name or directory for another run so that an older successful capture cannot be mistaken for the new one. The integer is only a deterministic workload check; it is not a duration, throughput result, or measure of CPU utilization.
Open the profile in a compatible CPU-profile viewer and locate the hash workload and its descendants. Exact sampled frames and proportions depend on the Node build, machine, and interval. If the work is too brief to resolve clearly, increase the synthetic iteration count for collection testing, but do not use that change when comparing an application's baseline with its candidate.
Choose a CPU profiling mechanism documented for the deployed Node.js version and supported on the test platform. Verify the flags or tool configuration against that version before collection. Keep the profiling procedure in the controlled diagnostic environment rather than adding a broadly accessible runtime endpoint.
Bound the collection duration and output location. Profiles can reveal source structure, function names, and filesystem paths. Store them as controlled diagnostic artifacts and review access before sharing them outside the team.
Collect baseline request and resource measurements alongside the profile. Profiling can introduce overhead, so do not silently compare an instrumented candidate with an uninstrumented baseline and attribute every difference to the code change.
If collection fails, preserve the failure classification and fix the procedure. An empty or truncated profile is missing evidence, not proof that CPU work is negligible. Check that the captured process and collection interval correspond to the workload being exercised.
Interpret stacks without turning width into causality
Inspect the profile viewer's definitions for sampled duration, self time, inclusive time, and grouping. A wide parent stack can include time spent in descendants. A function appearing high in a stack does not establish that its own body is the expensive part.
Follow the expensive path to the work that actually runs. Look for repeated parsing, serialization, copying, allocation, or computation only when the samples support that hypothesis. Use source inspection to explain the mechanism rather than treating the visual shape as an explanation by itself.
Review native frames and garbage-collection activity where relevant. A JavaScript caller can trigger work outside its own visible body. Optimizing a small wrapper may leave the underlying allocation or native operation unchanged.
Sampling also has limits. Short operations may not appear consistently, and a profile represents the interval and workload observed. Repeat collection when the decision depends on a marginal difference, and investigate request waiting with appropriate tracing rather than forcing a CPU profile to account for it.
Change one mechanism and compare equivalent runs
Choose a change tied to the observed work. In the synthetic search service, eliminating an unnecessary transformation pass could be worth testing if the profile identifies that pass. Preserve output semantics, ordering, validation, and error behavior while changing the mechanism.
Run the same workload under comparable conditions for baseline and candidate. Use repeated measurements appropriate to the observed variance. Report the experiment's method and limits rather than publishing a percentage from one convenient run.
Check memory, throughput, errors, and user-visible latency alongside CPU. An optimization can trade computation for retained memory or improve one input shape while making another worse. Include the edge cases that constrain the application's actual contract.
If the improvement does not reproduce, keep the evidence and revise the hypothesis before expanding the change. For database-dominated requests, the query-plan guide may identify a more relevant next investigation. Keep the collection smoke test separate from that decision: producing a valid profile demonstrates that profiling works, while a representative before-and-after experiment is what can support an optimization claim.
Was this guide useful?
Your rating helps us prioritize clearer, more practical technical content.
Review diffs, run checks, and prepare the release in Arezgit.
Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.
Explore Arezgit