My Blog

My WordPress Blog

My Blog

My WordPress Blog

Optimize Performance with cluster Module

Tip:

Use the cluster module to take advantage of multi-core systems by creating child processes that share the same server port.

Example:

javascriptCopy codeconst cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
console.log(Master ${process.pid} is running);
for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
    console.log(Worker ${worker.process.pid} died);
});
} else {
http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello, World!\n');
}).listen(8000);
console.log(Worker ${process.pid} started);
}

Reason: Clustering enables better CPU utilization and can handle more concurrent connections by distributing the load.

Optimize Performance with cluster Module

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top