Lab 03: Memory Management

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm node:20-alpine sh

Memory bugs crash production systems and silently degrade performance. This lab covers V8's heap structure, heap statistics, WeakRef/FinalizationRegistry, common leak patterns, and analysis techniques.


Step 1: V8 Heap Spaces

V8 divides its heap into specialized spaces:

┌─────────────────────────────────────────────────────┐
│                   V8 HEAP                           │
│                                                     │
│  ┌─────────────┐  ┌─────────────┐                  │
│  │  New Space  │  │  Old Space  │                  │
│  │ (Scavenge)  │→ │  (Mark-    │                  │
│  │ short-lived │  │   Sweep)   │                  │
│  └─────────────┘  └─────────────┘                  │
│                                                     │
│  ┌─────────────┐  ┌─────────────┐  ┌────────────┐  │
│  │ Large Obj.  │  │ Code Space  │  │ Map Space  │  │
│  │  > 512 KB   │  │ (JIT code)  │  │(HiddenClass│  │
│  └─────────────┘  └─────────────┘  └────────────┘  │
└─────────────────────────────────────────────────────┘
  • New Space: Young generation, 1-8 MB, fast Scavenge GC (minor GC)

  • Old Space: Long-lived objects, promoted from New Space, slower Mark-Sweep-Compact (major GC)

  • Large Object Space: Objects > 512 KB, never moved

  • Code Space: Compiled machine code

  • Map Space: Hidden class descriptors


Step 2: Heap Statistics with v8.getHeapStatistics()

📸 Verified Output:

💡 Default heap_size_limit is ~1.5GB on 64-bit. Override with --max-old-space-size=4096 (in MB).


Step 3: process.memoryUsage() in Detail


Step 4: WeakRef + FinalizationRegistry

Run: node --expose-gc weakref-demo.js

📸 Verified Output:

💡 WeakRef deref may return undefined only after GC runs. Never rely on immediate collection.


Step 5: Common Memory Leak Patterns


Step 6: Heap Snapshot Analysis (Concept)

💡 heapdump npm package wraps v8.writeHeapSnapshot() for easy use. Load .heapsnapshot files in Chrome DevTools Memory tab.


Step 7: --max-old-space-size and GC Tuning


Step 8: Capstone — Memory Leak Detector

Build a memory monitor that tracks heap growth and alerts on leaks:


Summary

Concept
Tool / API
Use Case

Heap spaces

v8.getHeapSpaceStatistics()

Understand GC zones

Heap limit

--max-old-space-size

Prevent OOM crashes

Heap statistics

v8.getHeapStatistics()

Monitor memory usage

Process memory

process.memoryUsage()

RSS, heap, external

WeakRef

new WeakRef(obj)

Cache without preventing GC

FinalizationRegistry

new FinalizationRegistry(fn)

React to object collection

Heap snapshot

v8.writeHeapSnapshot()

Debug memory leaks

Leak patterns

Closures, timers, listeners

What to watch for

Last updated