Roadmap › Node.js — Runtime Internals, Express, APIs and SQL Server › Module: Performance and Production
Lessons in this course (11)
10. Scaling Node — cluster, worker threads, child processes and PM2
Advanced★ Must knowLesson 10 of 11
| Tool | Use |
|---|---|
| cluster module / PM2 cluster mode | Run one Node process per CPU core sharing the port — scale an API on one machine |
| worker_threads | Run CPU-heavy JavaScript in parallel threads (separate V8 isolates) without blocking the event loop |
child_process (spawn, exec, fork) | Run other programs/scripts as separate processes |
| Horizontal scaling | Many containers behind a load balancer (Kubernetes, App Service, ECS) — keep the app stateless |
js
// CPU-heavy work in a worker thread
import { Worker } from 'node:worker_threads';
function hashInWorker(data) {
return new Promise((resolve, reject) => {
const w = new Worker(new URL('./hash-worker.js', import.meta.url), { workerData: data });
w.once('message', resolve); w.once('error', reject);
});
}bash
pm2 start src/server.js -i max --name shop-api # cluster mode, one process per core, auto-restart
pm2 logs; pm2 reload shop-api # zero-downtime reloadPerformance tips: never block the event loop (sync fs/crypto in request paths, huge JSON.stringify), use streams for big data, connection pooling, caching (Redis), compression, UV_THREADPOOL_SIZE for heavy fs/crypto, measure with clinic doctor/--prof, watch event-loop lag and heap usage, avoid memory leaks (global caches, listeners never removed — MaxListenersExceededWarning).