Skip to content

Latest commit

 

History

History
48 lines (35 loc) · 1.86 KB

heap-dumps.md

File metadata and controls

48 lines (35 loc) · 1.86 KB

Heap dumps

What are heap dumps useful for?

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.

How to get a snapshot file

npm install heapdump

heapdump package

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.

How to find a memory leak with heap dumps

  1. Add heapdump to your app with means to run it in one of the ways described above
  2. Let the process stabilize for a few seconds
  3. Start using the functionality you suspect of leaking memory
  4. Take first heap snapshot
  5. Continue using the functionality for a while, preferably without running anything else in between
  6. Take second heap snapshot
  7. Open Chromium/Chrome dev tools and go to Memory tab
  8. Load the older snapshot file first, newer one second
  9. Select the newer snapshot and switch mode from Summary to Comparison
  10. 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).

Tracing garbage collection

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);

Examples

Practice capturing heap dumps and finding memory leaks with a heap dump exercise