V8 memory and garbage collection

suggest change

Node.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)                  |
|  +---------------------------------------------------------+  |
|  |                        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

  1. 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.
  2. 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).
  3. Large Object Space: Objects that exceed the size of normal allocation pages; these bypass the Young Generation and are never relocated by GC.
  4. 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)

Major GC (Full Mark-Sweep & Mark-Compact)


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

  1. Remove Unused Event Listeners: Always call emitter.off() or removeListener() when components unmount; lingering listeners retain the surrounding closure context.
  2. Avoid Unbounded Caches: Never store items in plain JavaScript objects or Maps without an eviction policy (use LRU caches like lru-cache).
  3. Beware of Timers: Unreferenced setInterval timers keep callbacks and variables alive indefinitely until clearInterval() is called.
  4. Use WeakMap / WeakSet: For caching auxiliary metadata on objects without preventing garbage collection of the target keys.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents