I am building a Node.js application and wanted to understand how concurrent requests are handled.
I build a test server, where high CPU load is being simulated by waiting 10 seconds. To test the behavior, I open two browser tabs and refresh the page simultaneously.
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', function (req, res, next) {
var requestTime = new Date().getTime(),
executionTime;
doHeavyWork(requestTime, function(error){
res.send({
requestTime : requestTime,
executionTime : executionTime
});
});
});
function doHeavyWork (requestTime, callback) {
var sleepSeconds = 10;
while (requestTime + sleepSeconds*1000 >= new Date().getTime()) {}
callback(null);
}
server.listen(1337, '127.0.0.1');
From what I heard about Node.js, I was expecting both Tabs to finish loading in the same time. In reality the Tab which is refreshed first also finishes first. The next tab loads after additional 10 seconds. So basically, the server processes the requests one at a time instead of processing them simultaneously. What am I missing here?
How NodeJS handle multiple client requests? NodeJS receives multiple client requests and places them into EventQueue. NodeJS is built with the concept of event-driven architecture. NodeJS has its own EventLoop which is an infinite loop that receives requests and processes them.
JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.
There's a benchmark made by Fastify creators, it shows that express. js can handle ~15K requests per second, and the vanilla HTTP module can handle 70K rps.
To answer your question without getting into the nitty gritty of how Node works (which I advise you read), the behaviour you see is exactly what I'd expect to see based on your code.
For each Node instance running there is a single processing thread, in high-volume scenarios it's recommended to do as little CPU-bound operations as possible as to not block that thread. In your example, each request is running a 10s CPU-bound operation which means Node can't process any new requests until that request completes.
If you want to better demonstrate the throughput of Node, use a non-blocking example e.g. use of a timer
app.get('*', function (req, res, next) {
var requestTime = new Date().getTime(),
executionTime;
setTimeout(() => {
res.send({
requestTime,
executionTime: new Date().getTime()
});
}, 10000);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With