OpenTelemetry metrics in Node.js: HTTP instrumentation and OTLP

Instrument Express HTTP and business metrics with the OpenTelemetry JavaScript SDK. Verify HTTP counts, custom metrics, and OTLP/HTTP Protobuf export locally.

Best practices
Illustration of inspecting application telemetry

A checkout endpoint can return 503 while the number of orders created barely changes. The HTTP duration histogram records the failed response. A business counter increases only after the application accepts the order. Recording the two separately gives you a way to tell a change in traffic from a change in business outcomes.

This guide uses Express, the OpenTelemetry JavaScript Metrics SDK, and a local Collector. The SDK pushes batches over OTLP/HTTP. If your goal is to expose a /metrics endpoint for Prometheus to scrape, follow the separate Node.js Prometheus guide.

Start a local OTLP receiver

Save the configuration as collector.yaml and run otelcol-contrib --config=collector.yaml. The HTTP receiver listens on loopback, and its debug exporter displays the received metrics.

receivers:
  otlp:
    protocols:
      http:
        endpoint: 127.0.0.1:14318
exporters:
  debug:
    verbosity: detailed
service:
  pipelines:
    metrics:
      receivers: [otlp]
      exporters: [debug]

The example was checked on Node.js 22.16.0 with Express 5.3.0, the OpenTelemetry Metrics SDK 3.1.1, HTTP instrumentation and exporter 0.301.1, and Collector Contrib 0.165.0. The pinned OpenTelemetry packages require Node.js 22.15.0 or newer. In an empty directory, install the packages.

npm init -y
npm install --save-exact express@5.3.0 \
  @opentelemetry/api@1.10.0 @opentelemetry/resources@3.1.1 \
  @opentelemetry/sdk-metrics@3.1.1 \
  @opentelemetry/instrumentation@0.301.1 \
  @opentelemetry/instrumentation-http@0.301.1 \
  @opentelemetry/exporter-metrics-otlp-proto@0.301.1

Register HTTP instrumentation before loading Express

The example uses one MeterProvider for the automatic and manual instruments. The periodic reader sends through an OTLP/HTTP exporter that encodes metrics as Protobuf. The collector address below is for this loopback demo.

Save the code as checkout.cjs and run node checkout.cjs. The program sends two synthetic requests, drains their response bodies, and prints 201 and 503. It closes the test server before asking the provider to collect and export its last batch through shutdown().

const { once } = require('node:events');
const { MeterProvider, PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics');
const { resourceFromAttributes } = require('@opentelemetry/resources');
const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-proto');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');

const exporter = new OTLPMetricExporter({
  url: 'http://127.0.0.1:14318/v1/metrics',
});
const provider = new MeterProvider({
  resource: resourceFromAttributes({ 'service.name': 'checkout-node' }),
  readers: [new PeriodicExportingMetricReader({ exporter, exportIntervalMillis: 30_000 })],
});
const unregister = registerInstrumentations({
  meterProvider: provider,
  instrumentations: [new HttpInstrumentation()],
});

const express = require('express');
const app = express();
const meter = provider.getMeter('example.com/checkout');
const created = meter.createCounter('orders.created', { unit: '{order}' });
const inFlight = meter.createUpDownCounter('orders.inflight', { unit: '{request}' });
const depth = meter.createGauge('orders.queue.depth', { unit: '{order}' });
const duration = meter.createHistogram('orders.process.duration', {
  unit: 's',
  advice: { explicitBucketBoundaries: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 5] },
});

app.post('/orders', (req, res) => {
  const started = performance.now();
  const attributes = { route: '/orders' };
  inFlight.add(1, attributes);
  res.once('close', () => inFlight.add(-1, attributes));
  res.once('finish', () => {
    duration.record((performance.now() - started) / 1000, attributes);
  });
  depth.record(2);

  if (req.query.fail === '1') {
    res.sendStatus(503);
    return;
  }
  created.add(1, { channel: 'app' });
  res.sendStatus(201);
});

async function run() {
  const server = app.listen(0, '127.0.0.1');
  try {
    await once(server, 'listening');
    const { port } = server.address();
    for (const suffix of ['', '?fail=1']) {
      const response = await fetch(`http://127.0.0.1:${port}/orders${suffix}`, {
        method: 'POST',
        signal: AbortSignal.timeout(5_000),
      });
      await response.arrayBuffer();
      console.log(response.status);
    }
  } finally {
    try {
      if (server.listening) {
        await new Promise((resolve, reject) => {
          server.close(error => error ? reject(error) : resolve());
        });
      }
    } finally {
      try {
        await provider.shutdown();
      } finally {
        unregister();
      }
    }
  }
}

run().catch(error => {
  console.error(error);
  process.exitCode = 1;
});

A production application should register instrumentation before importing the modules it instruments. With CommonJS you can preload a bootstrap file using --require. With ESM, follow the SDK's loader instructions for your runtime and deployment. TypeScript types alone do not determine when instrumentation is loaded. Node.js OpenTelemetry setup

Read the automatic HTTP histogram first

In the Collector output, find service.name=checkout-node and http.server.request.duration. With the pinned HTTP instrumentation, the histogram has unit s, and each status-code attribute set has a Count of one. The histogram count describes the recorded HTTP requests at those dimensions. The application’s orders.created counter reports one order under channel=app.

Automatic route attributes depend on the instrumentation and framework. In this example the automatic HTTP histogram has no http.route. The business duration histogram uses the fixed route attribute /orders. On a route such as /orders/:id, use the actual matched template and keep full URLs and request IDs out of metric attributes. Older HTTP instrumentation can emit different metric names and units, so check what your pinned version exports before reusing a dashboard. HTTP instrumentation package · HTTP metric conventions

Match the instrument to the measurement

Question Instrument How the example records it
How many orders were created? Counter Adds a nonnegative increment for a successful order.
How many requests are in flight? UpDownCounter Adds on entry and subtracts on connection close or completion with the same attributes.
How deep is the queue now? Gauge Records a measured value. The demo uses two. To read the live queue at collection time, register an ObservableGauge with addCallback(result => result.observe(value)), where the callback obtains the current value.
How long did the handler take? Histogram Records elapsed seconds on the response’s finish event, including both status codes.

The finish event means the response has been handed off to the operating system for transmission. The example measures server-side time from the handler, without client network time. An early disconnect can still release the in-flight count through close. The business duration histogram records responses that reach finish. Node.js response events

The example includes a histogram boundary at 250 ms. Keep bucket boundaries compatible across replicas, and choose boundaries around your alert thresholds. Use a stable service name across replicas and a distinct service.instance.id when per-process comparison is needed. Configure it per process rather than using the same ID for an entire PM2 cluster.

Connect the same pipeline to Guance

For DataKit, enable its OpenTelemetry input and point the exporter at the actual OTLP receiver. DataKit documents an HTTP default of port 9529 with the metrics path /otel/v1/metrics. The loopback Collector in this article uses /v1/metrics on its own port. Configure TLS and authentication for the deployment that receives your data. DataKit OpenTelemetry input

Send a known number of requests. In Guance, verify the received names, units, attributes, and histogram representation before setting up charts and monitors. Check status-code coverage alongside business throughput, so a rise in failures remains visible even when the order total stays flat. Configure Guance monitors

Questions that come up in production

Can I collect metrics without exporting traces? Yes. This example configures a metrics reader and leaves trace export unconfigured. If you already use NodeSDK, add the metrics reader to that setup and avoid registering the same HTTP instrumentation twice.

Can automatic metrics and custom metrics overlap? They can. Name instruments for distinct measurements and verify metric identity, units, and dimensions in the receiver. When a business counter and the automatic HTTP histogram count different populations, their values will differ for good reasons.

How often should the reader export? The default is 60 seconds when the direct reader has no explicit interval. The example configures 30 seconds during normal operation and collects at shutdown. Choose the interval based on the alert window, traffic, and receiver capacity.

What happens when the process stops? In production, handle the termination signal, stop accepting requests, let in-flight work finish within the available grace period, and await SDK shutdown. A forced stop, exporter timeout, or receiver failure can still lose the last batch.

References and related reading

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting