I recently had the (mis?)fortune of trying to reproduce a memory leak in a NodeJS project I’ve been working on. I started out by searching for nodejs memory leak and having a read of the tools that showed up.
As I can’t reproduce the memory leak on demand yet, I wanted the ability to take snapshots on demand so I could analyse them and learn how to read the heap dumps whilst the app built up it’s memory usage.
I decided to use v8-profiler with node-inspector, and whilst I got it running, the profiles tab would never show up for me. It turns out that v8-profiler doesn’t really work any more, and the recommended tool to use now is node-webkit-agent.
npm install webkit-devtools-agent and require it at the top of the script you run to start the app e.g.
To enable the debug mode, you’ll need to send your process a
SIGUSR2 signal. You can use
pgrep -l node to get the process ID, then use
kill -SIGUSR2 <process ID> to enable the agent.
Next, you need to open up the web interface. I was debugging node 0.8 so I used the node 0.8 inspector. There are links to 0.6 and 0.8 versions on github. One thing I did notice, is that the agent runs on port 9999 locally, but the example specifies port 1337.
Once you have the interface showing, click on the Profiles tab, and look in the bottom left corner. There should be a button that has a solid black circle on it. This is the “take snapshot” button. You can use it to take memory snapshots on demand. Give it a go, and have a look at the output it produces.
I didn’t understand any of the output, but thankfully Google provide some useful information to help us interpret it. I’ve only read memory analysis 101 and the documentation on heap profiling so far. The output makes much more sense after reading those two pages.
Unfortunately I’ve not found my leak yet, but hopefully this will help anyone that finds it (or more likely, myself in the future) start profiling their nodejs applications for memory leaks in no time at all.
Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter