Simultaneous requests are not being handled by different processes. Doesn't seem to be an OS issue as I have tested it on both Windows and Linux.
const express = require('express');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const app = express();
const PORT = 3000;
app.use((req, res, next) => {
console.log(`Route ${req.url} handled by ${process.pid}.`);
next();
});
app.get('/', (req, res) => {
res.send(`Hello from Node! Request handled by ${process.pid}`);
});
const _delay = (duration) => {
const startTime = Date.now();
while (Date.now() - startTime < duration) {
// does nothing
}
};
app.get('/timer/:time', (req, res) => {
_delay(Number(req.params.time));
res.send(`Time's Up! Request handled by ${process.pid}.`);
});
if (cluster.isPrimary) {
console.log('Master started...');
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
app.listen(PORT, () => {
console.log(`Server started on port ${PORT} with PID ${process.pid} ...`);
});
}
If I request the blocking route first and then the non-blocking one, they should be handled by different processes, but the entire server is getting blocked.