calibr
calibr

Reputation: 59

Node.JS, Server close Keep-Alive connection in middle of request

I have Node.js HTTP server which closes incoming connections if their idle for 10 seconds, and client which uses Keep-Alive connections pool to request this server. When I start send requests with interval 10 seconds, I got periodically error messages ECONNRESET, I think because connection closes in middle of HTTP request. Is there any elegant solution except simple resending request?

server.js

var server = require('http').createServer(function(req, res) {
  console.log(new Date(), "Request ", req.method);
  res.end("Nice");
});

server.timeout = 10000;

server.on("connection", function(socket) {
  console.log("New connection");
  socket._created = new Date().getTime();
  socket.on("close", function() {
    var now = new Date().getTime();
    console.log(new Date(), "Socket closed, TTL", (now - socket._created)/1000);
  });
});
server.listen(3000);

client.js

var http = require("http");

var agent = new http.Agent({
  keepAlive: true
});

var reqSent = 0;
var NEED_REQS = 10;
var TIMEOUT = 10000;

function _req() {
  var start = new Date().getTime();
  var req = http.get({
    host: "localhost",
    port: 3000,
    agent: agent
  }, function(res) {
    reqSent++;
    var now = new Date().getTime();
    console.log("Sent:", reqSent, (now - start)/1000);

    if(reqSent >= NEED_REQS) {
      agent.destroy();
      return;
    }
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    });

    setTimeout(function() {
      _req();
    }, TIMEOUT);
  });
  req.on("error", function(err) {
    console.error(err);
  });
}

_req();

Running client.js

$ node client.js
Sent: 1 0.028
Sent: 2 0.008
Sent: 3 0.002
{ [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }

Upvotes: 2

Views: 12402

Answers (2)

vipr
vipr

Reputation: 56

I did reproduce your problem with sending requests each 5 seconds. The default keepAlive timeout in nodejs is 5 seconds, https://nodejs.org/api/http.html#http_server_keepalivetimeout

This github issue against nodejs explains the behavior well, https://github.com/nodejs/node/issues/20256 The workaround would be to set keepAlive timout client side to something less than the timeout on server side but I don't see such option in nodejs, https://nodejs.org/api/http.html#http_new_agent_options

Upvotes: 4

calibr
calibr

Reputation: 59

I think that there is only one solution for this - resend request if ECONNRESET obtained, I found good lib which wraps such logic https://github.com/FGRibreau/node-request-retry

Upvotes: 0

Related Questions