I'm working on a small demo of Node performance and was surprised to see the following example with 50 concurrent calls to setTimeout
take over 4 seconds instead of 500ms.
The following code sets up a very simple express server that listens for all requests, and responds 500ms later using setTimeout
. Then it has a client that makes 50 requests passing in a number to track requests and corresponding responses.
// SERVER
var express = require('express');
var app = express();
app.get('*', function (req, res) {
setTimeout(function () {
return res.send(req.query.i);
}, 500);
});
app.listen(8099);
// CLIENT
var http = require('http');
function start() {
for (var i = 0; i < 50; i++) {
console.log(new Date().getSeconds() + ':' + new Date().getMilliseconds() + ' - Sending ' + i);
http.get('http://localhost:8099?i=' + i, responseHandler);
}
function responseHandler(res) {
res.on('data', function (body) {
return console.log(new Date().getSeconds() + ':' + new Date().getMilliseconds() + ' - Received ' + body);
});
}
}
start();
I expected the code to take 30-50ms to make all the setTimeout
calls and then 500ms later all of them would respond around the same time. Instead I see them respond in groups of 5, with 500ms between each group of 5.
I tried a number of simpler alternatives which all do fix the problem. If I take the setTimeout
out and immediately respond, all 50 responses come in within 100ms. If I take the web server out of the equation and just have 50 calls to setTimeout
, then all 50 calls are queued immediately and all 50 come back at the same time 500ms later.
What could be causing the extra delays when express and http calls are combined with setTimeout
?