NodeJS / ExpressJS Memory Leak - node.js

I've a static ExpressJS Server like that:
var express = require("express"),
app = express();
app.use(express.static(__dirname));
app.listen(1050);
When i start the server it uses 20MB of v8 heap. If i do a page reload every second the heap used grow continuously. After 4 hours it goes to 40MB of v8 heap used. The total v8 heap goes to 80MB and the RSS (total memory used by the process) goes to 130MB.
Why this simple and static server uses so much ram? It seems a memory leak. If i don't stop the page reload, the used memory keeps growing.
It's impossible to do larger projects if a simple static server like this uses too much ram.
NodeJS version: v0.10.21
ExpressJS version: 3.3.5
EDIT: I noticed that it's a problem with NodeJS, because i tried node-static instead of express, and while the used/total V8 heap stayed constant, the RSS memory used by nodejs continued to grow up.
Screen:
https://www.dropbox.com/s/4j5qs3rv2549dix/Screenshot%202014-03-20%2014.06.57.png
https://www.dropbox.com/s/0c30ou8l3rv2081/Screenshot%202014-03-20%2014.07.54.png
https://www.dropbox.com/s/5be1isk4v70qj8g/Screenshot%202014-03-20%2014.08.10.png
(Starts at 13:48)

Not sure if you are still in need of an answer but ill post for anyone else who might be having the same issues.
I was having this same exact problem and fixed it by using:
--max-old-space-size 5
This limits how much memory is held until it gets deleted by GC.

To help the creators of NodeJS and Express potentially, try taking memory snapshots (done using chrome dev tools, use the url chrome://inspect ) this will allow you to see where your memory is allocated.

Related

Node - memory leak

I have a Node app using express (rest api).
The thing works nicely except that it breaks if it keeps running too long.
By monitoring the memory, I noticed that the footprint goes up with every page reload/query sent.
Even after upping the memory to 8gb, I still finally end up with:
Reached heap limit Allocation failed - JavaScript heap out of memory
I googled a bit and tried adding --inspect and then looked at the chrome devtools, but I can't make sense of it. It shows the whole transpiled (ts->js) webpack bundle as a string multiple times.
Can't share the source code but would appreciate any general pointers what to look out for.

Why does Node.js have incremental memory usage?

I have a gameserver.js file that is well over 100 KB in size. And I kept checking my task manager after each refresh on my browser and kept seeing my node.exe memory usage keep rising for every refresh. I'm using the ws module here: https://github.com/websockets/ws and figured, you know what, there is most likely some memory leak in my code somewhere...
So to double check and isolate the issue I created a test.js file and put in the default ws code block:
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 9300 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
});
And started it up:
Now, I check node.exe's memory usage:
The incremental part that makes me confused is:
If I refresh my browser that makes the connection to this port 9300 websocket server and then look back at my task manager.. it shows:
Which is now at: 14,500 K.
And it keeps on rising upon each refresh, so theoretically if I keep just refreshing it will go through the roof. Is this intended? Is there a memory leak in the ws module somewhere maybe? The whole reason I ask is because I thought maybe in a few minutes or when the user closes the browser it will go back down, but it doesn't.
And the core reason why I wanted to do this test because I figured I had a memory leak issue in my personal code somewhere and just wanted to check if it wasn't me, or vice versa. Now I'm stumped.
Seeing an increased memory footprint by a Node.js application is completely normal behaviour. Node.js constantly analyses your running code, generates optimised code, reverts to unoptimised code (if needed), etc. All this requires quite a lot of memory even for the most simple of applications (Node.js itself is from a large part written in JavaScript that follows the same optimisations/deoptimisations as your own code).
Additionally, a process may be granted more memory when it needs it, but many operating systems remove that allocated memory from the process only when they decide it is needed elsewhere (i.e. by another process). So an application can, in peaks, consume 1 GB of RAM, then garbage collection kicks in, usage drops to 500 MB, but the process may still keep the 1 GB.
Detecting presence of memory leaks
To properly analyse memory usage and memory leaks, you must use Node.js's process.memoryUsage().
You should set up an interval that dumps this memory usage into a file i.e. every second, then apply some "stress" on your application over several seconds (i.e. for web servers, issue several thousand requests). Then take a look at the results and see if the memory just keeps increasing or if it follows a steady pattern of increasing/decreasing.
Detecting source of memory leaks
The best tool for this is likely node-heapdump. You use it with the Chrome debugger.
Start your application and apply initial stress (this is to generate optimised code and "warm-up" your application)
While the app is idle, generate a heapdump
Perform a single, additional operation (i.e. one more request) that you suspect will likely cause a memory leak - this is probably the trickiest part especially for large apps
Generate another heapdump
Load both heapdumps into Chrome debugger and compare them - if there is a memory leak, you will see that there are some objects that were allocated during that single request but were not released afterwards
Inspect the object to determine where the leak occurs
I had the opportunity to investigate a reported memory leak in the Sails.js framework - you can see detailed description of the analysis (including pretty graphs, etc.) on this issue.
There is also a detailed article about working with heapdumps by StrongLoop - I suggest to have a look at it.
The garbage collector is not called all the time because it blocks your process. So V8 launches GC when it thinks it's necessary.
To find if you have a memory leak I propose to fire up the GC manually after every request just to see if your memory is still going up. Normally if you don't have a memory leak your memory should not increase. Because the GC will clean all non-used objects. If your memory is still going up after a GC call you have a memory leak.
To launch GC manually you can do that, but attention! Don't use this in production; this is just a way to cleanup your memory and see if you have a memory leak.
Launch Node.js like this:
node --expose-gc --always-compact test.js
It will expose the garbage collector and force it to be aggressive. Call this method to run the GC:
global.gc();
Call this method after each hit on your server and see if the GC clean the memory or not.
You can also do two heapdumps of your process before and after request to see the difference.
Don't use this in production or in your project. It is just a way to see if you have a memory leak or not.

What is consuming memory in my Node JS application?

Background
I have a relatively simple node js application (essentially just expressjs + mongoose). It is currently running in production on an Ubuntu Server and serves about 20,000 page views per day.
Initially the application was running on a machine with 512 MB memory. Upon noticing that the server would essentially crash every so often I suspected that the application might be running out of memory, which was the case.
I have since moved the application to a server with 1 GB of memory. I have been monitoring the application and within a few minutes the application tends to reach about 200-250 MB of memory usage. Over longer periods of time (say 10+ hours) it seems that the amount keeps growing very slowly (I'm still investigating that).
I have been since been trying to figure out what is consuming the memory. I have been going through my code and have not found any obvious memory leaks (for example unclosed db connections and such).
Tests
I have implemented a handy heapdump function using node-heapdump and I have now enabled --expore-gc to be able to manually trigger garbage collection. From time to time I try triggering a manual GC to see what happens with the memory usage, but it seems to have no effect whatsoever.
I have also tried analysing heapdumps from time to time - but I'm not sure if what I'm seeing is normal or not. I do find it slightly suspicious that there is one entry with 93% of the retained size - but it just points to "builtins" (not really sure what the signifies).
Upon inspecting the 2nd highest retained size (Buffer) I can see that it links back to the same "builtins" via a setTimeout function in some Native Code. I suspect it is cache or https related (_cache, slabBuffer, tls).
Questions
Does this look normal for a Node JS application?
Is anyone able to draw any sort of conclusion from this?
What exactly is "builtins" (does it refer to builtin js types)?

Optimize Node.js memory consumption

I'm writing a simple cms in Node.js, Express and MongoDB. I'm planning to run a different Node.js process for every site. The problem is that after startup the process takes about 90m of RAM and for me it's too big (eight site take all server RAM). This memory is taken after the first connection to the site and other connections don't affect the memory.
Is there a guideline or a list of "best practices" to optimize this memory usage? I'm trying to track where the memory is allocated with process.memoryUsage() or a similar function but it's not simple to do this.
Is not a problem of memory leaks or something similar because the memory usage doesn't grow up after the first connection, so probably the optimization could be in loading less modules or do something differently...
The links below may help you to understand and detect memory leaks (if they do exist):
Debugging memory leaks in node.js
Detecting Memory Leaks in Node.js Applications
Tracking Down Memory Leaks in Node.js
These SO questions may also be useful:
How to monitor the memory usage of Node.js?
Node.js Memory Leak Hunting
Here is a quick fix, a node.js lib that will restart the any node process once it reaches a certain size.
https://github.com/DoryZi/memory_limiter
Set the --max_old_space_size CLI flag to control the maximum heap size. There's a post that describes Running a node.js app in a low-memory environment
tl;dr; Try setting this value, in megabytes, to about 80% of the maximum memory footprint you want node to try to remain under. e.g. to run app.js and keep it under 500MB RAM used
node --max_old_space_size=400 app.js
This setting is also described in the Node JS CLI documentation

Memory leak in Node.js outside of heap?

I've just fixed a memory leak in my node application which was in the heap of node.
I've profiled that with Google's Profiler and managed to fix the memory leak.
Now my app is running again for some time, and I've seen that the heap size is pretty constant. No memory leak anymore. But when I check my server's free RAM, I see a decrease...
When I restart my node server the RAM is up to it's normal free RAM.
Now I've heard about that Node.js can save objects and stuff outside of the heap. I think that is what's causing the memory leak here.
How can I see what's taking up the memory? Can't really profile anything, or can I?
I'm using:
node.js: v0.8.18 and
socket.io: v0.9.13
Some other node modules that I'm using are: nodetime, heapdump (will delete this, though), jquery, crypto, request and querystring.
Some graphs:
Free OS memory and
Node RSS and Heap used

Resources