Profiling and performance
Overview
“Make it faster” is only useful advice once you know what is slow. Developers are notoriously bad at guessing — the slow part is rarely where you expect. Good performance work follows a simple loop:
Set a target first (“95% of requests under 200 ms at 500 requests per second”), so you know when to stop.
Measuring: load tests and percentiles
autocannon is a fast HTTP load-testing tool written in Node:
npx autocannon -c 50 -d 20 http://localhost:3000/api/v1/coursesThat runs 50 concurrent connections for 20 seconds and reports requests per second and latency. Pay attention to percentiles, not averages:
- p50 (median) — what a typical request experiences.
- p95 / p99 — the slowest 5% / 1%. A great average can hide a terrible p99, and at scale, 1% of users is a lot of people.
Load-test against something production-like (same Node version, similar data volume, NODE_ENV=production) — a laptop with an empty database tells you little. Tools like k6 and Artillery handle more complex scenarios.
The event loop: Node’s vital sign
In Node, the question “is something blocking?” is answered by event-loop delay — how late timers fire because the loop was busy. Measure it in production:
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
console.log({
p50: h.percentile(50) / 1e6, // nanoseconds → ms
p99: h.percentile(99) / 1e6,
max: h.max / 1e6,
});
h.reset();
}, 10_000).unref();A healthy API’s p99 delay is a few milliseconds. Tens or hundreds of milliseconds means something CPU-heavy or synchronous is running on the main thread — and every request is waiting for it.
Finding CPU hotspots
Start the app with the CPU profiler on, apply load, then stop it:
node --cpu-prof src/server.js
# in another terminal: npx autocannon -c 50 -d 20 http://localhost:3000/slow
# then Ctrl+C — a CPU.*.cpuprofile file is writtenOpen the .cpuprofile file in Chrome DevTools (Performance panel → load profile) or in VS Code. The flame graph shows which functions used the most CPU time: wide bars are where time goes. Typical culprits:
JSON.parse/JSON.stringifyof huge objects,- sorting or filtering large arrays on every request,
- synchronous
fsorcryptocalls, - expensive regular expressions,
- template rendering or validation of very large payloads.
You can also debug and profile live: node --inspect src/server.js, then open chrome://inspect in Chrome and attach DevTools to your server.
Finding memory leaks
A memory leak is memory that keeps growing because something keeps references it no longer needs. Typical causes in Node:
- caches (a
Map) without size limits or expiry, - event listeners added per request and never removed,
- timers (
setInterval) that capture large objects and are never cleared, - global arrays that only grow (
allRequests.push(req)).
Watch process.memoryUsage().heapUsed over time. If it climbs steadily under constant load and never drops after garbage collection, take heap snapshots and compare them:
import { writeHeapSnapshot } from 'node:v8';
process.on('SIGUSR2', () => console.log('Heap snapshot:', writeHeapSnapshot()));Load the snapshots in Chrome DevTools’ Memory panel and use the Comparison view: objects whose count keeps growing between snapshots are your leak.
The usual fixes
Profiling usually points to a handful of familiar fixes, roughly in order of how often they help:
- Fewer database round trips. The classic N+1 problem: loading 50 courses, then running one query per course for its lessons — 51 queries. Use a join or
WHERE course_id = ANY($1)for one query. - Indexes. A query filtering on an unindexed column scans the whole table.
EXPLAIN ANALYZEin Postgres shows what it’s doing. - Pagination and smaller payloads. Don’t return 10,000 rows or fields nobody uses.
- Parallelise independent I/O with
Promise.allinstead of awaiting one call after another. - Cache expensive, frequently read results (see Caching with Redis).
- Move CPU work off the main thread — worker threads or background jobs.
- Compression and HTTP caching — gzip/brotli responses (often done by the proxy),
Cache-ControlandETagheaders. - Keep Node updated. Each major version brings V8 performance improvements for free.
Instrument in production
Profiling on your laptop finds obvious problems; production data finds the rest. Record per-route latency and error rates, event-loop delay, memory and database query times. OpenTelemetry is the vendor-neutral standard for collecting this (traces show exactly which part of a request took the time), and services like Grafana, Datadog, New Relic and Sentry display it. You’ll set up the foundations in Logging and monitoring.
Fix the biggest bar first. A 2× speed-up of code that takes 1% of the time changes nothing. Profilers tell you where the 80% is.
Find the slow endpoint
Add a middleware that logs a warning when a request takes over 200 ms, and use monitorEventLoopDelay to log the event loop's p99 delay every 10 seconds. Then load-test an endpoint that sorts a 200,000-item array on every request with npx autocannon, watch the metrics, fix it by caching the sorted result, and compare.
import { monitorEventLoopDelay } from 'node:perf_hooks';
// your code hereimport { monitorEventLoopDelay } from 'node:perf_hooks';
app.use((req, res, next) => {
const start = performance.now();
res.on('finish', () => {
const ms = performance.now() - start;
if (ms > 200) console.warn(`SLOW ${req.method} ${req.originalUrl} ${ms.toFixed(0)}ms`);
});
next();
});
const loopDelay = monitorEventLoopDelay({ resolution: 20 });
loopDelay.enable();
setInterval(() => {
console.log(`event loop p99: ${(loopDelay.percentile(99) / 1e6).toFixed(1)}ms`);
loopDelay.reset();
}, 10_000).unref();
// Fix: sort once, not per request
const sorted = items.toSorted((a, b) => a.score - b.score);
app.get('/leaderboard', (req, res) => res.json(sorted.slice(0, 100)));
// Measure: npx autocannon -c 50 -d 20 http://localhost:3000/leaderboardSummary
- Measure before optimising: load-test, look at latency percentiles (p95, p99), and profile.
- Event-loop delay is the key Node health metric — high delay means something is blocking.
node --cpu-profand Chrome DevTools flame graphs show where CPU time goes.- Heap snapshots compared over time reveal memory leaks.
- Most wins come from fewer database round trips, indexes, caching, pagination and avoiding sync work.