Bird
Raised Fist0
Node.jsframework~20 mins

How cluster module works in Node.js - Practice Exercises

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Cluster Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a worker process dies in Node.js cluster?
Consider a Node.js cluster setup where the master forks several worker processes. What is the default behavior when one worker process unexpectedly exits?
AThe master restarts the entire cluster including all workers.
BThe master shuts down all other workers and exits.
CThe master ignores the dead worker and does not replace it.
DThe master automatically forks a new worker to replace the dead one.
Attempts:
2 left
💡 Hint
Think about how Node.js cluster maintains availability by managing worker processes.
📝 Syntax
intermediate
2:00remaining
Identify the correct way to create a cluster master and fork workers
Which code snippet correctly creates a cluster master that forks 2 worker processes?
A
const cluster = require('cluster');
if (cluster.isWorker) {
  cluster.fork();
  cluster.fork();
} else {
  console.log('Master running');
}
B
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
  cluster.fork();
} else {
  console.log('Worker running');
}
C
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.start(2);
} else {
  console.log('Worker running');
}
D
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.createWorkers(2);
} else {
  console.log('Worker running');
}
Attempts:
2 left
💡 Hint
Check the official cluster API properties and methods for forking workers.
🔧 Debug
advanced
2:00remaining
Why does this cluster code cause workers not to start?
Given the code below, why do no worker processes start? const cluster = require('cluster'); if (cluster.isMaster) { for (let i = 0; i < 2; i++) { cluster.fork; } } else { console.log('Worker started'); }
Node.js
const cluster = require('cluster');

if (cluster.isMaster) {
  for (let i = 0; i < 2; i++) {
    cluster.fork;
  }
} else {
  console.log('Worker started');
}
Acluster.isMaster is deprecated and should be replaced with cluster.isPrimary.
BThe else block should be inside the for loop to start workers.
Ccluster.fork is missing parentheses, so the function is not called.
DThe cluster module requires an explicit call to cluster.start() to begin.
Attempts:
2 left
💡 Hint
Look carefully at how functions are called in JavaScript.
state_output
advanced
2:00remaining
What is the output of this cluster worker count code?
What will be printed when running this code? const cluster = require('cluster'); if (cluster.isMaster) { console.log('Master process'); cluster.fork(); cluster.fork(); console.log('Workers count:', Object.keys(cluster.workers).length); } else { console.log('Worker process'); }
Node.js
const cluster = require('cluster');

if (cluster.isMaster) {
  console.log('Master process');
  cluster.fork();
  cluster.fork();
  console.log('Workers count:', Object.keys(cluster.workers).length);
} else {
  console.log('Worker process');
}
A
Master process
Workers count: 0
Worker process
Worker process
B
Master process
Worker process
Worker process
Workers count: 2
C
Master process
Workers count: 2
Worker process
Worker process
D
Master process
Workers count: 2
Attempts:
2 left
💡 Hint
Consider when the workers are fully registered in the cluster.workers object.
🧠 Conceptual
expert
2:00remaining
How does Node.js cluster module distribute incoming connections?
In a Node.js cluster with multiple worker processes, how are incoming TCP connections distributed among workers by default?
AThe master process uses a round-robin algorithm to distribute connections evenly to workers.
BEach worker listens on the same port independently and the OS load balances connections.
CThe first worker accepts all connections until it crashes, then the next worker takes over.
DConnections are distributed randomly without any specific order or balancing.
Attempts:
2 left
💡 Hint
Think about how Node.js cluster manages load balancing internally.

Practice

(1/5)
1. What is the main purpose of the cluster module in Node.js?
easy
A. To provide a graphical user interface for Node.js apps
B. To manage database connections efficiently
C. To handle file system operations asynchronously
D. To create multiple worker processes to use all CPU cores

Solution

  1. Step 1: Understand the cluster module role

    The cluster module allows Node.js to create multiple worker processes.
  2. Step 2: Recognize the benefit

    These workers use all CPU cores to improve performance by handling requests in parallel.
  3. Final Answer:

    To create multiple worker processes to use all CPU cores -> Option D
  4. Quick Check:

    cluster module = multiple workers for CPU cores [OK]
Hint: Cluster = multiple processes for CPU cores [OK]
Common Mistakes:
  • Confusing cluster with database or file system modules
  • Thinking cluster manages UI or frontend
  • Assuming cluster runs code in a single process
2. Which of the following is the correct way to check if the current process is the master in a cluster setup?
easy
A. if (cluster.isMaster) { ... }
B. if (cluster.isPrimary) { ... }
C. if (cluster.isWorker) { ... }
D. if (cluster.isMain) { ... }

Solution

  1. Step 1: Recall the updated property name

    In recent Node.js versions, cluster.isPrimary replaces cluster.isMaster.
  2. Step 2: Identify the correct syntax

    Using cluster.isPrimary correctly checks if the process is the primary (master) process.
  3. Final Answer:

    if (cluster.isPrimary) { ... } -> Option B
  4. Quick Check:

    Primary process check = cluster.isPrimary [OK]
Hint: Use cluster.isPrimary, not isMaster [OK]
Common Mistakes:
  • Using deprecated cluster.isMaster instead of cluster.isPrimary
  • Confusing isWorker with isPrimary
  • Using non-existent properties like isMain
3. Consider this Node.js cluster code snippet:
const cluster = require('cluster');
const http = require('http');

if (cluster.isPrimary) {
  cluster.fork();
  cluster.fork();
} else {
  http.createServer((req, res) => {
    res.end('Worker ' + process.pid);
  }).listen(8000);
}

What will happen when you visit http://localhost:8000 multiple times?
medium
A. You will see responses from different worker process IDs
B. Only one worker will handle all requests
C. The server will crash because of multiple forks
D. You will get a syntax error on startup

Solution

  1. Step 1: Understand cluster.fork creates workers

    Two workers are created, each running the HTTP server on port 8000.
  2. Step 2: Recognize load balancing behavior

    Requests are distributed between workers, so responses show different process IDs.
  3. Final Answer:

    You will see responses from different worker process IDs -> Option A
  4. Quick Check:

    Multiple workers share port, respond with different PIDs [OK]
Hint: Multiple forks = multiple workers respond differently [OK]
Common Mistakes:
  • Thinking only one worker handles all requests
  • Assuming server crashes due to multiple forks
  • Expecting syntax errors from this code
4. What is wrong with this cluster code snippet?
const cluster = require('cluster');
if (cluster.isPrimary) {
  cluster.fork();
} else {
  console.log('Worker running');
}
medium
A. cluster.isPrimary is deprecated, should use isMaster
B. No call to cluster.fork in the worker process
C. Missing server code inside worker
D. No error, code works fine

Solution

  1. Step 1: Check cluster usage

    The primary forks one worker, which only logs a message but does not start a server.
  2. Step 2: Identify missing functionality

    Without server code, the worker does not handle requests, so the cluster setup is incomplete.
  3. Final Answer:

    Missing server code inside worker -> Option C
  4. Quick Check:

    Worker must run server code to handle requests [OK]
Hint: Workers need server code to handle requests [OK]
Common Mistakes:
  • Confusing isPrimary with deprecated isMaster
  • Expecting cluster.fork in worker process
  • Assuming code runs without server in worker
5. You want to create a cluster that automatically restarts a worker if it crashes. Which approach correctly implements this behavior?
hard
A. Listen to the 'exit' event on cluster and fork a new worker inside the handler
B. Use setInterval to fork new workers every second
C. Call cluster.fork() only once at startup and never again
D. Use cluster.disconnect() inside the worker to restart itself

Solution

  1. Step 1: Understand worker crash handling

    The primary process can listen to the 'exit' event when a worker dies.
  2. Step 2: Restart worker on exit

    Inside the 'exit' event handler, calling cluster.fork() creates a new worker to replace the crashed one.
  3. Final Answer:

    Listen to the 'exit' event on cluster and fork a new worker inside the handler -> Option A
  4. Quick Check:

    Restart crashed workers by handling 'exit' event [OK]
Hint: Use 'exit' event to restart workers automatically [OK]
Common Mistakes:
  • Forking workers repeatedly with setInterval causes overload
  • Not restarting workers after crash leads to downtime
  • Using cluster.disconnect() inside worker does not restart it