0PricingLogin
Node.js Backend Development Bootcamp · Lesson

The V8 Heap, Generational GC, and Object Lifetimes

Understand how V8 allocates and collects memory across the young and old generations.

Why Heap Mechanics Matter in Node

Every object, closure, and buffer your Node.js service allocates lives somewhere in V8's managed memory. Understanding where it lives and when it gets reclaimed is the difference between a service that holds steady at 200 MB and one that creeps toward an OOM crash under load.

V8 splits its managed memory into two main regions:

  • New space (young generation) — small, fast, where almost every object is born.
  • Old space (old generation) — large, where objects that survive go to live.

You can inspect the live numbers at runtime with process.memoryUsage().

// heap_snapshot.js — print V8 heap usage in MB
function mb(bytes) {
  return (bytes / 1024 / 1024).toFixed(2) + ' MB';
}

const u = process.memoryUsage();
console.log('rss        ', mb(u.rss));        // total process memory
console.log('heapTotal  ', mb(u.heapTotal));  // V8 heap reserved
console.log('heapUsed   ', mb(u.heapUsed));   // V8 heap live
console.log('external   ', mb(u.external));   // C++ objects bound to JS
console.log('arrayBuffers', mb(u.arrayBuffers));

The Weak Generational Hypothesis

V8's GC is built on a single empirical observation called the weak generational hypothesis: most objects die young.

In a typical request handler, you allocate request-scoped objects — parsed JSON bodies, temporary arrays, intermediate strings — that become garbage the instant the response is sent. A small minority (caches, connection pools, module-level singletons) survive for the lifetime of the process.

This skew lets V8 optimize aggressively: it collects the young generation frequently and cheaply, and the old generation rarely and thoroughly. Each generation gets a GC algorithm tuned to its survival profile.

All lessons in this course

  1. The V8 Heap, Generational GC, and Object Lifetimes
  2. Capturing and Comparing Heap Snapshots
  3. CPU Profiling and Flame Graphs for Hot Paths
  4. Detecting and Fixing Common Leak Patterns
← Back to Node.js Backend Development Bootcamp