1

I wrote a server application in Node.js.

When I do lsof -p 10893 (10893 is the pid of my Node.js application), I get this:

node    10893 root   19u  IPv4 (num) 0t0    TCP ip-X.X.X.X->ip-X-X-X.X:45403 (ESTABLISHED)
node    10893 root   19u  IPv4 (num) 0t0    TCP ip-X.X.X.X->ip-X-X-X.X:58416(ESTABLISHED)

This connections are hold and never closed, just when I restart my application.

I have the following code in node.js, which as I understand, should handle this issue:

app.use(function(err, req, res, next) {
    res.setTimeout(120000);
    res.status(500).send('Unexpected error');
});

But these connection are still appears, even after 120000 ms.

How can I fix it?

Or Smith
  • 3,556
  • 13
  • 42
  • 69

1 Answers1

3

Pretty sure this is a Keep-Alive issue. See this question and it's answer for details, but the gist is:

res.set("Connection", "close");

If you want that behavior for all your connections, then add it as a middleware above your routes/router:

app.use(function (req, res, next) {
    res.set("Connection", "close");
    next();
});

Also, if you want to time out the socket itself, it's a bit trickier:

var http = require('http');
var express = require('express');

var app = express();
var svr = http.createServer(app);

svr.on('connection', function (socket) {
    socket.setTimeout(120000, function () {
        this.end();
    });
});

// other middleware / routes here

app.use(function(err, req, res, next) {
    res.status(500).send('Unexpected error');
});

svr.listen(PORT);

EDIT:

Just noticed that your function is an error handler middleware (due to the presence of the err parameter). This means that the timeout would only have been set if there was an error, and not if the request completed successfully.

Community
  • 1
  • 1
rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • There is no impact to change the strategy from Keep-alive to connection close? – Or Smith Feb 05 '15 at 08:03
  • There are ramifications, it depends on what your app is doing. Is the client a browser? Is it an API where the client is going to be making many requests to the service in a row? In those cases Keep-Alive would be better, and you can rely on the timeout. – rossipedia Feb 05 '15 at 08:05