Profiling and performance

Topic 4 of 4 in Performance & scaling7 min readIntermediateFree course

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:

A performance workflow: 1 measure with a load test and p95 latency, 2 profile with –cpu-prof and flame graphs, 3 fix the hotspot with one change, 4 measure again and compare. Repeat until it meets the target.

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:

Terminal
npx autocannon -c 50 -d 20 http://localhost:3000/api/v1/courses

That 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:

JavaScript
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:

Terminal
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 written

Open 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.stringify of huge objects,
  • sorting or filtering large arrays on every request,
  • synchronous fs or crypto calls,
  • 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:

JavaScript
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:

  1. 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.
  2. Indexes. A query filtering on an unindexed column scans the whole table. EXPLAIN ANALYZE in Postgres shows what it’s doing.
  3. Pagination and smaller payloads. Don’t return 10,000 rows or fields nobody uses.
  4. Parallelise independent I/O with Promise.all instead of awaiting one call after another.
  5. Cache expensive, frequently read results (see Caching with Redis).
  6. Move CPU work off the main thread — worker threads or background jobs.
  7. Compression and HTTP caching — gzip/brotli responses (often done by the proxy), Cache-Control and ETag headers.
  8. 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.

Exercise

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.

JavaScript
import { monitorEventLoopDelay } from 'node:perf_hooks';
// your code here

Summary

  • 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-prof and 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.