Lesson 6 of 9 · 25m
Handles, Retention, and Memory-Leak Mechanics
Connect object retention, event listeners, closures, sockets, timers, and async resources so leaks become traceable structures instead of folklore.
Memory leaks in Node are rarely exotic. They are usually ordinary references doing exactly what references do. The painful part is that the retaining object is often three framework layers away from the allocation you noticed. To fix leaks, stop asking "what object is large?" and ask "what path keeps it reachable?"
Reachability is the rule
If any live root can reach an object, V8 keeps it. Roots include globals, active closures, timers, sockets, pending promises in some dependency graphs, event listeners, and native references. A cache is only the obvious version:
const sessions = new Map();
setInterval(() => sessions.set(crypto.randomUUID(), {
created: Date.now(), payload: Buffer.alloc(1024),
}), 10);Nothing is wrong with Map. The missing lifecycle is wrong. If entries are inserted forever and never evicted, memory is the correct behavior of the program as written.
Listeners retain their emitter graph
Event emitters create strong references in both directions:
server.on('connection', socket => socket.on('data', chunk => audit.write(chunk)));A socket retains its listener functions; those closures may retain request state, user objects, or larger service objects. removeListener, off, and once semantics matter. Listener-count warnings exist because accidental accumulation is common.
Timers and intervals are retention machines
An interval holds its callback, and the callback's closure holds everything it captures:
setInterval(() => metrics.observe(hugeRequestContext), 1000);If the interval is never cleared, hugeRequestContext has immortal lifetime. In long-lived services, prefer explicit lifecycle ownership: create resources in a scope, close them in the same scope, and test shutdown paths.
Handles keep processes alive too
Open sockets, active servers, timers, watchers, and some native handles can keep a Node process alive. Diagnostic builds sometimes inspect process._getActiveHandles() and _getActiveRequests(), but these are internal APIs; production code should expose explicit close lifecycle rather than scrape runtime state.
Heap snapshots explain paths, not blame
A heap snapshot can show dominators and retainer paths. The object with the largest shallow size is not always the problem. Look for:
root -> cache/object -> listener -> closure -> huge payload
root -> timer -> closure -> request context
root -> socket -> parser -> accumulated bufferThe first unfamiliar frame in the retaining path is usually more interesting than the final large object. Framework wrappers can obscure ownership, so reproduce leaks with minimal instrumentation before annotating the entire service.
Leak testing requires steady state
Take at least three heap snapshots: after warm-up, after a controlled load period, and after another identical period. Compare objects that consistently grow in count or retained size across independent load cycles. One snapshot is archaeology; repeated snapshots are evidence.
Field notes
- Global caches need eviction, memory-aware sizing, and metrics. Unbounded
Mapis a leak generator. - Removing a socket listener is not enough if the socket itself remains open and retains parser state.
- Per-request telemetry labels can accidentally retain request bodies through closure capture.
Was this lesson helpful?