Measure event-loop delay and CPU cost before optimizing, capture a CPU profile, move genuinely CPU-bound work to a reusable worker pool, and avoid adding workers to ordinary asynchronous I/O.
What you will build
This tutorial produces a working, verifiable result rather than a command list. Read each command before running it, keep configuration in version control without secrets, and record the versions used for repeatable deployment.
1. Prepare the project
node --cpu-prof --cpu-prof-name=cpu.cpuprofile server.js
npx autocannon -c 50 -d 20 http://127.0.0.1:3000/work
ls -lh cpu.cpuprofile
Run preparation commands as an unprivileged application user unless a command explicitly requires sudo. A clean working tree and lockfile make rollback much easier.
2. Implement the solution
// worker.js
import {parentPort} from 'node:worker_threads';
parentPort.on('message',n=>{let result=0;for(let i=0;i<n;i++) result+=Math.sqrt(i);parentPort.postMessage(result);});
// pool concept: create a fixed number near availableParallelism(), queue jobs,
// correlate replies with job IDs, enforce timeouts, and terminate on shutdown.
Save the example in the filename indicated by its comment or surrounding instructions. Treat it as a minimal baseline: production applications should separate transport, business logic, persistence, and configuration into testable modules.
3. Verify end to end
node --inspect=127.0.0.1:9229 server.js
node --trace-gc server.js
pidstat -p "$(pgrep -n node)" 1
curl -fsS http://127.0.0.1:3000/metrics
Verification should cover both process state and a real request or data operation. A process that is merely running is not necessarily ready to serve traffic.
4. Troubleshooting and production notes
Worker threads help CPU-intensive JavaScript, not database or network I/O. Creating one worker per request costs more than a bounded pool. Measure latency percentiles, event-loop delay, throughput, CPU, memory, and garbage collection under representative load before and after each change.
Production checklist
- The supported Node.js LTS version and dependency lockfile are recorded.
- Configuration is validated at startup and secrets are stored outside source control.
- Input limits, authentication, authorization, timeouts, and error boundaries are explicit.
- Logs identify a request without exposing credentials or personal data.
- Health checks, graceful termination, resource limits, backup, and rollback have been tested.
Reference: official topic documentation. For production version selection, use a supported LTS line from the Node.js release schedule.