Back to 20 Concepts
internalsExpert

V8 Garbage Collection: Scavenger Minor GC & Mark-Sweep Major GC

V8 manages RAM via Generational Garbage Collection: Young Generation (Eden + Semi-Spaces From/To for fast Minor GC) and Old Generation (Mark-Sweep-Compact for long-lived objects).

Intuitive Mental Model

The Recycling Bin vs The Attic: Short-lived objects (daily receipts) are dumped into the paper recycling bin (Minor GC) every minute. Things kept for over a month are moved upstairs to the Attic (Old Generation) and cleaned once a year (Major GC).

Node.js ESM / CJS ImplementationNode.js v22 LTS
import v8 from 'v8';

// Inspect current heap memory:
const stats = v8.getHeapStatistics();
console.log('Heap Size Limit:', stats.heap_size_limit / 1024 / 1024, 'MB');
console.log('Used Heap:', stats.used_heap_size / 1024 / 1024, 'MB');

// Run with exposed GC (debugging only):
// node --expose-gc script.js
if (global.gc) {
  global.gc(); // Forces manual Major Mark-Sweep GC cycle
}

Key Architectural Takeaways

  • Minor GC (Scavenger): Operates on Young Generation (1-64MB) using Cheney algorithm in < 2ms.
  • Objects surviving 2 Minor GC cycles are promoted to the Old Generation.
  • Major GC (Mark-Sweep-Compact): Reclaims Old Gen objects; long Major GC cycles cause latency spikes in API responses.
Common Production Mistake

Retaining references to large objects in global arrays, preventing Mark-Sweep GC from reclaiming Old Generation memory and causing OOM.

Recommended Solution

Use WeakMap or WeakSet for caches where keys should be garbage-collected automatically.