Lesson 9 of 9 · 26m
Observability and Incident Debugging for JavaScript Runtimes
The metrics, traces, heap tools, and runtime diagnostics that separate a quick diagnosis from a week of guessing — plus the portability differences between Node, Bun, and Deno.
When a JavaScript service degrades, the first wrong move is adding more logging statements randomly. The second wrong move is restarting everything and losing the evidence. Runtime incidents are stateful: heap shape, event-loop delay, open handles, dependency latency, garbage collection, threadpool saturation. You need instrumentation before the incident, not after the postmortem.
RED and USE still apply
For services, track rate, errors, duration. For the process, track utilization, saturation, errors. In Node terms, the minimum useful process metrics are event-loop delay, active handles, RSS, heap used/external memory, GC behavior, CPU usage, and open file descriptors.
import { performance, monitorEventLoopDelay } from "node:perf_hooks";
const delay = monitorEventLoopDelay();
delay.enable();
setInterval(() => {
metrics.gauge("nodejs_eventloop_delay_p99_ms", delay.percentile(99) / 1e6);
metrics.gauge("nodejs_rss_bytes", process.memoryUsage().rss);
metrics.gauge("nodejs_heap_used_bytes", process.memoryUsage().heapUsed);
delay.reset();
}, 5_000);Do not average away tail latency. Event-loop p99 is often the first sign that a small synchronous code path became a queue for the whole process.
Async context is the hard part
A trace that starts at an HTTP handler but disappears inside promises and queue consumers is not observability. Node’s AsyncLocalStorage is the primitive for propagation:
import { AsyncLocalStorage } from "node:async_hooks";
export const requestContext = new AsyncLocalStorage();
export function withRequest(req, fn) {
return requestContext.run({ requestId: req.headers["x-request-id"] }, fn);
}But async_hooks behavior is one of the areas where runtime compatibility differs most. APM agents and instrumentation libraries rely on subtle ordering and lifecycle details. Verify tracing on the exact runtime you deploy, especially outside Node.
Heap snapshots beat heap theories
Memory leaks in JavaScript are usually retained object graphs, not “garbage collector failure.” Capture two or three snapshots over time and compare dominators/retained size. In Node:
node --inspect=0.0.0.0:9229 dist/server.jsThen connect Chrome DevTools or trigger heapsnapshots through tooling. In production, prefer controlled diagnostics endpoints or sidecar collection rather than exposing an inspector port to the network. --inspect is a remote code execution surface when reachable by untrusted users.
Look for growth tied to caches without eviction, listeners accumulating on long-lived emitters, closures capturing request objects, and “temporary” maps keyed by user/session forever.
CPU profiles explain flame, not vibes
Use the inspector or node --cpu-prof to capture CPU profiles. Read the flame graph by total time first. A hot JSON parser, regex, serializer, or template function is often more important than framework overhead.
node --cpu-prof --cpu-prof-dir=/var/tmp/profiles dist/server.jsKeep profiling artifacts out of public object storage. They can contain secrets in strings, source paths, and business data.
Correlation beats volume
One useful log line should carry service, version, environment, request ID, trace ID, route, status, duration, and error class. Ten unstructured lines without correlation are noise. For queue consumers, propagate trace context through message metadata. For workers, propagate identifiers explicitly in workerData or messages.
Runtime differences show up here first
Node has the deepest profiling ecosystem: inspector protocol, clinic.js, APM vendors, async hooks, corepack tooling, and years of documented incident recipes. Bun and Deno have debugging support and improving diagnostics, but the exact workflows and third-party integrations differ. If your organization depends on a particular APM agent, test it early; do not discover incompatibility after choosing a runtime.
Field notes
- Alert on event-loop lag and memory slope, not only CPU and HTTP 5xx.
- A restart can be mitigation, but capture metrics and artifacts first when safe.
- Sampling profilers are cheap enough for many production systems; continuous full tracing often is not.
- Validate correlation end-to-end: browser or client request → API → downstream service → queue job.
- Keep a documented “incident debugging runbook” per runtime. Port numbers, flags, artifact locations, and security rules should not be improvised during an outage.
Was this lesson helpful?