Skip to content
jshacks.dev
Node.js

The node --heap-prof Flag Explained

Find where Node.js 24 and 26 allocate memory with node --heap-prof: .heapprofile files, output flags, sampling interval, reading them in DevTools and limits.

9 min read
Summarize in AI
Flat illustration of folders syncing with a cloud bucket, with the Node.js, Cloudflare, Linux and DigitalOcean logos.

A Node.js process that keeps growing is one of the harder problems to debug, because the code that allocates memory and the code that holds on to it are often in different files. A heap profile narrows the search. It tells you which functions allocated the memory that is still alive, so you can start from the biggest owner instead of guessing. Node.js can produce one without installing anything: run node --heap-prof app.mjs, and when the process exits it writes a file with the extension .heapprofile that Chrome DevTools opens. This post covers the node --heap-prof flag on Node.js 24 and 26: what a sampling heap profile contains, how to produce one, the companion flags for the folder, file name and sampling interval, how to read the result, how it differs from a heap snapshot and a CPU profile, how to profile a server that never exits, and the mistakes that make a profile misleading. The flag is documented on the Node.js command line options page. A CPU profile is the sibling tool, covered in the --cpu-prof flag, and Node.js heap limits are in the --max-old-space-size flag. Sizes and file names vary on every run, so the samples show shapes rather than measurements.

What a sampling heap profile is

V8, the engine inside Node.js, has a sampling heap profiler. It does not record every allocation, which would slow the program to a crawl. Instead it picks allocations at a roughly regular byte interval and records the call stack that made each one. When the profile is written, it reports the sampled allocations that are still alive, grouped by the function that made them and arranged as a call tree.

Two consequences follow, and both matter when you read the result:

  • The profile shows memory that is retained at the end of the run, not everything that was ever allocated. A function that allocates a lot of short-lived garbage does not appear, because that garbage was collected.

  • The sizes are estimates built from samples. Large allocations are almost always caught, and small ones are scaled up statistically, so treat the numbers as a ranking, not an exact count.

That makes the profile a good answer to the question "what is holding my memory", and a poor answer to "how much garbage does this loop create".

Producing a profile

Start with a program that allocates something and keeps it.

cache.mjsJavaScript
const cache = new Map();

function remember(id) {
  cache.set(id, { id, payload: new Array(100).fill(id) });
}

function scratch() {
  // short-lived: not alive when the process exits
  return new Array(100).fill(0).map((_, i) => ({ i }));
}

for (let i = 0; i < 50_000; i++) {
  remember(i);
  scratch();
}

console.log("entries", cache.size);
Shell
node --heap-prof cache.mjs
ls *.heapprofile
Text
entries 50000
Heap.20261120.101530.4821.0.001.heapprofile

The program printed its usual output, and a file appeared in the working directory when the process exited. The default name has the date, the time, the process id, the thread id and a sequence number, so yours will differ. The file is JSON. It can be large for a program with a deep call tree, so watch the disk when you profile something that runs for a long time.

In the profile, remember carries the retained memory, because the Map still holds every object. scratch allocates the same order of memory in total but is mostly absent, because the arrays it creates were garbage by the time the process exited. That contrast is the whole point of the tool.

Controlling the output

Three companion flags control where the file goes, what it is called and how often samples are taken.

FlagMeaning
--heap-prof-dir=<folder>write profiles into this folder
--heap-prof-name=<file>use this file name instead of the generated one
--heap-prof-interval=<bytes>average number of bytes between samples, default 524288
Shell
node --heap-prof --heap-prof-dir=./profiles --heap-prof-name=cache.heapprofile cache.mjs
ls profiles
Text
entries 50000
cache.heapprofile

A fixed name is convenient in scripts but is overwritten by the next run, so use the generated names when you want to compare several runs. The interval is measured in bytes allocated, not in time. The default is 512 KiB (524,288 bytes), which keeps the overhead low. A smaller interval catches smaller allocations and produces a larger file and a slower program, and a program that retains only small objects may need it. The defaults and the flag list are on the command line options page.

Opening the file

Open Chrome DevTools, go to the Memory panel, choose to load a profile, and pick the .heapprofile file. The panel shows the allocation sampling view, which has three ways to look at it:

  • Heavy (bottom up) lists functions by the memory they allocated themselves, so the top rows are the biggest owners.

  • Tree (top down) shows the call hierarchy with the total for each branch, which tells you which entry point is responsible.

  • Chart draws the same data as a flame chart, where wide bars are large owners.

In the profile for the program above, the heavy view puts remember first, with the arrays and objects it created. Read self size to find the allocation site and total size to find which caller to change. A function with a large total and a small self size is a dispatcher, so look at what it calls.

Because the file is plain JSON, you can also read it from code. The top level has a head node, which is the root of the tree, and a list of samples. Each node carries a callFrame with the function name and location, a selfSize in bytes and its children.

read-profile.mjsJavaScript
import { readFile } from "node:fs/promises";

const profile = JSON.parse(await readFile("profiles/cache.heapprofile", "utf8"));

function walk(node, found = []) {
  found.push({ name: node.callFrame.functionName || "(anonymous)", size: node.selfSize });
  for (const child of node.children) walk(child, found);
  return found;
}

const nodes = walk(profile.head);
const top = nodes.sort((a, b) => b.size - a.size)[0];

console.log(typeof profile.head.selfSize, Array.isArray(profile.head.children));
console.log(top.name);
Text
number true
remember

The walk flattens the tree and sorts by self size. Here the largest single owner is remember, as the allocation site of everything the Map holds. The same idea scales to an automated check: after a load test, read the profile and fail the job if a function you did not expect is at the top. The node names for built-in code look like (program) or (garbage collector), and a real report should skip them.

Heap profile, heap snapshot and CPU profile

Three tools get confused. They answer different questions.

ToolAnswersCost
--heap-profwhich functions allocated the memory that is still alivelow, sampled
Heap snapshotwhat objects exist right now and what keeps each one alivehigh, pauses the process
--cpu-profwhich functions used the processor timelow, sampled

Use the heap profile first, because it is cheap and points at the allocation site. Use a heap snapshot when you need the retaining path of one object, for example which array or closure keeps a leaked request in memory. A snapshot is taken from DevTools through the inspector, or from code with the node:v8 module.

Profiling a server

A server does not exit on its own, and the profile is written only when the process ends. Run it with the flag, apply load, and stop it with a signal that lets it exit normally. A hard kill with SIGKILL writes nothing.

server.mjsJavaScript
import { createServer } from "node:http";

const sessions = new Map();
let nextId = 0;

const server = createServer((req, res) => {
  const id = nextId++;
  sessions.set(id, { id, trace: new Array(200).fill(req.url) });
  res.end(String(sessions.size));
});

server.listen(3000);

process.on("SIGINT", () => {
  server.close(() => process.exit(0));
});
Shell
node --heap-prof --heap-prof-dir=./profiles server.mjs

Send a few thousand requests with a load tool, then press Ctrl+C. The handler closes the server and calls process.exit(0), which triggers the profile write. The result points at the request handler, because the sessions map retains one record per request. That is a leak by construction, and the profile shows it without any source reading. Run the load for long enough that the retained memory dominates the start-up allocations, or the profile will mostly describe module loading.

For a process you cannot restart, connect DevTools through the inspector and start an allocation sampling recording from the Memory panel. It uses the same sampling profiler and produces the same kind of result.

Worker threads and child processes

Each thread gets its own profile. The flag applies to the main thread and to worker threads, and each writes a file whose name carries its own thread id. Child processes that inherit the flag, including through NODE_OPTIONS, write their own files too. A build tool that starts many processes can fill a folder quickly, so always combine the flag with --heap-prof-dir and clean the folder between experiments.

What a heap profile cannot show

  • Garbage. Objects that were collected before the process ended are not in the profile. To see allocation pressure, look at garbage collection time in a CPU profile or in trace output.

  • Retaining paths. The profile says who allocated, not who holds. A cache that never evicts and a listener that is never removed look the same: the allocating function is the owner. Use a snapshot to find the holder.

  • Native memory. Buffers outside the V8 heap, such as large Buffer allocations and native module memory, show up in process.memoryUsage() as external or array buffer memory, not in this profile.

  • Exact numbers. Sizes are estimates built from samples.

Making a profile trustworthy

  • Use realistic input. A tiny test run profiles the start-up cost.

  • Let the leak grow. A leak of a few kilobytes is invisible against a baseline of tens of megabytes, so drive enough load to make it dominant.

  • Profile the production build. Source transformation and extra logging change what allocates.

  • Repeat. Two profiles of the same load should agree on the top owners. If they do not, the run is too short.

  • Change one thing, then profile again. Confirm that the fix moved the memory.

Common mistakes

  • Expecting the profile to list temporary allocations, then concluding nothing allocates.

  • Reading total size as self size and fixing a dispatcher.

  • Killing a server with SIGKILL, so no profile is written.

  • Leaving --heap-prof in a start script, which adds overhead and writes a file on every run.

  • Committing .heapprofile files, which contain source paths and function names.

  • Raising --max-old-space-size to hide a leak instead of profiling it.

  • Setting the sampling interval so small that the profiler dominates the run.

Review and testing

Keep memory work reproducible. Write down the command, the load, the Node.js version and the machine, and store the profile outside the repository. After a fix, run the same load and compare the share of memory held by the function you changed. For regressions you want to catch automatically, run a fixed workload in CI, read the profile with a script like the one above and fail when an unexpected function owns the most memory. In review, ask for a before and after profile on any change that claims to reduce memory use.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.