title: Node.JS express API hangs sometimes
body: <p>I have a web API service written using Node.JS and Express. The service receives requests from web front-end, and sometime it does http request to other web api too by using <a href="https://www.npmjs.com/package/request" rel="nofollow noreferrer"><code>request</code> package</a>. </p>
  
  <p>Randomly, I experience issue that the API server simply hangs and never respond. I confirmed that I have changed the default http.globalAgent.maxSockets value by the following code in app.js</p>
  
  <pre><code>http.createServer(app).listen(config.http_port);
  http.globalAgent.maxSockets = config.http_max_socket //actual value is 1000. 
  </code></pre>
  
  <p>I googled further and found this stackoverflow article <a href="https://stackoverflow.com/questions/16965582/node-js-http-get-hangs-after-5-requests-to-remote-site">node.js http.get hangs after 5 requests to remote site</a>. I suspect this might be related to my code to request other services, so I setup a simple express service to test this. In the simple express service, I have a simple api function to mimic my application code: </p>
  
  <pre><code>app.get('/test', function(req, res) {
      request('http://google.com', function(err, resp, body) {
          res.send(body);
      })
  }); 
  </code></pre>
  
  <p>and I set the server maxSocket to be 5</p>
  
  <pre><code>http.createServer(app).listen(100);
  http.globalAgent.maxSockets = 5;
  </code></pre>
  
  <p>I then wrote a small test script to test this: </p>
  
  <pre><code>var request = require('request'); 
  
  const url = 'http://localhost:100/test',
      total = 100; 
  
  for(var i = 0; i &lt; total; i++) {
      (function(i){
          request(url, function(err, res, data) {
              console.log(i, res.statusCode);
          })
      })(i);
  }
  </code></pre>
  
  <p>I was expecting the test to hang after 5 requests but this isn't the case. The test run all the way to the end without issue. So I'm rather confused with the cause why my api sometimes hangs, would appreciate if anyone can enlighten me.  </p>