A process’s memory can keep rising even though it has finished using the data it allocated. A memory leak occurs when code still holds a reference to an unneeded object, preventing the garbage collector from reclaiming it. Rising memory alone is not proof: temporary allocation pressure can also enlarge the heap. section 11.2 section 11.2.2
Closures expose a less obvious route to retention. In V8, a function that captures an outer variable references a heap-allocated Context. That Context can outlive the outer call. A returned function that reads only an ID may therefore keep a large processed string in scope alive too. V8 may optimize unused captures away, but that is not guaranteed; separating data processing from creation of the returned function limits what it can retain. section 6.4
function processData() {
const str = 'a'.repeat(1_000_000);
const id = generateId();
processStr(str);
return function getId() {
return id;
};
}
const getId = processData();The returned getId function uses id, not str. Inspect the enclosing scope to see why the million-character string may remain retained. section 6.4
A registered listener creates another long-lived reference. If its surrounding scope contains large data, leaving the listener installed can prolong that data’s lifetime. Keep a reference to the handler and remove it when the work ends; a finally block can make cleanup explicit. section 6.4
Diagnose retention in order:
- Confirm the symptom. Sample process.memoryUsage() under load and compare post-collection heapUsed troughs, not just peaks. Stable troughs fit ordinary collection; rising troughs indicate accumulating survivors. section 11.2.1
- Identify the growing metric. Rising heapUsed points toward JavaScript objects; rising external with stable heapUsed points toward Buffers or ArrayBuffers. Rising rss alone needs care: on Bun, allocator retention can raise rss without a JavaScript heap leak. section 11.2.1 section 11.1.1
- Distinguish leak from pressure. Under --trace-gc, stable mu and a return to baseline after load stops favor pressure. Declining mu or a baseline that stays elevated favors a leak. section 11.2.2
- Find what accumulates, then find the reference retaining it. Reduce allocation rate or object lifetime for pressure; remove the unnecessary reference for a leak. section 11.2 section 11.2.2








