Full answer
Guessing about speed is usually wrong. A repeatable method:
- Define the symptom: high latency at the 95th percentile, high CPU, or memory growth.
- Measure at the right level.
Tools:
- Event loop delay: perf_hooks.monitorEventLoopDelay({ resolution: 10 }) records how late a timer fires. A max or p99 above 100 ms means something blocks the loop. This is the best single health number for a Node server.
- CPU profile: node --cpu-prof app.js writes a .cpuprofile file. Open it in Chrome DevTools or VS Code. A flame graph shows which functions use the most self time. node --inspect lets you attach and record on a running process. Tools such as 0x and clinic.js build flame graphs from the same data.
- Timing code: performance.now(), performance.mark and performance.measure give high-resolution timings, and performance.timerify wraps a function and reports its duration.
- Tracing: --trace-gc shows garbage collection pauses, and the diagnostics_channel module gives hooks for HTTP and database events in libraries.
- Under load: use autocannon or k6, because single requests hide contention.
Typical fixes: remove synchronous calls, avoid repeated JSON parse and stringify, cache results, batch database queries, stream large payloads, move CPU work to workers, and reduce garbage by reusing objects in hot paths.
Always measure again after a change, with the same load, and keep the number.
javascript
const { monitorEventLoopDelay, performance, PerformanceObserver } = require('node:perf_hooks');
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
function slowTask() {
const end = performance.now() + 120;
while (performance.now() < end) { /* block the event loop for 120 ms */ }
}
// Time a block of code with marks and measures.
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('measure', JSON.stringify(entry.name), 'took at least 100 ms:', entry.duration >= 100);
}
});
observer.observe({ entryTypes: ['measure'] });
setTimeout(() => {
performance.mark('start');
slowTask();
performance.mark('end');
performance.measure('slow task', 'start', 'end');
// Give the histogram a turn of the loop to record the delay.
setTimeout(() => {
histogram.disable();
console.log('event loop delay max is above 100 ms:', histogram.max / 1e6 > 100);
console.log('histogram has samples:', histogram.count > 0);
observer.disconnect();
}, 50);
}, 100);The delay histogram reports nanoseconds, so the code divides by one million to get milliseconds. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): measure "slow task" took at least 100 ms: true event loop delay max is above 100 ms: true histogram has samples: true
Key points
- Measure before changing anything.
- Event loop delay is the key health metric.
- --cpu-prof and flame graphs show hot functions.
- perf_hooks gives timing marks and measurements.
- Test under load and compare before and after.
Common mistakes
- Optimising code without a profile.
- Looking at average latency only, instead of p95 and p99.
- Profiling a debug build or an idle process.
- Measuring a single request instead of a load test.
Follow-ups
- What is the difference between self time and total time in a flame graph?
- How would you profile a production process safely?
- How do you measure GC pauses?
Tips
- Describe the loop: symptom, measure, fix, measure again.
- Name event loop delay as the first metric for a Node server.
- Mention percentile latency, not averages.