Search code examples
javascriptnode.jsexpressnode.js-domains

Do node.js domains need to be disposed? When should it be done?


I have an Express app and I use domains per each request received. I've added a middleware to ensure any further middlewares are executed "inside" a domain.

app.use(function(req, res, next) {
    var d = domain.create();

    d.req = req;

    d.add(req);
    d.add(res);

    d.run(next);
});

Also, some code, which is executed while request is processed uses process.domain.req to get a reference to initial request, it's headers, cookies, etc... I'm doing this cause' I can't pass req directly to this code. This strange code is a kind of cross-environment code (for browser and for node) which doesn't knows where it is executed. Under the hood, some base layers are implemented differently for Node and for browser, especially network code. For browser it is an XMLHttpRequest and for NodeJS it is a custom wrapper based on request lib.

I'm worrying about memory leaks. That references to req stored on domain. Can they keep this things and get them not garbage collected?

Also, do I need to dispose domains on a regular basis, or do I need to dispose them in some edge/error cases?


Solution

  • Typically you would dispose your domain on the error or finish event, here's an example https://gist.github.com/regality/3061748.

    However, from my understanding the domain.dispose() method is being deprecated. See this git issue for details - https://github.com/joyent/node/issues/5018

    Further according to the doc it's recommended that you kill a domain process when you encounter an error. That link has a good explanation and example.