Performance & Best Practices
Blocking vs non-blocking, clustering, caching, and profiling.
Rule zero: don't block the event loop
Everything about Node performance follows from one fact: all requests share one JavaScript thread. Any synchronous work delays *every* pending callback. A 500ms JSON.parse of a giant payload means every concurrent user waits 500ms extra.
Usual suspects for accidental blocking:
- Sync fs APIs (
readFileSync) inside request handlers - Parsing or stringifying huge JSON blobs
- Complex regular expressions on untrusted input (catastrophic backtracking, aka ReDoS)
- Tight CPU loops over large arrays
Keep per-callback work small; the event loop's health *is* your latency.
// If the loop is healthy, a 0ms timer fires almost instantly.
// Block the thread, and the timer fires late:
const scheduled = Date.now();
setTimeout(() => {
console.log("timer delay:", Date.now() - scheduled, "ms (wanted ~0)");
}, 0);
// Simulate a blocking request handler (~150ms of sync work):
const start = Date.now();
while (Date.now() - start < 150) { /* burning CPU */ }
console.log("blocked for", Date.now() - start, "ms");Scaling across cores: cluster and worker threads
One Node process uses one core for JavaScript. To use a whole machine:
- cluster module / multiple processes — run one process per core, all sharing a port; the OS distributes connections. Best for scaling an I/O-bound server. Process managers like PM2, or container orchestrators, do this for you in production.
- worker_threads — spin up extra JavaScript threads *inside* one process, each with its own event loop. Best for offloading CPU-bound tasks (image processing, parsing, crypto) so the main thread keeps serving requests.
Rule of thumb: cluster for more traffic, workers for heavy computation.
const cluster = require("node:cluster");
const http = require("node:http");
const os = require("node:os");
if (cluster.isPrimary) {
const cores = os.availableParallelism();
console.log("Forking " + cores + " workers");
for (let i = 0; i < cores; i++) cluster.fork();
cluster.on("exit", (worker) => {
console.log("worker " + worker.process.pid + " died - restarting");
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.end("handled by pid " + process.pid);
}).listen(3000);
}Caching: the cheapest speedup
The fastest work is work you skip. Caching stores expensive results for reuse:
- In-memory caches (a
Mapin your process) — microsecond reads; lost on restart, not shared between instances - External caches (Redis, Memcached) — shared across processes and servers; survive restarts
- HTTP caching —
Cache-ControlandETagheaders let clients and CDNs skip requests entirely
The hard part is invalidation: every cache needs a story for staleness — a TTL (time to live), an explicit purge on writes, or both. A cache without an expiry plan is a bug factory.
const cache = new Map();
function cached(key, ttlMs, compute) {
const hit = cache.get(key);
if (hit && Date.now() < hit.expires) {
console.log("cache HIT: " + key);
return hit.value;
}
console.log("cache MISS: " + key + " (computing...)");
const value = compute();
cache.set(key, { value, expires: Date.now() + ttlMs });
return value;
}
const slowSquare = (n) => { for (let i = 0; i < 1e6; i++); return n * n; };
console.log(cached("sq:12", 5000, () => slowSquare(12))); // MISS
console.log(cached("sq:12", 5000, () => slowSquare(12))); // HITMeasure before you optimize
Intuition about performance is usually wrong — profile first. The toolkit, from quick to deep:
console.time/performance.now()— quick timing of a suspect block- Autocannon or similar load generators — measure real requests-per-second and latency percentiles
node --cpu-prof app.js— writes a CPU profile you open in Chrome DevTools to see exactly which functions burn timenode --inspect— attach DevTools live: profiler, heap snapshots, debugger
Optimize the top of the profile, re-measure, repeat. Anything else is guessing.
const { performance } = require("perf_hooks");
function timeIt(label, fn) {
const start = performance.now();
const result = fn();
const ms = (performance.now() - start).toFixed(2);
console.log(label + ": " + ms + "ms");
return result;
}
const n = 5_000_00;
timeIt("array push loop", () => {
const arr = [];
for (let i = 0; i < n; i++) arr.push(i);
return arr.length;
});
timeIt("Array.from", () => Array.from({ length: n }, (_, i) => i).length);Everyday best practices
A checklist that prevents most Node performance and reliability problems:
- Use async APIs in request paths; sync APIs only at startup
- Stream large payloads instead of buffering them whole
- Set timeouts on all outbound calls — a hung dependency must not hang you
- Watch for memory leaks: unbounded caches and arrays, forgotten event listeners and intervals
- Run NODE_ENV=production in production — libraries enable optimizations based on it
- Add health checks and metrics (event-loop delay, heap usage, request latency) so regressions surface before users notice
- Keep dependencies updated — performance fixes ship constantly
Check your understanding
5 questionsQuestion 1 of 5
Score: 0