Memory Management and Garbage Collection

Node.js uses V8's garbage collector to reclaim memory that is no longer reachable. Memory leaks occur when application references unintentionally keep objects alive.

Common causes include unbounded caches, global collections, event listeners that are never removed, timers that remain active, and closures retaining large objects.

Memory Leaks Are Reachability Problems

Garbage collection cannot reclaim objects that are still reachable. Look for references that live longer than the data they retain.

Avoiding an Unbounded Cache
const cache = new Map();

function setUser(id, user) {
  cache.set(id, user);
}

// Production code should define an eviction or expiration strategy.
💡 A plain Map grows indefinitely unless the application explicitly removes entries. Production caches should have bounded size or expiration.
Key Takeaways
  • Garbage collection removes unreachable objects.
  • Unbounded collections are a common source of memory growth.
  • Heap snapshots can help identify retained objects.
Knowledge Check

Why can an unbounded Map cause memory growth?