OpenTelemetry tutorial for Node.js: traces and metrics from scratch
By Flavio
Updated
Tagged: Node.js
Instrument a Node.js API with OpenTelemetry, export traces and metrics through a collector, and learn how to debug slow production requests.
When something slows down in production, you usually lean on three kinds of data: logs tell you what happened, metrics tell you how often it’s happening, and traces follow a single request from start to finish across your system. OpenTelemetry is an open standard and a set of tools for generating all of that without locking your app into a single monitoring vendor.
In this tutorial, we’re going to instrument a small Node.js API and send its telemetry through the OpenTelemetry Collector. Along the way we’ll collect:
- an HTTP span for each incoming request
- child spans for our own application work
- request duration metrics
- custom attributes that help us track down slow requests
The three signals
OpenTelemetry organizes telemetry around three main signals:
- Traces follow one operation all the way through your system. Each trace is made up of spans, where a span is a single timed piece of work like an HTTP request, a SQL query, or a call to another service.
- Metrics are numbers measured over time, such as request count, memory use, or response duration.
- Logs are timestamped events emitted by your code.
In OpenTelemetry’s JavaScript project, traces and metrics are stable while the logs API and SDK are still less mature. Because of that, we’ll stick with our normal logger and tie our log entries to traces using trace IDs.
Create the API
Let’s start by setting up a fresh project:
mkdir otel-books-api
cd otel-books-api
npm init -y
npm install express
Add "type": "module" to package.json so we can use ES module imports, then create app.js:
import express from 'express'
const app = express()
app.get('/books/:id', async (request, response) => {
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 200)
})
response.json({
id: request.params.id,
title: 'The Hobbit',
})
})
app.listen(3000, () => {
console.log('API listening on http://localhost:3000')
})
Start the server:
node app.js
Open http://localhost:3000/books/1 in your browser. The API works fine locally, but if it starts getting slow in production, all you’d have to go on is whatever a user happens to report.
Install OpenTelemetry
Next, install the Node SDK, automatic instrumentations, and OTLP exporters:
npm install \
@opentelemetry/api \
@opentelemetry/sdk-node \
@opentelemetry/sdk-metrics \
@opentelemetry/resources \
@opentelemetry/semantic-conventions \
@opentelemetry/instrumentation \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/exporter-trace-otlp-http \
@opentelemetry/exporter-metrics-otlp-http
Each package handles a distinct piece of the setup:
apigives our app the instrumentation interface we’ll call in our own codesdk-nodeconfigures providers and processors for Node.jsauto-instrumentations-nodeautomatically instruments common libraries- the exporters ship telemetry out using OTLP (the OpenTelemetry Protocol) over HTTP
Start instrumentation before the app
Create instrumentation.js to bootstrap the SDK:
import { NodeSDK } from '@opentelemetry/sdk-node'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
import { resourceFromAttributes } from '@opentelemetry/resources'
import {
ATTR_SERVICE_NAME,
ATTR_SERVICE_VERSION,
} from '@opentelemetry/semantic-conventions'
const sdk = new NodeSDK({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: 'books-api',
[ATTR_SERVICE_VERSION]: '1.0.0',
}),
traceExporter: new OTLPTraceExporter(),
metricReaders: [
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter(),
exportIntervalMillis: 5000,
}),
],
instrumentations: [getNodeAutoInstrumentations()],
})
sdk.start()
const shutdown = async () => {
await sdk.shutdown()
process.exit(0)
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
Then load it before your application starts:
node \
--experimental-loader=@opentelemetry/instrumentation/hook.mjs \
--import ./instrumentation.js \
app.js
The loading order matters here. Automatic instrumentation patches modules as they’re imported, so if Express or Node’s HTTP module loads first, OpenTelemetry won’t get the chance to instrument them.
Run a local Collector
Your app can send data straight to a monitoring backend, though in production you’ll usually put the OpenTelemetry Collector in between. It receives telemetry, processes it, and exports it wherever you want it to go.
Create a config file named otel-collector.yaml:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
batch:
exporters:
debug:
verbosity: detailed
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [debug]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [debug]
Now run the official Collector image with that configuration:
docker run --rm \
-p 127.0.0.1:4317:4317 \
-p 127.0.0.1:4318:4318 \
-v "$PWD/otel-collector.yaml:/etc/otelcol/config.yaml:ro" \
otel/opentelemetry-collector:0.160.0
By convention, OTLP uses port 4317 for gRPC and 4318 for HTTP. Out of the box, the HTTP exporters send data to these defaults:
http://localhost:4318/v1/traces
http://localhost:4318/v1/metrics
Open another terminal, start the app, and make a request:
curl http://localhost:3000/books/1
Check the Collector’s output and you’ll see it print a server span for that request.
What automatic instrumentation gives us
Without writing any tracing code in our routes, the HTTP and Express instrumentations already wrap incoming requests in spans. Each span records:
- a trace ID
- a span ID
- start and end times
- a status
- attributes
- links to its parent and children
The trace ID ties together every span belonging to the same operation. If this API called another instrumented service, OpenTelemetry would propagate the trace context in HTTP headers so the downstream service’s spans join the exact same trace.
Add a custom span
Automatic spans show what the framework is doing, but they don’t know which parts of your own business logic matter. For that, you can create custom spans.
Start by replacing the Express import at the top of app.js with these imports:
import express from 'express'
import { metrics, SpanStatusCode, trace } from '@opentelemetry/api'
const tracer = trace.getTracer('books-api')
Next, extract the fake database lookup into its own function:
async function findBook(id) {
return tracer.startActiveSpan('find book', async (span) => {
span.setAttribute('book.id', id)
try {
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 200)
})
return {
id,
title: 'The Hobbit',
}
} catch (error) {
span.recordException(error)
span.setStatus({
code: SpanStatusCode.ERROR,
message: error instanceof Error ? error.message : String(error),
})
throw error
} finally {
span.end()
}
})
}
Then call it inside the route handler:
app.get('/books/:id', async (request, response) => {
const book = await findBook(request.params.id)
response.json(book)
})
Calling startActiveSpan() keeps the new span active while the callback runs, so it becomes a descendant of the incoming HTTP span and a child of whichever framework span is active at that moment. Always close manually created spans inside a finally block, otherwise an error will leave unfinished spans hanging around.
Add a custom metric
Use the metrics import we added above to grab a meter:
const meter = metrics.getMeter('books-api')
const lookupCounter = meter.createCounter('book.lookup.count', {
description: 'Number of book lookups',
})
const lookupDuration = meter.createHistogram('book.lookup.duration', {
description: 'Book lookup duration',
unit: 'ms',
})
Then record the measurements when the operation runs:
async function findBook(id) {
const startedAt = performance.now()
return tracer.startActiveSpan('find book', async (span) => {
span.setAttribute('book.id', id)
try {
lookupCounter.add(1)
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 200)
})
return {
id,
title: 'The Hobbit',
}
} catch (error) {
span.recordException(error)
span.setStatus({
code: SpanStatusCode.ERROR,
message: error instanceof Error ? error.message : String(error),
})
throw error
} finally {
lookupDuration.record(performance.now() - startedAt)
span.end()
}
})
}
We’re using two instrument types here for a reason: a counter only goes up, while a histogram records a distribution of values, which is what you want for tracking durations.
Be careful with metric attributes
It’s tempting to attach every useful value to your measurements, like putting id straight onto a metric:
lookupCounter.add(1, {
'book.id': id,
})
Don’t do that when id can have millions of values. Every unique attribute combination creates another metric time series, a problem called high cardinality, and it’ll quickly make your metrics backend expensive or unusable.
Keep metric attributes to a small, controlled set of values:
- HTTP method
- route pattern
- status class
- deployment region
Put a specific request ID, user ID, or book ID on a span instead. Traces are built for that kind of high-detail debugging data.
Configure with environment variables
OpenTelemetry SDKs support standard environment variables out of the box, so you don’t have to hardcode backend addresses in your code. For example:
OTEL_SERVICE_NAME=books-api \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
node \
--experimental-loader=@opentelemetry/instrumentation/hook.mjs \
--import ./instrumentation.js \
app.js
If traces and metrics go to different places, you can set signal-specific endpoints as well:
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://localhost:4318/v1/metrics
With configuration handled this way, the exact same application image can run in development, staging, and production without touching your code.
Correlate logs with traces
When handling an error, grab the current trace ID using our existing trace import and include it in the log:
function logError(error) {
const span = trace.getActiveSpan()
const traceId = span?.spanContext().traceId
console.error({
message: error.message,
traceId,
})
}
That links your logs straight to your traces: a log search leads you to the exact trace, and the trace shows which child operation slowed everything down. In a real app, configure your structured logger once so it attaches trace and span IDs to every log line automatically.
Record errors correctly
Recording an exception on a span only attaches an event; you also need to set the span’s status to an error so monitoring tools flag it as failed. For manual spans, do both:
span.recordException(error)
span.setStatus({
code: SpanStatusCode.ERROR,
message: error instanceof Error ? error.message : String(error),
})
Match the semantic status to what happened in the operation. A handled 404 usually isn’t an internal error, whereas a failed database connection definitely is. Also keep secrets and personal data out of span attributes, since telemetry leaves your process and often stays in storage for a long time.
Sampling
Recording every trace is great locally, though on a high-traffic service it’ll produce far more data than you want to handle. Sampling decides which traces to keep and which ones to drop.
A common production setup samples a percentage of new traces while respecting whatever decision a parent service already made. The right percentage depends on your traffic, your budget, and how rare the failures are. You’ve got two main options:
- Head sampling makes the decision at the beginning of a trace. It’s lightweight and easy to run, though it can’t know ahead of time whether a later span will fail.
- Tail sampling happens inside a Collector after the spans arrive. It lets you keep slow or failed traces, at the cost of extra infrastructure and memory.
Start by collecting enough data to understand your real traffic volume instead of guessing an aggressive sampling rate on day one.
Send data to a real backend
The debug exporter is useful for verifying that the pipeline works locally. When you’re ready for production, replace it or add another exporter in your Collector configuration. Your application doesn’t need to know whether the final destination is Jaeger, Grafana, Honeycomb, a cloud provider, or another compatible backend:
Running your telemetry through the Collector also lets you:
- batch spans before exporting
- retry failed exports
- strip out sensitive attributes
- enrich data with infrastructure metadata
- route signals to multiple backends at once
Debug missing telemetry
If no spans show up, walk through these checks in order:
- Instrumentation loads before the application.
- The Collector is listening on the expected port.
- The exporter protocol matches the receiver (HTTP vs. gRPC).
- The endpoint includes
/v1/tracesor/v1/metricswhen required. - The process stays alive long enough to export.
- Shutdown calls
sdk.shutdown()so buffered data gets flushed.
If you aren’t sure whether the bug is in your instrumentation or the network path, temporarily switch to console exporters inside the app. Seeing spans in your terminal narrows it down right away.
Watch version compatibility between OpenTelemetry packages too. Install related packages together instead of mixing an old instrumentation package with a newer SDK.
Use the signals together
With this setup in place, our API sends automatic HTTP and Express spans through the Collector alongside a custom child span around book lookups, a counter, a duration histogram, service metadata, and trace IDs for logs.
In practice, you jump between those signals while debugging. A spike in the duration histogram flags a slowdown, the traces show whether the time went to Express or the book lookup, and the trace ID pulls up the exact log lines from that request. Because OpenTelemetry connects everything in an open format through the Collector, you can swap the storage and visualization backend later without rewriting your app’s instrumentation.
Want me to talk about your product? You can sponsor this site.
Related posts about node: