Memory and heap snapshots
Prerequisite: node-inspector-and-debugging. Objective: Interpret synthetic retention graph. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
process.memoryUsage returns byte counts including rss, heapTotal, heapUsed, external and arrayBuffers; arrayBuffers is included in external. RSS includes more than JavaScript heap and can vary because of native memory and allocator behavior. A retained reference, such as an unbounded Map of sessions, can prevent objects from becoming collectible. v8.writeHeapSnapshot can block the event loop and consume substantial memory; snapshots may contain secrets. Use only a small synthetic process and keep snapshots private. Do not infer a leak from a single sample or force garbage collection as a routine repair.
Inspect memory counter structure without promising exact values
import assert from 'node:assert/strict';const memory=process.memoryUsage();const fields=['rss','heapTotal','heapUsed','external','arrayBuffers'];for(const key of fields)assert.ok(Number.isFinite(memory[key])&&memory[key]>=0);console.log(fields.join(','));Expected output:
rss,heapTotal,heapUsed,external,arrayBuffersOnly nonnegative numeric fields are asserted. Values depend on runtime state.
Model retention paths using a bounded cache
const cache=new Map();for(let i=0;i<3;i++)cache.set(i,{label:'item-'+i});console.log('entries',cache.size);cache.delete(0);console.log('after delete',cache.size);cache.clear();console.log('after clear',cache.size);Expected output:
entries 3after delete 2after clear 0Entries no longer retained by this Map may still have other references. This is not a GC or heap snapshot measurement.
Common mistakes
Do not add all memoryUsage fields together: they overlap. A rising RSS alone does not identify which objects are retained. The fixtures intentionally avoid writing a real heap snapshot.
Practice
Sketch the path root → cache → session, remove the cache entry and explain why this removes one retention path but does not guarantee immediate collection.
Reference candidate: node-memory-and-heap-snapshots-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/v8.html. Selected versioned documentation opened.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory and heap snapshots — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Which measure includes more than JavaScript heap?
Why protect heap snapshots?
Does deleting a Map entry guarantee immediate GC?