'Node/Express cluster not processing in parallel

Here's my code from a course:

const express = require('express');
const cluster = require('cluster');

const app = express();

function delay(duration) {
  const startTime = Date.now();
  while(Date.now() - startTime < duration) {
    //event loop is blocked...
  }
}

app.get('/timer', (req, res) => {
  delay(9000);
  res.send(`Ding ding ding! ${process.pid}`);
});

console.log('Running server.js...');
if (cluster.isPrimary) {
  console.log('Master has been started...');
  cluster.fork();
  cluster.fork();
} else {
  console.log('Worker process started.');
  app.listen(3000);
}

In the lecture when the instructor visits http://localhost:3000/timer in two different tabs simultaneously, the requests finish at about the same time. However, when I do it, the first request finishes in 9 seconds and the second one finishes another 9 seconds after the first as if the requests were processed sequentially.

I've even tried using the PM2 module in cluster mode to see if there was anything wrong with the code but the requests are still processed sequentially. I tried the solution in the following thread: Blocking requests not running simultaneously on PM2 but it did not work for me.

Anyone have any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source