node.js - possible http server memory leak

Problem

Nodejs version: 0.8.8

Here is the server:

var http = require('http');
var port = 1338;
var ip = "127.0.0.1";    

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hi there\n');
}).listen(port, ip);    

Client (php script) curls away a post request to the above server. POST is a string (json), about 4 megabytes in size.

As you can see, server does nothing with the posted data. In order to debug, I removed all my code and went back to the hello world example that does nothing :)
When I take a look at the memory usage of the node process (done in Activity Monitor, mac app) - it reports that the node server memory usage is geting larger for every request.
So after 20 requests or so memory usage is doubled.

Problem courtesy of: ado

Solution

This is not a bug. It's normal, expected behaviour.

Node.js is based on JavaScript, which is a garbage-collected language. In short, what happens, is that memory is not freed right away, but instead it will take some time until memory is freed (e.g. garbage is collected). V8 (which node uses) actually has a very intelligent garbage collector that "ensures fast object allocation, short garbage collection pauses, and no memory fragmentation".

To demonstrate this behaviour for you, I ran the above script with node.js 0.8.8 on Windows and bombarded the server with large HTTP POST requests.

Process Explorer reveals the following memory usage graph:

enter image description here

As you can see, the memory usage goes up, until a certain limit that triggers garbage collection. After the cleanup, the usage is reset and starts again climbing until the next triggering.

Solution courtesy of: jsalonen

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.