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 request
package.
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
http.createServer(app).listen(config.http_port);
http.globalAgent.maxSockets = config.http_max_socket //actual value is 1000.
I googled further and found this stackoverflow article node.js http.get hangs after 5 requests to remote site. 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:
app.get('/test', function(req, res) {
request('http://google.com', function(err, resp, body) {
res.send(body);
})
});
and I set the server maxSocket to be 5
http.createServer(app).listen(100);
http.globalAgent.maxSockets = 5;
I then wrote a small test script to test this:
var request = require('request');
const url = 'http://localhost:100/test',
total = 100;
for(var i = 0; i < total; i++) {
(function(i){
request(url, function(err, res, data) {
console.log(i, res.statusCode);
})
})(i);
}
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.