0
0
Node.jsframework~10 mins

Forking workers per CPU core in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Forking workers per CPU core
Start Master Process
Get CPU Core Count
For each CPU core
Fork a Worker Process
Workers run tasks in parallel
Master listens for worker exit
If worker exits, fork a new one
End
The master process counts CPU cores, forks one worker per core, and restarts workers if they exit.
Execution Sample
Node.js
import cluster from 'node:cluster';
import os from 'node:os';

if (cluster.isPrimary) {
  const cpuCount = os.cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }
}
This code forks one worker process per CPU core from the master process.
Execution Table
StepActionValue/ResultNotes
1Check if process is mastercluster.isPrimary = trueMaster process starts
2Get CPU core countcpuCount = 4Assuming 4 cores on machine
3Start loop i=0i=0First iteration
4Fork workerWorker 1 createdWorker process 1 starts
5Increment ii=1Next iteration
6Fork workerWorker 2 createdWorker process 2 starts
7Increment ii=2Next iteration
8Fork workerWorker 3 createdWorker process 3 starts
9Increment ii=3Next iteration
10Fork workerWorker 4 createdWorker process 4 starts
11Increment ii=4Loop ends, i == cpuCount
12Master listens for worker exitIf worker exits, fork new workerEnsures continuous availability
13Workers run tasksParallel processingWorkers handle workload independently
14ExitAll workers runningMaster process waits
💡 Loop ends when i equals cpuCount; all workers forked.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
iundefined01234
cpuCountundefined44444
cluster.isPrimaryundefinedtruetruetruetruetrue
Key Moments - 3 Insights
Why do we check if cluster.isPrimary before forking?
Because only the master process should fork workers. Workers should not fork more processes. See execution_table step 1.
What happens if we don't fork one worker per CPU core?
We might not fully use all CPU cores, leading to less efficient processing. The loop in steps 3-11 ensures one worker per core.
Why does the master listen for worker exit and fork new ones?
To keep the system running smoothly by replacing any worker that crashes or exits unexpectedly, as shown in step 12.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'i' when the third worker is forked?
A2
B3
C1
D4
💡 Hint
Check steps 7 and 8 where i increments and the third worker is created.
At which step does the loop end because i equals cpuCount?
AStep 10
BStep 11
CStep 12
DStep 9
💡 Hint
Look for the step where i becomes 4 and the loop stops.
If the machine has 8 CPU cores, how many times will the loop run?
A4
B6
C8
D1
💡 Hint
Refer to variable_tracker for cpuCount and loop iterations.
Concept Snapshot
Forking workers per CPU core in Node.js:
- Use cluster.isPrimary to check master process
- Get CPU count with os.cpus().length
- Loop from 0 to cpuCount-1
- Fork a worker each iteration
- Master listens for worker exit to restart
- This uses all CPU cores for parallel work
Full Transcript
In Node.js, to use all CPU cores, the master process first checks if it is the primary process using cluster.isPrimary. It then gets the number of CPU cores with os.cpus().length. A loop runs from zero up to one less than the CPU count, and in each loop iteration, the master forks a new worker process. Each worker runs independently to handle tasks in parallel. The master also listens for any worker exiting and forks a new one to keep the system running smoothly. This approach maximizes CPU usage by having one worker per core.