v8-memoryAnswer last reviewed July 2026

Let's talk closures. How does a closure end up leaking memory? And be precise with me about what a function actually holds onto.

Strong answers know capture is per-variable into a heap context, and that closures born in one scope share it, the mechanism behind the classic pin

What an AI-prepared candidate might say

So a closure keeps a reference to the variables from its enclosing scope, which means as long as the closure itself is reachable, those variables can't get garbage collected. The leak pattern is basically a long-lived closure capturing something large. Like an event handler or a setInterval callback that references a big object, that object stays alive for as long as the handler stays registered. The fix is to remove listeners when you don't need them anymore, clear your intervals, and avoid capturing large objects in callbacks that outlive the request. Copy out the one field you actually need instead of holding the whole object. In heap snapshots these show up as objects retained by closures. A closure retains its captured variables, so a leaked or forgotten closure leaks everything it captured, or something like that.

Senior
Locked

How contexts get allocated, which variables end up on the heap versus the stack, and the shared-context rule that lets one surviving callback pin a sibling's data.

Unlock the depth
Staff
Locked

The long-lived-emitter registration mistake behind most closure leaks in services, what it looks like in a heap snapshot, and the narrow-capture refactors that actually fix it.

Unlock the depth
Follow-up chain
Let's talk closures. How does a closure end up leaking memory? And be precise with me about what a function actually holds onto. | NodeBook