In a web application it is common for each request to create a new thread that handles all processing and if for some reason the thread gets blocked by performing a heavy task, the resource is allocated to the request.
I understand that this is inefficient because the allocated resources are misused and cause excessive consumption of server resources.
While studying Node, I tested the following code that calculates a prime number and therefore makes CPU intensive use;
calc-primo.js
var http = require('http');
var isPrime = require('./number-util').isPrime;
var count = 1;
var server = http.createServer(function (req, res) {
console.log('Requisição #' + count++);
console.time('Tempo');
var number = 0;
var numberOfPrimes = 0;
while(true) {
if(isPrime(++number)) numberOfPrimes++;
if(numberOfPrimes === 1000000) break;
}
res.end("Número: " + number);
console.timeEnd('Tempo');
});
server.listen(3000);
I executed the command node calc-primo.js
and in the browser opened 2 tabs and in each one I made a request to localhost:3000
. In the console I get the following result:
Requisition # 1
Time: 12458ms
Requisition # 2
Time: 12358ms
Due to the nature of the Node, the #2
request only received a response after the #1
request, but the second request waited for about 12 seconds until it was processed and 12 more for a response.
While optimizing server resources, there is a greater slowness to get a response. I saw that this can be solved using the cluster
module and have multiple instances of the event loop.
1) When adding multiple instances of the event loop (each instance being a new thread), does it not violate the principle of Node that is to optimize server resources?
2) Does the fact that the Node has a single main thread does not slow down the system for requests that require heavier processing, since there will be competition?