V8 memory and garbage collection
suggest changeNode.js delegates all JavaScript memory management to the Google V8 engine. Understanding V8's heap structure and generational garbage collector is essential for diagnosing memory leaks, avoiding high latency spikes from GC pauses, and sizing production container limits.
1. The V8 Memory Structure
When a Node.js process runs, memory is partitioned into distinct segments:
- Resident Set Size (RSS): Total RAM occupied by the process in system memory (includes the V8 heap, C++ runtime memory, native modules, and execution stack).
- V8 Heap: Where JavaScript objects, arrays, closures, and primitives are allocated.
- External Memory: C++ objects bound to JavaScript counterparts, such as Node.js
Bufferobjects andArrayBufferallocations.
+---------------------------------------------------------------+
| Resident Set Size (RSS) |
| +---------------------------------------------------------+ |
| | V8 Heap | |
| | +-------------------+ +----------------------------+ | |
| | | New Space | | Old Space | | |
| | | (Nursery & Semi) | | (Old Pointer & Old Data) | | |
| | +-------------------+ +----------------------------+ | |
| | +-------------------+ +----------------------------+ | |
| | | Large Object Space| | Code Space | | |
| | +-------------------+ +----------------------------+ | |
| +---------------------------------------------------------+ |
| +------------------------+ +-----------------------------+ |
| | Execution Stack | | Native / External Buffers | |
| +------------------------+ +-----------------------------+ |
+---------------------------------------------------------------+
V8 Heap Spaces
- New Space (Young Generation): Contiguous buffer (typically 16 MB–64 MB) where fresh objects are allocated. Subdivided into two semi-spaces: From Space and To Space.
- Old Space (Old Generation): Contains objects that survived multiple minor GC cycles in the Young Generation.
- Old Pointer Space: Objects containing references to other objects.
- Old Data Space: Raw payloads (strings, boxed numbers, raw byte arrays).
- Large Object Space: Objects that exceed the size of normal allocation pages; these bypass the Young Generation and are never relocated by GC.
- Code Space: Executable machine code generated by V8's JIT compilers (Ignition & TurboFan).
2. Generational Garbage Collection: Minor vs Major GC
V8 leverages the Weak Generational Hypothesis: most objects die young.
Minor GC (Scavenger)
- Target: The New Space.
- Mechanism: Implements Cheney's copying algorithm. Live objects from the "From" semi-space are copied into the "To" semi-space; unreachable objects are discarded.
- Promotion: If an object survives two scavenger cycles, it is promoted ("tenured") to the Old Space.
- Performance: Extremely fast (typically 1–5 milliseconds) and frequent.
Major GC (Full Mark-Sweep & Mark-Compact)
- Target: The entire Old Space and Large Object Space.
- Phases:
- Marking: Traverses object graphs from root references (global object, stack frames, DOM/Node modules) to discover reachable objects.
- Sweeping: Frees unreferenced memory and adds contiguous blocks to free lists.
- Compacting: Defragments memory by shifting live objects to reduce fragmentation.
- Optimizations: V8 uses Concurrent Marking, Incremental Marking, and Concurrent Sweeping on background threads to prevent prolonged "stop-the-world" application freezes.
3. Inspecting Memory Programmatically
process.memoryUsage()
function reportMemory() {
const mem = process.memoryUsage();
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(2);
console.log(`RSS: ${toMB(mem.rss)} MB`);
console.log(`Heap Total: ${toMB(mem.heapTotal)} MB`);
console.log(`Heap Used: ${toMB(mem.heapUsed)} MB`);
console.log(`External: ${toMB(mem.external)} MB`);
console.log(`ArrayBuffers: ${toMB(mem.arrayBuffers)} MB`);
}
reportMemory();
Granular Heap Statistics with node:v8
import v8 from 'node:v8';
const heapStats = v8.getHeapStatistics();
console.log('Heap Size Limit:', (heapStats.heap_size_limit / 1024 / 1024).toFixed(2), 'MB');
console.log('Total Available:', (heapStats.total_available_size / 1024 / 1024).toFixed(2), 'MB');
// Detailed breakdown of each heap space
const spaces = v8.getHeapSpaceStatistics();
console.table(spaces.map(s => ({
Space: s.space_name,
SizeMB: (s.space_size / 1024 / 1024).toFixed(2),
UsedMB: (s.space_used_size / 1024 / 1024).toFixed(2)
})));
4. Monitoring Garbage Collection in Real Time
Using node:perf_hooks, you can capture individual GC pauses directly in application logs:
import { PerformanceObserver } from 'node:perf_hooks';
// values of perf_hooks.constants.NODE_PERFORMANCE_GC_*
const gcTypes = {
1: 'Scavenge (Minor GC)',
2: 'Minor Mark-Sweep',
4: 'Mark-Sweep-Compact (Major GC)',
8: 'Incremental Marking',
16: 'Weak Callbacks'
};
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const gcType = gcTypes[entry.detail?.kind] || 'Unknown';
console.log(`[GC] ${gcType}: Duration ${entry.duration.toFixed(2)} ms`);
}
});
obs.observe({ entryTypes: ['gc'], buffered: true });
5. Capturing Heap Snapshots to Diagnose Memory Leaks
When memory continuously climbs without plateauing, generate a heap snapshot to identify the leaking objects:
import v8 from 'node:v8';
import path from 'node:path';
function takeSnapshot() {
const filename = path.join(process.cwd(), `snapshot-${Date.now()}.heapsnapshot`);
const snapshotPath = v8.writeHeapSnapshot(filename);
console.log(`Heap snapshot written to ${snapshotPath}`);
}
// Trigger snapshot on demand (e.g., when heapUsed exceeds threshold)
if (process.memoryUsage().heapUsed > 500 * 1024 * 1024) {
takeSnapshot();
}
You can open the resulting .heapsnapshot file in Google Chrome via DevTools -> Memory tab -> Load profile to inspect retained objects, constructor counts, and allocation retainers.
6. Essential V8 CLI Flags
When deploying Node.js to production, customize V8's memory behavior via CLI arguments:
# 1. Adjust maximum old space size in MB (default depends on available memory, up to ~4 GB on 64-bit systems)
node --max-old-space-size=4096 app.js
# 2. Log every GC event with time spent and memory freed
node --trace-gc app.js
# 3. Expose global.gc() for automated testing and benchmarks
node --expose-gc test-memory.js
# 4. Generate core dump or heap dump on out-of-memory crash
node --heapsnapshot-near-heap-limit=3 app.js
7. Best Practices to Prevent Memory Leaks
- Remove Unused Event Listeners: Always call
emitter.off()orremoveListener()when components unmount; lingering listeners retain the surrounding closure context. - Avoid Unbounded Caches: Never store items in plain JavaScript objects or
Maps without an eviction policy (use LRU caches likelru-cache). - Beware of Timers: Unreferenced
setIntervaltimers keep callbacks and variables alive indefinitely untilclearInterval()is called. - Use WeakMap / WeakSet: For caching auxiliary metadata on objects without preventing garbage collection of the target keys.