Sub topic 12
Memory in Node.js: Heap Limits and Monitoring
This chapter assumes you already know how reachability and mark-and-sweep work, how V8 splits the heap into young and old generations, and how to read a heap snapshot in Chrome DevTools. Here those ideas meet a running server. A Node.js process has a fixed heap limit, and its memory includes more than the JavaScript heap. Watching the right numbers tells you whether you have a leak or just a busy process.
What a Node.js Process Uses Memory For
A Node.js process is a native program that embeds V8. Its memory comes from several places, and only some of it is managed by the garbage collector.
- The V8 heap holds JavaScript objects, strings, closures, and compiled code. The garbage collector manages this memory.
- External memory is memory allocated outside the V8 heap and tied to JavaScript objects.
BufferandArrayBuffercontents live here. The small JavaScript wrapper object sits on the heap and the bytes sit outside it. - Native memory covers everything else: the Node.js runtime, libuv, thread stacks, native addons, and the allocator's own overhead.
The operating system sees the sum of all of this as the resident set size (RSS), which is the physical memory currently mapped to the process.
Reading process.memoryUsage()
process.memoryUsage() returns a snapshot of these numbers in bytes.
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(1);
const usage = process.memoryUsage();
for (const [key, value] of Object.entries(usage)) {
console.log(`${key.padEnd(12)} ${toMB(value)} MB`);
}| Field | Meaning | What growth usually means |
|---|---|---|
| `rss` | Total physical memory held by the process | Anything: heap, buffers, native leaks, or fragmentation |
| `heapTotal` | Memory V8 has reserved for its heap | V8 expanded the heap to make room |
| `heapUsed` | Heap memory occupied by objects | Live JavaScript objects, or garbage not yet collected |
| `external` | Memory of C++ objects bound to JavaScript objects | Buffers, typed arrays, or native resources |
| `arrayBuffers` | The part of `external` used by `ArrayBuffer` and `Buffer` | Binary data being retained |
heapUsed includes garbage that has not been collected yet, so it rises and falls in a sawtooth pattern. A single reading tells you little. A leak shows up as a rising floor: the lowest point after each major collection keeps climbing.
The Heap Limit
V8 caps the size of its heap. The cap applies mainly to the old generation, because that is where long-lived and leaked objects end up. When a major collection cannot free enough memory to satisfy an allocation below the cap, V8 aborts the process with an error like this:
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memoryThis is a crash, not an exception. You cannot catch it with try/catch, and process.on("exit") handlers do not get a chance to clean up.
The default limit depends on the Node.js version, the CPU architecture, and the memory available to the machine. Don't guess it. Ask V8:
const v8 = require("node:v8");
const stats = v8.getHeapStatistics();
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(0);
console.log(`heap size limit: ${toMB(stats.heap_size_limit)} MB`);
console.log(`used heap size: ${toMB(stats.used_heap_size)} MB`);
console.log(`total available: ${toMB(stats.total_available_size)} MB`);Changing the Limit
Two flags control heap sizing:
# Old-generation limit in megabytes
node --max-old-space-size=4096 app.js
# Size of each young-generation semi-space in megabytes
node --max-semi-space-size=64 app.js
# Same settings through the environment, useful in containers and npm scripts
NODE_OPTIONS="--max-old-space-size=4096" node app.jsRaising --max-old-space-size is reasonable when a process really needs a large working set, for example a build tool loading a big dependency graph. It does not fix a leak. A leaking process with a 4 GB limit crashes later than one with a 2 GB limit, and it spends more time in long major collections on the way there.
A larger --max-semi-space-size can help programs that allocate many short-lived objects. Fewer objects survive long enough to be promoted, so scavenges run less often. The cost is more memory per young-generation space.
Containers and the Limit
In a container, the heap limit and the container's memory limit are separate. If V8 sizes its heap from the host machine's memory instead of the container's, the kernel's out-of-memory killer can terminate the process before V8 ever reports a heap error. You then see the process exit with signal SIGKILL (often exit code 137) and no JavaScript stack trace.
Recent Node.js versions take container memory limits into account when choosing a default, but older versions may not. The safe practice is to set the limit explicitly and leave headroom for everything outside the heap.
| Container memory limit | Reasonable `--max-old-space-size` | Headroom left for |
|---|---|---|
| 512 MB | 384 | Young generation, buffers, native memory |
| 1 GB | 768 | Same, plus larger buffer workloads |
| 2 GB | 1536 | Same |
These numbers are a starting point. A service that handles large file uploads or streams needs more room for external memory and a smaller heap share.
Monitoring Memory Over Time
A leak is a trend, so log memory periodically and look at the trend. The script below logs usage every five seconds and deliberately leaks so you can watch the floor rise.
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(1);
function logMemory() {
const { rss, heapUsed, heapTotal, external } = process.memoryUsage();
console.log(
`${new Date().toISOString()} rss=${toMB(rss)} heapUsed=${toMB(heapUsed)} ` +
`heapTotal=${toMB(heapTotal)} external=${toMB(external)}`
);
}
const monitor = setInterval(logMemory, 5000);
monitor.unref(); // do not keep the process alive just for monitoring
// Simulated leak: an unbounded cache that is never trimmed
const cache = [];
setInterval(() => {
for (let i = 0; i < 10_000; i++) {
cache.push({ id: i, payload: "x".repeat(100) });
}
}, 200);monitor.unref() matters in real code. Without it, a monitoring timer keeps the event loop alive and stops the process from exiting when its real work is done. That is the forgotten-timer leak from an earlier chapter, applied to your own tooling.
In production, send these numbers to your metrics system instead of the console, and alert on sustained growth of heapUsed or rss over hours rather than on single spikes.
Watching Garbage Collection Itself
Memory numbers show what is retained. GC timing shows what retention costs. Node.js reports each collection as a performance entry:
const { PerformanceObserver, constants } = require("node:perf_hooks");
const kinds = {
[constants.NODE_PERFORMANCE_GC_MINOR]: "minor",
[constants.NODE_PERFORMANCE_GC_MAJOR]: "major",
[constants.NODE_PERFORMANCE_GC_INCREMENTAL]: "incremental",
[constants.NODE_PERFORMANCE_GC_WEAKCB]: "weakcb",
};
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const kind = kinds[entry.detail.kind] ?? "other";
console.log(`gc ${kind} ${entry.duration.toFixed(2)} ms`);
}
});
observer.observe({ entryTypes: ["gc"] });
// Generate some garbage so collections happen
let keep = [];
setInterval(() => {
keep = Array.from({ length: 100_000 }, (_, i) => ({ i }));
}, 100);For a quick look without code changes, node --trace-gc app.js prints one line per collection with its type, heap size before and after, and duration. If major collections get more frequent and free less memory each time, the old generation is filling with live objects. That is the signature of a leak heading toward the heap limit.
Capturing Heap Snapshots in Node.js
Once monitoring shows a rising floor, take heap snapshots and compare them in Chrome DevTools, using the same comparison workflow as in the browser.
const v8 = require("node:v8");
const file = v8.writeHeapSnapshot();
console.log(`heap snapshot written to ${file}`);You can also trigger snapshots without editing code:
# Write a snapshot when the process receives SIGUSR2
node --heapsnapshot-signal=SIGUSR2 app.js
kill -USR2 <pid>
# Write up to 2 snapshots automatically as the heap approaches its limit
node --heapsnapshot-near-heap-limit=2 app.js
# Attach Chrome DevTools via chrome://inspect
node --inspect app.js--heapsnapshot-near-heap-limit is the most useful of these for crashes you cannot reproduce locally. It captures the heap just before the fatal error, when the leaked objects are at their largest and easiest to spot.
When the Heap Looks Fine but RSS Grows
If heapUsed is flat while rss keeps climbing, a heap snapshot will not show the problem. Check external and arrayBuffers first. Retained Buffer objects are a common cause, for example request bodies held in a cache. The JavaScript wrappers are small in the snapshot, but each one points to megabytes of external memory. If external is flat too, suspect a native addon or allocator fragmentation, which needs native tools rather than DevTools.
Exercise
A service's logs show heapUsed oscillating between 150 MB and 400 MB with a steady floor over 24 hours, while rss rises from 600 MB to 1.8 GB and arrayBuffers rises at the same rate. Is this a JavaScript heap leak, and should you raise --max-old-space-size?
Show answer
It is not a heap leak, because the heapUsed floor is steady. The growth matches arrayBuffers, so the process is retaining Buffer or ArrayBuffer data outside the V8 heap. Raising --max-old-space-size would not help and would give V8 more room inside an already constrained container. Look for code that keeps references to Buffers, such as caches of request or file contents. In a heap snapshot, look for retained Buffer or ArrayBuffer objects with large external sizes.
Exercise
A Node.js container with a 1 GB memory limit is killed with exit code 137 and no "JavaScript heap out of memory" message. v8.getHeapStatistics() inside the container reports a heapsizelimit of about 4 GB. What is happening, and what is the fix?
Show answer
V8 sized its heap from more memory than the container allows, so the heap can grow past the container limit and the kernel's OOM killer sends SIGKILL (exit code 137) before V8 reaches its own limit. Set the limit explicitly below the container limit, for example NODE_OPTIONS="--max-old-space-size=768", so that V8 collects more aggressively and, if memory really runs out, fails with a diagnosable heap error. Also look for a leak if memory use keeps growing.
Exercise
Why should a periodic memory-logging timer call unref(), and what goes wrong without it?
Show answer
An active timer keeps the Node.js event loop alive. Without unref(), a script or worker that has finished its real work never exits, because the monitoring interval is still scheduled. unref() lets the process exit when the timer is the only thing left, while the timer still fires as long as other work keeps the process running.