← Back to Node.js, page 9

nodejs-0180 · Hard senior

A Node.js service in production is slow or restarting. How do you triage it in the first fifteen minutes, and what diagnostics can you collect safely?

First stabilise, then diagnose. Check what changed (deploy, traffic, dependency), look at the four signals (error rate, latency, CPU, memory) and the event loop, restart or roll back if users are hurt, and collect evidence before you destroy it: logs, a diagnostic report, a heap snapshot, a CPU profile. Classify the failure (CPU, memory, blocked event loop, resource exhaustion, a slow dependency) and then fix and prevent.

Full answer

Minutes 0 to 5: stabilise and orient

  • Who is affected, since when, and what changed? Check deploys, config, traffic, dependency status pages and recent alerts.
  • If a recent release correlates, roll back first. Diagnose afterwards.
  • Look at dashboards: request rate, error rate, latency (p50 and p99), CPU, memory, event loop delay or utilization, open handles and file descriptors, database and downstream latency, restarts.

Minutes 5 to 15: classify

  • High CPU, normal I/O: a hot loop, a regex, large JSON work, a crypto call. Capture a CPU profile (node --cpu-prof or the inspector).
  • Memory grows then OOM kill (exit code 137 in containers, or a V8 heap error): a leak or a huge payload. Take heap snapshots over time.
  • Event loop blocked (latency for everything, CPU one core at 100 percent, health checks time out): synchronous work. Check event loop delay and profile.
  • Errors such as ECONNRESET, ETIMEDOUT, EMFILE: a dependency or a limit. Check connection pools, file descriptor limits and downstream health.
  • Low CPU and slow requests: waiting on a database, lock or external API. Look at traces and timeouts.

Collecting evidence safely

  • Keep one instance out of rotation, then inspect it. Do not attach the debugger to a customer-facing instance.
  • process.report.getReport() (or --report-on-signal and kill -USR2) writes a JSON diagnostic report with JavaScript and native stacks, heap statistics, libuv handles and resource usage.
  • v8.writeHeapSnapshot() blocks the process and needs memory about equal to the heap, so use it on an isolated instance.
  • --heapsnapshot-near-heap-limit and --report-on-fatalerror capture data right before a crash.
  • Always save logs, metrics and traces with timestamps for the post-incident review.

After: write a blameless post-incident review, add the missing alert, add a regression test or a load test, and add limits (timeouts, concurrency, memory) that would have contained it.

javascript
const v8 = require('node:v8');
const { performance, monitorEventLoopDelay } = require('node:perf_hooks');

// A small "snapshot" function: the quick facts to look at during an incident.
function snapshot() {
  const report = process.report.getReport();
  const heap = v8.getHeapStatistics();
  const memory = process.memoryUsage();
  const elu = performance.eventLoopUtilization();
  return {
    reportSections: Object.keys(report),
    nodeVersion: report.header.nodejsVersion,
    heapUsedMB: Math.round(memory.heapUsed / 1048576),
    heapLimitMB: Math.round(heap.heap_size_limit / 1048576),
    heapUsedPercent: Math.round((heap.used_heap_size / heap.heap_size_limit) * 100),
    openFileDescriptorLimit: report.userLimits.open_files.soft,
    libuvHandles: report.libuv.length,
    activeResources: process.getActiveResourcesInfo().sort(),
    eventLoopUtilizationAvailable: typeof elu.utilization === 'number',
    uptimeSeconds: Math.round(process.uptime()),
  };
}

const delay = monitorEventLoopDelay({ resolution: 10 });
delay.enable();

const server = require('node:http').createServer((req, res) => res.end('ok')).listen(0, '127.0.0.1', () => {
  const s = snapshot();
  console.log('report sections       :', s.reportSections.join(', '));
  console.log('node version known    :', s.nodeVersion === process.version);
  console.log('heap used under limit :', s.heapUsedMB < s.heapLimitMB);
  console.log('fd limit is a number  :', typeof s.openFileDescriptorLimit === 'number' || s.openFileDescriptorLimit === 'unlimited');
  console.log('active resources      :', s.activeResources.join(', '));
  console.log('ELU available         :', s.eventLoopUtilizationAvailable);

  // The event loop delay histogram is the quickest check for a blocked loop.
  setTimeout(() => {                               // let the histogram run for a moment first
    const end = Date.now() + 120;
    while (Date.now() < end) {}                    // block the loop on purpose for 120 ms
    setTimeout(() => {
      delay.disable();
      console.log('max loop delay above 100 ms after the blocking loop:', delay.max / 1e6 > 100);
      server.close();
    }, 100);
  }, 50);
});

The script collects facts that matter in an incident from a running process and shows that the event loop delay histogram notices a 120 ms block. It is a starting point, not a monitoring system. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): report sections : header, javascriptStack, javascriptHeap, nativeStack, resourceUsage, uvthreadResourceUsage, libuv, workers, environmentVariables, userLimits, sharedObjects node version known : true heap used under limit : true fd limit is a number : true active resources : TCPServerWrap ELU available : true max loop delay above 100 ms after the blocking loop: true

Key points

  • Stabilise first, roll back if a release correlates.
  • Classify the failure: CPU, memory, event loop, resource limits or a dependency.
  • Collect reports, profiles and snapshots from an isolated instance.
  • process.report gives a quick JSON diagnostic snapshot.
  • Finish with a review, alerts and limits.

Common mistakes

  • Restarting everything before saving any evidence.
  • Taking a heap snapshot on a busy production instance.
  • Changing several things at once and losing the cause.
  • Debugging before rolling back an obvious bad release.
  • No alert on event loop delay, memory growth or restarts.

Follow-ups

  • What does exit code 137 mean for a container?
  • How do you enable a diagnostic report on a signal?
  • What goes into a blameless post-incident review?

Tips

  • Say 'stabilise first'.
  • Name the five failure classes.
  • Mention isolating one instance for evidence.