0
0
Node.jsframework~30 mins

When to use workers vs cluster in Node.js - Hands-On Comparison

Choose your learning style9 modes available
When to Use Workers vs Cluster in Node.js
📖 Scenario: You are building a Node.js server that needs to handle multiple tasks efficiently. Some tasks are CPU-heavy, and others involve handling many client requests. You want to learn when to use worker_threads and when to use the cluster module to improve your server's performance.
🎯 Goal: Build a simple Node.js setup that demonstrates creating a worker thread for CPU-intensive work and a cluster to handle multiple server processes. This will help you understand when to use each approach.
📋 What You'll Learn
Create a worker thread to perform a CPU-heavy calculation
Create a cluster to spawn multiple server processes
Use exact variable and function names as instructed
Follow Node.js modern syntax with ES modules
💡 Why This Matters
🌍 Real World
Node.js servers often need to handle CPU-heavy tasks and many client requests simultaneously. Using workers and clusters helps improve performance and reliability.
💼 Career
Understanding workers and clusters is essential for backend developers working with Node.js to build scalable and efficient server applications.
Progress0 / 4 steps
1
Create a CPU-intensive task function
Create a function called heavyComputation that takes a number n and returns the sum of all numbers from 1 to n. Use a simple for loop inside the function.
Node.js
Need a hint?

Use a for loop from 1 to n and add each number to a sum variable.

2
Set up a worker thread to run the CPU task
Import Worker from worker_threads. Create a new Worker instance called worker that runs a file named worker.js. This file will use the heavyComputation function.
Node.js
Need a hint?

Use import { Worker } from 'worker_threads' and create worker with new Worker(new URL('./worker.js', import.meta.url)).

3
Set up a cluster to handle multiple server processes
Import cluster and os modules. Create a variable numCPUs that stores the number of CPU cores using os.cpus().length. Use cluster.isPrimary to check if the current process is the primary. If yes, use a for loop with variable i from 0 to numCPUs to fork workers using cluster.fork().
Node.js
Need a hint?

Use os.cpus().length to get CPU count and cluster.fork() inside a for loop to create workers.

4
Complete the cluster setup with a simple server
Inside the else block of if (cluster.isPrimary), create a simple HTTP server using import http from 'http'. The server should listen on port 3000 and respond with 'Hello from worker ' + process.pid for every request.
Node.js
Need a hint?

Use http.createServer inside the else block and listen on port 3000.