Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EADDRNOTAVAIL after many http.get requests to localhost

When doing many http.get-requests to localhost (Apache) after 28233 requests I get EADDRNOTAVAIL.

When broken:

  • I cannot do a http.request to localhost for (round about) 10 seconds (EADDRNOTAVAIL)

While these 10 seconds

  • I can do curl http://localhost (there is no error in Apache, it is still working like charm)
  • I can do a http.get-request (from node.js) to www.google.com (the error only affects requests to localhost)

After 10 seconds

  • I can do a http.request to localhost again (as if node.js has healed itself)

This is the code:

var http = require( "http");

function httpRequest( callback ) {
    var options = {
            host: 'localhost',
            port: 80,
            path: ''
        },
        data = "";

    http.get(options, function(resp){
        resp.on('data', function( chunk ){   
            data += chunk;
        }).on("end", function() {
            callback( null, data );
        });
    }).on("error", function(e){
            callback( e );
    });
}

function loop( i, callback ) {
    if( i < 100000 ) {
        httpRequest( function( err, data ) {
            if( err ) {
                console.log( "Error!", i, err );
                return;
            }
            if( i % 1000 === 0 ) {
                console.log( i );
            }
            loop( i+1, callback );
        });
    } else {
        callback();
    }
}

console.log( "GO!");
loop( 0, function() {
   console.log( "READY!");
});
like image 495
heinob Avatar asked Jan 08 '14 09:01

heinob


1 Answers

I have found the solution by overwriting the default global agent. One possibility is to set maxSockets:1:

var http = require( "http"),
    agent = new http.Agent( {maxSockets: 1} ); // <-- this is new

function httpRequest( callback ) {
    var options = {
            host: 'localhost',
            port: 80,
            path: '',
            agent: agent // <-- and this is new
        },
...

With this correction the example above works. But I still had the EADDRNOTAVAIL issue within my production code, so setting the agent to false did it finally:

var http = require( "http");

function httpRequest( callback ) {
    var options = {
            host: 'localhost',
            port: 80,
            path: '',
            agent: false // <-- here
        },
...

I have posted this issue also on GitHub.

like image 155
heinob Avatar answered Sep 28 '22 09:09

heinob