0
0
Node.jsframework~8 mins

Forking workers per CPU core in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Forking workers per CPU core
MEDIUM IMPACT
This pattern affects server-side request handling speed and responsiveness by utilizing multiple CPU cores to handle concurrent tasks.
Handling multiple incoming requests efficiently on a multi-core server
Node.js
import cluster from 'cluster';
import http from 'http';
import os from 'os';

if (cluster.isPrimary) {
  const cpuCount = os.cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello World');
  }).listen(8000);
}
Forking one worker per CPU core maximizes CPU usage and allows handling many requests in parallel.
📈 Performance GainImproves concurrency, reduces request queueing, and lowers INP by distributing load across cores.
Handling multiple incoming requests efficiently on a multi-core server
Node.js
import cluster from 'cluster';
import http from 'http';

if (cluster.isMaster) {
  // Fork only one worker
  cluster.fork();
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello World');
  }).listen(8000);
}
Using only one worker process underutilizes CPU cores, causing slower request handling under load.
📉 Performance CostBlocks handling multiple requests concurrently, leading to higher INP and slower response times.
Performance Comparison
PatternCPU UtilizationRequest ConcurrencyResponse DelayVerdict
Single worker processLow (uses 1 core)Low (serial requests)High (requests queue)[X] Bad
One worker per CPU coreHigh (uses all cores)High (parallel requests)Low (fast responses)[OK] Good
Rendering Pipeline
While this concept is server-side, it impacts the browser's interaction responsiveness by reducing server response delays.
Request Handling
Response Time
⚠️ BottleneckSingle-threaded server process limits concurrency and increases request wait times.
Core Web Vital Affected
INP
This pattern affects server-side request handling speed and responsiveness by utilizing multiple CPU cores to handle concurrent tasks.
Optimization Tips
1Fork one worker process per CPU core to maximize concurrency.
2Avoid single worker setups on multi-core servers to prevent request delays.
3Monitor server response times to verify effective worker utilization.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main benefit of forking one worker per CPU core in Node.js?
ASimplifies code by avoiding clusters
BImproves concurrency by using all CPU cores
CReduces memory usage by sharing one process
DIncreases single-thread performance
DevTools: Network
How to check: Open DevTools Network tab, send multiple requests quickly, and observe response times and concurrency.
What to look for: Look for reduced response times and overlapping request handling indicating parallel processing.