8

I have some code that is working, however it has a memory leak in it.

What are some good strategies for tracking memory leaks in node.js?

What steps should I follow when looking for such leaks?

How can I track the leak in my code?

Thanks

1 Answer 1

17

You can figure this out by profiling the memory usage of your application.

Javascript objects are allocated on the heap, so you'll want a tool that can dump the heap. After acquiring a heap dump you can inspect it and see how many instance of a given object (or function) exist.

E.g., for your code you know you create a socket whenever a user connects. Dumping the heap while three users are connected should show ~3 sockets. Dumping the heap after those users disconnect should show ~0 sockets.


You can actually use the Chrome heap dump analyzer with Node.js heap dumps.


Just fyi, functions are going to show up in the heap dump under the (closure) section.

You'll want to make sure you name your functions (even if they don't need a name) so they show up as something useful in the heap dump.

For example, something like

function() { }

will just show up as function() in the heap dump. Where as:

function taggedFunction() { }

will show up as function taggedFunction() in the heap dump. If you create 100 taggedFunctions then you'll see taggeFunction in the heap dump 100 times. Basically, naming your functions lets you figure out if you keep creating and leaking them.

Sign up to request clarification or add additional context in comments.

9 Comments

+1 for a great answer with good links and constructive criticism on OP's code
The setInterval should be common to every connections. It is used to have the same time displayed for each user. Maybe there is another way to do it ?
Ah. Yeah, you're setInterval is actually fine. I didn't see that the interval variable was in the global scope and only ever got set once. I thought an interval was being created for each connection.
My script takes 1.5GB in memory with 100 clients connected to it.
I switched from socket.io to socks.js and I don't have memory leak anymore.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.