3

Hi everyone i have recently started to dive into clusters on Node and i'm having an issue with PM2, this is the code i'm trying to run using clusters (server.js):

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

const app = express();

function delay (duration) {
    const startTime = Date.now();

    while (Date.now() - startTime < duration) {
        // event loop is blocked...
    }
}

app.get('/', (req, res) => {
    res.send(`Performance example running on process ${process.pid}`);
})

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

// Set scheduling policy to Round Robin for Windows
cluster.schedulingPolicy = cluster.SCHED_RR;

if (cluster.isMaster) {
    console.log('Master process has been started');
    const NUM_WORKERS = os.cpus().length;

    for (let i = 0; i < NUM_WORKERS; i++) {
        cluster.fork()
    }
}
else {
    app.listen(3000, () => {
        console.log(`Worker process ${process.pid} running on port 3000`);
    });
}

When i run the command pm2 start server.js it starts 8 different Node windows (since i have 8 threads in my CPU) and it works fine, i open up 8 different chrome tabs and hit the /timer endpoint and they all respond back in around the same time. The problem is when i remove all the code related to the cluster (since i want pm2 to take care of that and not doing it manually) it stops working, i run pm2 start server.js -i max or pm2 start server.js, it creates 8 different processes (not opening 8 different windows) and Round Robing doesn't work, the same process is taking care of all the responses. I opened up just two Chrome tabs, hit /timer and they all responded secuentially (9s, 17s) and the same process was handling them.

0 Answers0