Sub topic 12
Memory in Node.js: Heap Limits and Monitoring
This chapter assumes you can run scripts with Node.js from a terminal, know what a heap snapshot is from the earlier profiling chapter, and understand that V8 splits the heap into young and old generations.
A Node.js process runs V8 inside a native program. Some of its memory belongs to the JavaScript heap and some does not. To diagnose memory problems on a server, you need to know how big the heap is allowed to grow and which numbers to watch.
Reading process.memoryUsage()
process.memoryUsage() returns a snapshot of the process's memory, in bytes.
| Field | What it measures |
|---|---|
| `rss` | Resident set size: all memory the OS has given the process, including code, stacks, the heap, and native allocations |
| `heapTotal` | Memory V8 has reserved for the JavaScript heap |
| `heapUsed` | The part of `heapTotal` currently occupied by objects |
| `external` | Memory for C++ objects bound to JavaScript objects, such as Buffer contents |
| `arrayBuffers` | Memory for `ArrayBuffer` and `SharedArrayBuffer` data, including Buffers (counted inside `external`) |
The relationships tell you where to look. If heapUsed keeps climbing across several garbage collections, JavaScript objects are leaking. If heapUsed stays flat while rss grows, the growth is outside the JS heap: Buffers, native addons, or fragmentation.
Heap Limits
V8 caps the old generation. The default depends on the Node.js version and the memory available on the machine. When the cap is reached and collection cannot free enough space, the process aborts with FATAL ERROR: ... JavaScript heap out of memory. You can check the real limit:
const v8 = require("node:v8");
const { heap_size_limit, used_heap_size } = v8.getHeapStatistics();
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(1);
console.log(`heap limit ${toMB(heap_size_limit)} MB, used ${toMB(used_heap_size)} MB`);To change the limit, use these flags:
# Raise the old-generation limit to 4 GB (value is in megabytes)
node --max-old-space-size=4096 app.js
# Write a heap snapshot automatically when the heap nears its limit (at most 1 file)
node --heapsnapshot-near-heap-limit=1 app.js
# Attach Chrome DevTools (open chrome://inspect) to take snapshots live
node --inspect app.jsMonitoring a Running Process
A small sampler shows memory trends over time. Call unref() on the timer so that monitoring alone does not keep the process alive.
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(1);
const monitor = setInterval(() => {
const { rss, heapUsed, heapTotal, external } = process.memoryUsage();
console.log(
`rss=${toMB(rss)}MB heap=${toMB(heapUsed)}/${toMB(heapTotal)}MB external=${toMB(external)}MB`
);
}, 5000);
monitor.unref();
// Simulated leak so the output shows growth
const leak = [];
setInterval(() => {
leak.push(new Array(100_000).fill("x"));
}, 500);Look at the low points of heapUsed, not the peaks. The heap normally rises and falls in a sawtooth as collections run. A leak shows up when the floor after each collection keeps rising.
When the trend looks wrong, capture evidence from the process itself:
const v8 = require("node:v8");
process.on("SIGUSR2", () => {
const file = v8.writeHeapSnapshot();
console.log(`heap snapshot written to ${file}`);
});Send kill -USR2 <pid> twice, a few minutes apart, then open both files in the DevTools Memory tab and compare them. Writing a snapshot pauses the process and can temporarily need about as much memory as the heap itself, so use it with care in production.
Exercise
A service's heapUsed stays steady at about 150 MB, but rss climbs from 400 MB to 2 GB over a day. Where should you look first, and why?
Show answer
Look outside the JavaScript heap. Because heapUsed is flat, JS objects are not accumulating. Check external and arrayBuffers for Buffers that are retained or never released, then check native addons. Heap snapshots will not show this growth well.
Exercise
A batch job crashes with "JavaScript heap out of memory" at about 2 GB on a machine with 16 GB of RAM. The data it loads is legitimately 3 GB. What do you change?
Show answer
Start Node with a larger old-generation limit, for example node --max-old-space-size=6144 job.js, and keep it within the available memory. A better long-term fix is to stream the data instead of loading all of it at once.