In Node.js, clustering is used to improve performance by:
- A: Running multiple instances of the event loop on different CPU cores
- B: Combining all requests into a single thread
- C: Reducing the number of CPU cores used
- D: Disabling asynchronous operations
Which option correctly explains why clustering improves performance?
Think about how Node.js uses CPU cores and how clustering can help.
Node.js runs on a single thread by default. Clustering creates multiple processes, each with its own event loop, allowing the app to use multiple CPU cores and handle more requests simultaneously.
Consider this Node.js code using clustering:
const cluster = require('cluster');
const http = require('http');
const numCPUs = 2;
if (cluster.isPrimary) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Worker ${process.pid} says hello`);
}).listen(8000);
}What will be the output when accessing http://localhost:8000 multiple times?
Think about how clustering distributes requests among workers.
Clustering forks multiple worker processes that share the same port. Incoming requests are distributed among these workers, so responses come from different process IDs.
You run a CPU-intensive task on a Node.js server. You measure CPU usage without clustering and then with clustering using 4 workers. Which data output best represents the CPU usage?
Consider how clustering uses multiple CPU cores.
Without clustering, Node.js uses one CPU core (100%). With 4 workers, it can use up to 4 cores (400%).
Find the error in this Node.js clustering code snippet:
const cluster = require('cluster');
const http = require('http');
if (cluster.isworker) {
http.createServer((req, res) => {
res.end('Hello from worker');
}).listen(3000);
} else {
for (let i = 0; i < 2; i++) {
cluster.fork();
}
}Check the correct property name to detect the worker process.
The correct property to check if the process is a worker is 'cluster.isWorker'. The code uses 'cluster.isworker' which is undefined (case-sensitive), causing all processes to execute the else block and fork infinitely.
You manage a Node.js web app with high traffic and CPU-intensive tasks. You want to maximize performance using clustering. Which strategy is best?
Think about how to use CPU cores efficiently and balance load.
Forking one worker per CPU core maximizes CPU usage. A load balancer ensures requests are spread evenly, improving throughput and responsiveness.