How to Take a Node.js Heap Snapshot: Every Method

Signal, writeHeapSnapshot, near-heap-limit, inspector and DevTools, with measured pauses, file sizes and peak memory, plus Kubernetes and secrets.

By · · 12 min read

Illustration for How to Take a Node.js Heap Snapshot: Every Method

The Node service's RSS climbs every hour, a restart is scheduled, and you want the heap on disk first. The quickest way that needs no code change is to start Node with --heapsnapshot-signal=SIGUSR2, then run kill -USR2 <pid> when memory is high: Node writes a .heapsnapshot file into its working directory. If you can change code, call v8.writeHeapSnapshot(). If the process will crash before you are awake, start it with --heapsnapshot-near-heap-limit=1. Everything below was run on Node v25.1.0 (V8 14.1) on a 10-core Apple laptop. Version notes come from the nodejs.org API docs. Once the file exists, the Heap Snapshot Analyzer reads it in your browser without uploading it.

Every way to take one, and what each needs

MethodNeeds a restart?Needs code?Best for
--inspect + Chrome DevTools Memory panelyes, unless you send SIGUSR1noa dev box or a tunnel you control
--heapsnapshot-signal=<sig> + killyes, oncenoproduction, on demand
v8.writeHeapSnapshot([file[, options]])noyesan admin route, a test, a threshold
--heapsnapshot-near-heap-limit=<n>yes, oncenoa crash you cannot catch by hand
inspector module, HeapProfiler.takeHeapSnapshotnoyesstreaming chunks to a custom sink
DevTools Memory panel in a browser tabnonofront-end leaks

The demo service for every number on this page holds sessions in a Map that never evicts. Each session has an email and a token parsed from JSON and a 512-character base64 payload. Its source is in the test fixtures, and the session count sets the heap size.

Signal: --heapsnapshot-signal

node --heapsnapshot-signal=SIGUSR2 server.js
kill -USR2 <pid>

The flag, added in v12.0.0, installs a handler for the signal you name. It is off by default. The run printed nothing, and the file appeared as Heap.20261123.085552.87825.0.001.heapsnapshot, which reads as date, time, pid, thread id and sequence number.

  • Pick SIGUSR2, not SIGUSR1. SIGUSR1 is the signal Node already uses to start the inspector (node --help lists --disable-sigusr1 for that listener), so reusing it mixes two features.
  • The file lands in the process's working directory, not your shell's. In a container that is usually the app directory on the image's writable layer.

While the 200,000-session process wrote its 175.7 MB snapshot, a 10 ms timer inside it measured the longest gap between ticks. The gaps were 1,723, 1,820 and 2,039 ms over three runs. That gap is how long every request on that process waited.

Code: v8.writeHeapSnapshot()

const v8 = require('node:v8');
const file = v8.writeHeapSnapshot();            // returns the file name it wrote
v8.writeHeapSnapshot('/dumps/api.heapsnapshot', {
  exposeInternals: false,        // default false: hide V8 internals
  exposeNumericValues: false,    // default false: numbers in artificial fields
});

writeHeapSnapshot was added in v11.13.0. The options object arrived in v19.1.0, and since v18.0.0 a write failure throws instead of failing quietly. The docs give the default name as Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot, with hyphens. On v25.1.0 the call returned dotted names like the signal's, Heap.20261123.085516.87563.0.001.heapsnapshot. Scripts that glob for snapshots should match both. Every file was created with mode -rw-------.

What the options did on the 50,000-session heap:

CallFile sizeWrite time
v8.writeHeapSnapshot(), median of three47,372,781 bytes397 ms
{ exposeInternals: true }47,362,924 bytes359 ms
{ exposeNumericValues: true }53,109,066 bytes (+12%)391 ms

exposeNumericValues is the one worth turning on when you need the values of numbers. The Chrome DevTools docs say plain snapshots do not capture non-string values such as numbers. exposeInternals made no measurable difference on this heap.

A snapshot covers one isolate. The v8 docs state that a snapshot from the main thread has nothing about worker threads, and the reverse. To capture a worker, call writeHeapSnapshot() inside it, or use worker.getHeapSnapshot() from the parent. v8.getHeapSnapshot() returns the same data as a readable stream, for piping somewhere other than local disk.

Automatic: --heapsnapshot-near-heap-limit

node --max-old-space-size=512 --heapsnapshot-near-heap-limit=1 server.js

The flag (v15.1.0 and v14.18.0) writes up to max_count snapshots as the heap approaches its limit. It stopped being experimental in v25.4.0, v24.13.1 and v22.22.1, so on the 25.1.0 build tested here it was still experimental. The docs warn that it is best effort and that it costs memory both inside and outside the V8 heap. They also say Node "will adjust the V8 heap to accommodate the additional V8 heap memory overhead", and the runs showed what that adjustment means in practice.

The demo leaked 100 sessions every 5 ms under --max-old-space-size=64, three runs each way:

RunSnapshots writtenDied afterPeak RSS
no flag (3 runs)06.76 to 6.88 s236 to 246 MiB
--heapsnapshot-near-heap-limit=3, run 11 (119,767,877 bytes)38.8 s806 MiB
--heapsnapshot-near-heap-limit=3, run 23 (1.15 GB together)82.6 s2,192 MiB
--heapsnapshot-near-heap-limit=3, run 33 (1.11 GB together)75.2 s1,705 MiB

With the flag, the 64 MB process grew to about 640 MB of heap before V8 gave up. Its peak resident memory went up to nine times that of the runs without it. Each extra snapshot captured a bigger heap than the last, so later files were larger. With a faster leak (2,000 sessions per tick) the same flag wrote 1, 3 and then 0 snapshots. The run that wrote none died 1.2 seconds in.

Two rules follow. In a container, use =1: one snapshot is the evidence, and later ones mostly burn memory against the cgroup limit. Leave headroom above --max-old-space-size, or the kernel kills the process mid-write and you get neither the crash message nor the file. The flag can also be set from code with v8.setHeapSnapshotNearHeapLimit(limit) (v18.10.0 and v16.18.0, stable since v24.0.0 and v22.17.0). That call does nothing if the command-line flag is already set.

DevTools: --inspect, --inspect-brk and chrome://inspect

node --inspect server.js          # Debugger listening on ws://127.0.0.1:9229/<uuid>
node --inspect-brk script.js      # same, paused before the first line
node --inspect-wait server.js     # waits for a debugger before running (v22.2.0, v20.15.0)

Open chrome://inspect, click inspect under the target, go to the Memory panel, choose Heap snapshot and click Take snapshot. The Chrome docs say every snapshot starts with a garbage collection and shows only objects reachable from the global object, so what you see is retained memory, not garbage. --inspect-brk suits a short script that would otherwise exit before you attach. For a process already running without the flag, kill -USR1 <pid> opens the inspector, unless it was started with --disable-sigusr1.

The inspector is a remote code execution port. The CLI docs say binding it to a public IP or 0.0.0.0 "allows external hosts to connect to the inspector and perform a remote code execution attack". node --inspect=0.0.0.0:9230 started without complaint here and printed Debugger listening on ws://0.0.0.0:9230/..., so nothing stops the mistake. The Node debugging guide recommends ssh tunnels instead; the nodejs.org Learn pages also warn that any local process can reach a 127.0.0.1 inspector. For Kubernetes, keep the default 127.0.0.1 and use kubectl port-forward pod/api 9229:9229.

In-process: the inspector module

const { Session } = require('node:inspector/promises');   // v19.0.0, experimental API
const fs = require('node:fs');
const session = new Session();
session.connect();
const fd = fs.openSync('api.heapsnapshot', 'w');
session.on('HeapProfiler.addHeapSnapshotChunk', (m) => fs.writeSync(fd, m.params.chunk));
await session.post('HeapProfiler.takeHeapSnapshot', null);
session.disconnect();
fs.closeSync(fd);

This is the docs' example, and it is the route to use when you want the chunks somewhere other than a local file. On the 50,000-session heap it delivered 46 chunks, totalling 47,466,657 bytes, in 555 ms, against 397 ms for writeHeapSnapshot. It blocks the event loop the same way. The file it created was -rw-r--r-- under the default umask, so set the mode yourself: unlike writeHeapSnapshot, it will not create the file 0600.

A browser tab

The same Memory panel works on a page. Open DevTools, then Memory, Heap snapshot, Take snapshot, and save the result as a .heapsnapshot file. For a leak, take one snapshot, repeat the suspect action a few times, and take a second. DevTools' Comparison view and the analyzer's constructor counts both read the difference. Detached DOM nodes are the browser-specific signature, covered in the heap and thread dump analysis guide.

What a snapshot costs: pause, file and memory

v8.writeHeapSnapshot() on four heap sizes, median of three runs each, peak RSS from process.resourceUsage().maxRSS before and after the call:

SessionsHeap usedSnapshot fileEvent loop blockedPeak RSS before, after
0 (bare process)3.6 MiB4,959,893 bytes54 ms43.8, 87.0 MiB
50,00038.3 MiB47,372,781 bytes397 ms141.5, 327.7 MiB
200,000141.9 MiB175,710,457 bytes1,771 ms341.9, 969.2 MiB
400,000280.2 MiB348,419,377 bytes3,449 ms501.8, 1,469.0 MiB
Bar chart of Node heap snapshot cost at three heap sizes: 38.3, 141.9 and 280.2 MiB of heap wrote files of 45.2, 167.6 and 332.3 MiB, blocked the event loop for 397 ms, 1,771 ms and 3,449 ms, and raised peak RSS by 186, 630 and 967 MiB
Bar chart of Node heap snapshot cost at three heap sizes: 38.3, 141.9 and 280.2 MiB of heap wrote files of 45.2, 167.6 and 332.3 MiB, blocked the event loop for 397 ms, 1,771 ms and 3,449 ms, and raised peak RSS by 186, 630 and 967 MiB

Three planning figures come out of the table:

  • File size is about 1.2 times heap used on this workload, and the docs promise no fixed ratio. Even an empty process writes a 4.7 MiB file.
  • The pause is roughly 12 ms per MiB of heap. It is synchronous, so a 1 GiB heap means a pause of more than ten seconds. Health checks fail during it.
  • Peak memory rose by 3.5 to 4.9 times the heap in use, more than the v8 docs' "about twice the size of the heap". This is the observed figure from one macOS build. Treat the docs' figure as a floor, not a budget, and leave room above the container limit.

Docker and Kubernetes

kubectl exec -n shop api-7d9f -c app -- kill -USR2 1
kubectl exec -n shop api-7d9f -c app -- ls -l /app
kubectl cp shop/api-7d9f:/app/Heap.20261123.085552.1.0.001.heapsnapshot ./api.heapsnapshot -c app
  • PID 1 and signals. The pid_namespaces man page says other processes can only send PID 1 the signals it has a handler for. The --heapsnapshot-signal flag installs that handler, so kill -USR2 1 reaches node. A shell wrapper running as PID 1 has no such handler, so make the entrypoint exec node or signal node's own pid.
  • A writable path. With a read-only root filesystem, chdir to a mounted volume before starting, or use writeHeapSnapshot('/dumps/...'). A memory-backed emptyDir counts against the container's memory limit, which the snapshot is already straining.
  • Copying out. The kubectl cp reference says the tar binary must be in the image. In an image without tar, stream the file with kubectl exec ... -- cat file > local, or mount a volume you can reach.
  • Probes. A 3.4 second pause on a 280 MiB heap can fail a liveness probe whose timeout is 1 second, and the kubelet then restarts the pod. Relax the probe before snapshotting a big heap.

A snapshot is a copy of the heap's strings

The 50,000-session snapshot was searched with grep -o and nothing else. It held all 50,000 distinct demo emails and all 50,000 tokens in plain text, plus the absolute path of the script that created them. Strings are stored in the file's string table as written. Whatever your process held, including API keys, JWTs, request bodies and customer data, is readable in the snapshot.

Handle it like a database export: keep the 0600 mode, move it over an encrypted channel, delete it from the pod, never attach it to a ticket, and analyse it locally. The Heap Snapshot Analyzer parses in the tab and sends nothing. Dropped onto that 50,000-session file, it reported 307,455 nodes · 798,577 edges · 40.1 MiB shallow and put 50,001 × Session at the top of its constructors table, which names the leak in one line.

Profiling allocations instead

A snapshot answers what is retained now. For which code allocates, --heap-prof starts V8's sampling heap profiler at launch and writes a .heapprofile on exit. The --heap-prof flags were added in v12.4.0 and became stable in v22.4.0 and v20.16.0. Their options are --heap-prof-dir, --heap-prof-name and --heap-prof-interval (default 512 KiB). The profile reports sampled allocations still alive when it is written. A test script whose array had already become garbage at exit wrote 0 samples. When the array was still referenced, the same script wrote 36 samples at the default interval and 17,879 at --heap-prof-interval=1024. The Node docs describe sampling as cheap enough for production, unlike the Allocation Timeline, which they advise against using there.

Which method for which situation

SituationUse
Production process, memory climbing now--heapsnapshot-signal=SIGUSR2 set in advance, then kill -USR2
No flag set, can deploy codev8.writeHeapSnapshot() behind an authenticated admin route
The crash happens at night--heapsnapshot-near-heap-limit=1, with memory headroom
Local debugging, want the UI--inspect, chrome://inspect, Memory panel
Short script that exits fast--inspect-brk
Worker thread leakingwriteHeapSnapshot() inside the worker
Front-end leakbrowser DevTools Memory panel, two snapshots
Which code allocates, not what is retained--heap-prof

The JVM equivalent of all of this is in how to take a Java heap dump. It has the same trade-offs, with a full GC inside the pause. When the complaint is a slow page rather than memory, capture the network side with how to capture a HAR file. If the service is Go, use how to collect Go pprof profiles. When a socket is the suspect, how to capture network packets covers the wire.

Tools for this job

  • Heap Snapshot Analyzer: drop the .heapsnapshot from Node or Chrome. It shows node types, constructors by shallow size, duplicate strings and detached DOM nodes, parsed locally.
  • Java Heap Dump Analyzer: the same histogram view for a JVM's .hprof when the leak is on the Java side of the system.

For reading what you captured, the heap and thread dump analysis guide covers leak signatures and the two-snapshot comparison.

Frequently asked questions

Does taking a heap snapshot stop my Node server?

Yes, for the whole write. The v8 docs call it synchronous, and it blocks the event loop. On Node v25.1.0, a 141.9 MiB heap blocked for about 1.8 seconds and a 280.2 MiB heap for about 3.4 seconds, so expect failed health checks and queued requests.

How much memory does a heap snapshot need?

The Node docs say about twice the heap. On v25.1.0, peak resident memory rose by 3.5 to 4.9 times the heap in use across three heap sizes. Budget at least that much headroom below the container limit, or the kernel may kill the process before the file is complete.

Why did --heapsnapshot-near-heap-limit not write a file?

The docs promise only best effort. In testing, a fast leak killed one run before any snapshot. Node also raises the heap limit to make room for the snapshot, so a container can be OOM-killed by the kernel first. Use a count of 1 and leave memory headroom.

Can I open a Node heap snapshot in Chrome?

Yes. The v8 docs say the file is intended for tools such as Chrome DevTools, and the Memory panel loads it. The format is V8's own JSON, which the same docs call undocumented and liable to change between V8 versions, so a very old file may not load in a much newer browser.

Sources and further reading

  • Command-line API, OpenJS Foundation. --heapsnapshot-signal, --heapsnapshot-near-heap-limit, the --inspect family and --heap-prof, with the versions they were added in.
  • V8 module, OpenJS Foundation. writeHeapSnapshot, its options, the "twice the size of the heap" warning and setHeapSnapshotNearHeapLimit.
  • Inspector module, OpenJS Foundation. The HeapProfiler.takeHeapSnapshot example with node:inspector/promises.
  • Using Heap Snapshot, OpenJS Foundation. The four capture routes and the production caveats.
  • Record heap snapshots, Chrome for Developers. The Memory panel, the GC before each snapshot and Expose internals.
  • kubectl cp, Kubernetes. Copying files from a pod and the tar requirement.
  • pid_namespaces(7), Linux man-pages project. Which signals reach PID 1 in a container.

Browse all tools