Heptic
Heptic

Reputation: 3106

node.js http request lock-up after 5 requests

I have some very simple code like this:

var http = require('http');

var options = {
    hostname: 'google.com',
    port: 80,
    path: '/'
};

function makeRequest() {
    http.get(options, function(res) {
        console.log('Got response code: ', res.statusCode);
        process.nextTick(makeRequest);
    }).on('error', function(err) {
            console.error('Got error: ', err);
            throw err;
        });
}

makeRequest();

and after 5 requests, it locks up and stops working. Sample output:

Got response code:  200
Got response code:  200
Got response code:  200
Got response code:  200
Got response code:  200
Got error:  { [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

Upvotes: 0

Views: 428

Answers (2)

Lorenzo
Lorenzo

Reputation: 1

By default client connections are pooled and have a 2 min idle timeout and default maximum pool size of 5.

If you are not going to reuse the instanced agent, you should call destroy() method after using it and avoid keeping idle connection in pool. Example:

var req = http.request({path: "/", host: "google.com",method: "HEAD"})
req.end();
req.on("response",function(res) {
    //do something
    // ....
    req.destroy();         
    //do other things
});

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 145994

Check out the hyperquest README, which explains exactly what is happening here, why @substack hates it, and how hyperquest can avoid it.

Upvotes: 1

Related Questions