Heap dump AKA heap snapshot is a file containing a snapshot of all memory allocated by your JavaScript running in Node. They're useful for diagnosing memory consumption and finding memory leaks.
npm install heapdump
Once installed, use one of:
- require the package in your app and run
kill -USR2 <pid of your process>
- require the package and call its
.writeSnapshot
function
A file heapdump-44214988.565232.heapsnapshot
is created. Numbers may vary.
- Add
heapdump
to your app with means to run it in one of the ways described above - Let the process stabilize for a few seconds
- Start using the functionality you suspect of leaking memory
- Take first heap snapshot
- Continue using the functionality for a while, preferably without running anything else in between
- Take second heap snapshot
- Open Chromium/Chrome dev tools and go to Memory tab
- Load the older snapshot file first, newer one second
- Select the newer snapshot and switch mode from Summary to Comparison
- Look for large positive deltas and explore the references that caused them
Finding a real memory leak requires some getting used to the tools, so for best results, practice on some examples (below).
There's a lot to learn about how garbage collector works, but if you learn one thing it's that when GC is running, your code is not. Print GC events to stdout for one minute.
const v8 = require('v8');
v8.setFlagsFromString('--trace_gc');
setTimeout(function() { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
Practice capturing heap dumps and finding memory leaks with a heap dump exercise