Node.js monitoring in production: event loop, memory leaks, GC and the metrics that matter

How to measure event loop lag and utilization, track heap and garbage collection, find memory leaks, watch the libuv threadpool, and instrument Node.js with OpenTelemetry, with a metrics table, example alerts and a checklist.

Obseria TeamObseria
Summary
  • Node.js runs JavaScript on a single main thread, so event loop delay and event loop utilization are the first signals to watch: a busy loop slows down every request at once.
  • Memory problems show up as a steadily growing heap after garbage collection. Track heap used against the heap limit, GC time, and RSS against the container limit, and take heap snapshots to find the retaining code.
  • OpenTelemetry auto-instrumentation for Node.js adds traces for HTTP, databases and messaging with a single --require or --import flag, and runtime metrics complete the picture.

Node.js monitoring in production is different from monitoring a multi-threaded runtime such as the JVM. Your JavaScript runs on one main thread with one event loop. When that loop is blocked, by a large JSON parse, a synchronous crypto call or a long garbage collection pause, every request in that process waits. Classic host metrics such as CPU and memory still matter, but they do not tell you why a Node.js service suddenly answers in two seconds instead of twenty milliseconds.

This guide covers the signals that matter for Node.js performance monitoring: event loop delay and utilization, heap and garbage collection, how to find a Node.js memory leak, the libuv threadpool, HTTP latency and errors, unhandled rejections, worker threads, clustering and Kubernetes specifics. It then shows how to instrument a service with OpenTelemetry, lists the key metrics in one table, gives example alerts and closes with a checklist. For setup details with Obseria, see our Node.js monitoring integration.

Event loop delay and event loop utilization

The event loop picks up callbacks, timers and I/O completions and runs them one after another. Two metrics describe its health.

Event loop delay (lag) measures how late a timer fires compared to when it was scheduled. If a timer should run every 10 ms but runs after 150 ms, something held the loop for about 140 ms. Node.js has a built-in, low-overhead histogram for this: perf_hooks.monitorEventLoopDelay(). It samples at a configurable resolution and reports min, max, mean, stddev and percentile(p), all in nanoseconds. Track the p99 and the max per reporting interval, and reset the histogram after each read.

Event loop utilization (ELU) is the share of time the loop was busy rather than idle waiting for I/O. performance.eventLoopUtilization() returns idle, active and utilization; passing a previous result gives you the value for the interval in between. ELU close to 1 means the process is CPU-bound in JavaScript. It is a better saturation signal than process CPU, because CPU also includes GC threads and native work, and because a process can show moderate CPU while its single main thread is completely busy.

A minimal runtime sampler without external dependencies could look like this:

// example: sample event loop and heap every 10 s
const { monitorEventLoopDelay, performance } = require('node:perf_hooks');
const v8 = require('node:v8');

const h = monitorEventLoopDelay({ resolution: 20 }); // ms, example value
h.enable();
let lastElu = performance.eventLoopUtilization();

setInterval(() => {
  const elu = performance.eventLoopUtilization(lastElu);
  lastElu = performance.eventLoopUtilization();
  const heap = v8.getHeapStatistics();
  console.log(JSON.stringify({
    event: 'runtime.sample',
    loop_delay_p99_ms: h.percentile(99) / 1e6,
    loop_delay_max_ms: h.max / 1e6,
    elu: Number(elu.utilization.toFixed(3)),
    heap_used_bytes: heap.used_heap_size,
    heap_limit_bytes: heap.heap_size_limit,
    rss_bytes: process.memoryUsage.rss(),
  }));
  h.reset();
}, 10_000).unref();

In practice you would emit these as metrics rather than logs, which OpenTelemetry's runtime instrumentation or a client library such as prom-client does for you. Common causes of high loop delay are synchronous APIs (fs.readFileSync, crypto.pbkdf2Sync), large JSON.parse and JSON.stringify calls, expensive regular expressions, big array sorts or loops over entire datasets, and long GC pauses. A CPU profile shows which function holds the loop; continuous profiling keeps those profiles available for the moment the problem actually happened.

Heap, garbage collection and memory limits

V8 manages JavaScript objects on a heap that is split into spaces: a small young generation (new space) for short-lived objects and a larger old generation for objects that survive several collections. Minor GCs (scavenges) are frequent and fast; major GCs (mark-sweep-compact) are less frequent and can pause the main thread longer, although V8 does much of the marking concurrently.

The data sources are built in:

  • process.memoryUsage() returns rss, heapTotal, heapUsed, external and arrayBuffers. external and arrayBuffers cover memory outside the JavaScript heap, for example Buffers, which matter for services that handle files or network streams.
  • v8.getHeapStatistics() adds heap_size_limit, the maximum the heap may grow to, and v8.getHeapSpaceStatistics() breaks usage down per space.
  • A PerformanceObserver for the gc entry type reports each collection with its duration and kind, which is how runtime libraries derive GC duration histograms.

The heap limit is set with --max-old-space-size (in MiB). Without it, Node.js derives a default from available memory, and how this interacts with container memory limits depends on the Node.js version. In containers, set it explicitly and leave headroom below the container limit for native memory, Buffers, thread stacks and the code itself. If the heap limit is too close to the container limit, the kernel kills the process (an OOM kill) before V8 can report "JavaScript heap out of memory", and you lose the error message that would have told you what happened.

The most useful memory signal is not heap used in general, but heap used after a major GC over hours or days. A healthy service shows a sawtooth that returns to a stable baseline. A baseline that rises after every deployment-free day indicates a leak. Also watch the share of time spent in GC: if it climbs while the heap approaches its limit, V8 is collecting more and more often to free less and less, and latency suffers long before the crash.

How to find a Node.js memory leak

A memory leak in Node.js means that objects remain reachable, so the garbage collector cannot free them, although the application no longer needs them. Typical causes:

  • Unbounded caches and maps. A module-level Map or object used as a cache without size limit or TTL, often keyed by user ID, URL or request ID.
  • Event listeners that are never removed. Adding a listener per request to a long-lived emitter. Node.js prints a MaxListenersExceededWarning when more than 10 listeners (the default) are added to one event, which is a useful early hint.
  • Closures that capture large objects. A callback kept in a timer, queue or listener holds on to everything in its scope, such as a full request or response object.
  • Timers and intervals not cleared. setInterval created per connection or job and never cleared.
  • Global state per request. Arrays that collect data for debugging or metrics and grow forever; metric labels with unbounded values also grow memory in the metrics library.
  • Native or Buffer memory. Growth in RSS or external without heap growth points to Buffers, native addons or the allocator rather than JavaScript objects.

The standard tool is the heap snapshot. Take one snapshot after warm-up, generate load, take a second and a third, and compare them in Chrome DevTools (Memory tab) using the comparison view. Sort by retained size and follow the retainer chain from a growing object type back to the code that holds it. Ways to capture snapshots in production:

  • v8.writeHeapSnapshot() from an internal, protected admin endpoint
  • --heapsnapshot-signal=SIGUSR2, then kill -USR2 <pid>
  • --heapsnapshot-near-heap-limit=1 (example value) to write a snapshot automatically when the heap approaches its limit

Be aware of the cost: writing a snapshot blocks the event loop for the whole duration and can need memory of the same order as the heap itself. Take snapshots from an instance that has been removed from load balancing, and store them securely, because a heap snapshot contains everything in memory, including tokens and personal data.

The libuv threadpool

Not all asynchronous work in Node.js is truly non-blocking at the operating system level. libuv runs some operations on a small threadpool: most fs calls, dns.lookup (used by default when you connect by hostname), asynchronous crypto functions such as pbkdf2, scrypt and randomBytes, and zlib compression. Network sockets do not use the pool.

The pool has 4 threads by default. Set UV_THREADPOOL_SIZE as an environment variable when starting the process to change it; setting it later from JavaScript may not take effect, because the pool is created on first use. When the pool is saturated, operations queue up: password hashing takes longer, file reads stall and, a classic surprise, outgoing HTTP requests slow down because the DNS lookup waits behind them. There is no built-in metric for pool queue length, so look at it indirectly: span durations for DNS, file and crypto operations, and latency that rises with concurrency while ELU stays moderate.

HTTP latency, errors and unhandled rejections

For request-serving services, the familiar RED metrics apply: request rate, error rate and duration, ideally as a histogram per route and status code. The OpenTelemetry semantic conventions define http.server.request.duration (in seconds) with attributes such as http.route, http.request.method and http.response.status_code. Use the route template (/orders/:id), never the raw URL, as an attribute. Look at percentiles rather than averages; our article on debugging latency spikes in microservices explains how to go from a p99 spike to the slow spans behind it.

Errors in Node.js come in two forms that deserve dedicated monitoring:

  • Unhandled promise rejections. Since Node.js 15 the default mode is throw: an unhandled rejection crashes the process. The --unhandled-rejections flag changes this behaviour. Register a process.on('unhandledRejection') handler that logs the error with its stack trace and context, and count these events as a metric.
  • Uncaught exceptions. After an uncaughtException the process is in an undefined state. Log the error, flush telemetry, and let the process exit so that the supervisor restarts it. Do not keep serving traffic.

Count process restarts per service. A service that restarts every few hours due to OOM or crashes can look healthy in averaged latency graphs, while users see failed requests at every restart.

Worker threads, cluster, PM2 and Kubernetes

Worker threads. worker_threads run JavaScript in parallel, each with its own event loop and V8 heap. Monitor them separately: worker.performance.eventLoopUtilization() gives ELU per worker, and resourceLimits sets heap limits per worker. A saturated main loop with idle workers, or the reverse, tells you whether work is distributed as intended.

Cluster and PM2. The cluster module and PM2 cluster mode run several Node.js processes behind one port. Every process has its own event loop, heap and metrics. Label all telemetry with the process identity (for example service.instance.id or the PID), otherwise a single blocked process disappears in the average. If you expose Prometheus metrics, make sure each worker's metrics are aggregated correctly or scraped individually.

Kubernetes. A few points matter specifically for Node.js:

  • Set --max-old-space-size below the memory limit, as described above, and alert on OOM-killed containers.
  • CPU limits cause CPU throttling. For a single-threaded runtime, throttling shows up directly as event loop delay and latency spikes, often at moderate average CPU.
  • Do not tie liveness probes too tightly to request handling. A probe that times out during a long GC or a burst of synchronous work can restart pods under load and make an incident worse. Readiness probes are the better place to shed traffic.
  • Handle SIGTERM: stop accepting new connections, finish in-flight requests, flush telemetry and exit within the termination grace period.

OpenTelemetry auto-instrumentation for Node.js

OpenTelemetry provides a meta package, @opentelemetry/auto-instrumentations-node, that bundles instrumentations for HTTP, Express, Fastify, NestJS, gRPC, popular database clients, Redis, Kafka clients and more. Its register entry point starts the SDK with configuration from environment variables, so a service can be instrumented without code changes:

# example: zero-code setup for a CommonJS service
npm install --save @opentelemetry/api @opentelemetry/auto-instrumentations-node

export OTEL_SERVICE_NAME=checkout-api
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production

node --require @opentelemetry/auto-instrumentations-node/register app.js

# ESM applications use --import instead; depending on the Node.js and
# OpenTelemetry versions, an additional loader hook may be required
node --import @opentelemetry/auto-instrumentations-node/register app.mjs

Practical notes:

  • The instrumentation must load before the libraries it patches, which is why it is passed as a flag (or via NODE_OPTIONS) rather than imported somewhere in the code.
  • ESM support works differently from CommonJS and has changed across versions. Check the current OpenTelemetry JavaScript documentation for the Node.js version you run.
  • Some instrumentations, such as file system instrumentation, can create a large number of spans. Review which instrumentations are enabled and disable the ones you do not need via configuration or environment variables, depending on the package version.
  • Runtime metrics such as event loop delay, ELU, heap usage and GC duration are available through the Node.js runtime instrumentation, with names defined in the semantic conventions (for example nodejs.eventloop.delay.p99 and v8js.gc.duration). These conventions are still evolving; verify the names your version emits.
  • Add the trace ID to your logs, so that a log line from a failing request links to its trace. Most popular loggers have an OpenTelemetry instrumentation that does this.

Key Node.js metrics at a glance

MetricSourceWhat it tells you
Event loop delay p99 and maxmonitorEventLoopDelay(), runtime instrumentationHow long callbacks wait; directly visible as latency
Event loop utilizationperformance.eventLoopUtilization()Saturation of the main thread, better than process CPU
Heap used and heap limitv8.getHeapStatistics()Distance to "heap out of memory"
Heap used after major GC (trend)Heap metrics plus GC eventsLeak indicator over hours and days
GC duration by kindPerformanceObserver (gc)Pause time and share of time spent in GC
RSS, external, arrayBuffersprocess.memoryUsage()Native and Buffer memory, distance to container limit
HTTP request duration by routeOpenTelemetry HTTP instrumentationLatency percentiles per endpoint
Error rate by route and statusHTTP instrumentation, error trackingFailed requests, 5xx share
Unhandled rejections and uncaught exceptionsProcess handlers, logsBugs that crash or destabilise the process
Restarts and OOM killsKubernetes, process managerCrashes hidden by averaged graphs
CPU throttlingcgroup metricsLimits that slow down the event loop
Active handles and connectionsRuntime metrics, HTTP serverConnection leaks, pool exhaustion

Example alerts

The following rules are starting points. All thresholds are example values; derive your own from the normal behaviour of each service and from your SLOs. The PromQL uses the default metric names of the prom-client library; with OpenTelemetry runtime metrics the names differ.

# example: event loop delay p99 above 100 ms for 5 minutes (example value)
max by (service, instance) (nodejs_eventloop_lag_p99_seconds) > 0.1

# example: more than 10 % of time spent in GC over 10 minutes (example value)
sum by (service, instance) (rate(nodejs_gc_duration_seconds_sum[10m])) > 0.10

# example: container working set above 90 % of the memory limit (example value)
max by (namespace, pod) (container_memory_working_set_bytes{container="app"})
  / max by (namespace, pod) (kube_pod_container_resource_limits{resource="memory", container="app"})
  > 0.9
  • Heap growth (example): heap used after GC higher than 24 hours ago on every instance of a service without a deployment in between.
  • Unhandled rejections (example): any increase in the count within 5 minutes after a deployment.
  • Restarts (example): more than 2 restarts of a container within 30 minutes, or any OOM kill.
  • Latency (example): p99 of http.server.request.duration on a critical route above its SLO target for 10 minutes.

Alert on symptoms users feel (latency, errors) with paging priority, and use runtime metrics (loop delay, GC, heap) mostly as diagnostic signals and early warnings in tickets or chat.

Node.js monitoring checklist

Use this checklist for every Node.js service in production

  • Event loop delay (p99, max) and event loop utilization collected per process
  • Heap used, heap limit, RSS, external memory and GC duration collected
  • --max-old-space-size set explicitly with headroom below the container memory limit
  • Heap trend after GC reviewed; heap snapshot procedure documented and tested
  • No synchronous APIs in request paths; CPU profiles available for event loop spikes
  • UV_THREADPOOL_SIZE reviewed for services with heavy fs, DNS, crypto or zlib use
  • HTTP duration histograms per route template, method and status code
  • Handlers for unhandledRejection and uncaughtException that log, count and exit cleanly
  • Telemetry labelled with process identity in cluster, PM2 and worker thread setups
  • CPU throttling, OOM kills and restarts monitored in Kubernetes
  • Liveness probes tolerant of short GC pauses; graceful SIGTERM handling
  • OpenTelemetry auto-instrumentation loaded via --require or --import, unneeded instrumentations disabled
  • Trace IDs in logs; alerts on latency and errors first, runtime metrics as early warnings

Running services in several languages? Our guides on Java and JVM monitoring and PHP monitoring follow the same structure.

How Obseria helps

Obseria is an OpenTelemetry-native observability platform, so Node.js services instrumented with the OpenTelemetry SDK send traces, metrics and logs via OTLP without a proprietary agent. Event loop delay, heap and GC metrics appear next to the request traces and logs of the same process, and continuous profiling shows which functions held the event loop when latency spiked.

  • Error tracking groups unhandled rejections and exceptions with stack traces and the trace of the failing request.
  • Obseria Intelligence correlates a latency spike with deployments, GC behaviour, throttling and dependencies, and shows the evidence behind its root cause analysis.
  • SLOs and alerting on route latency and error rate, with usage-based pricing per signal and data stored in the EU.

To see your Node.js services in Obseria, book a demo or start a 14-day free trial.

Share

Observability that delivers answers.

Start for free with OpenTelemetry, no credit card required.