How to Instrument Services with OpenTelemetry
Add traces, spans and context propagation to a service so a single request can be followed across every hop it touches.
On this page
Introduction
A distributed request crosses a client, a gateway, several services, a cache and a database, and when it is slow every one of those hops is a suspect. Logs tell you what each hop did in isolation; a trace tells you how long each hop took and which hop caused the delay. OpenTelemetry is the vendor-neutral standard for producing those traces, along with metrics and logs, using one set of APIs. This article shows how to initialize a tracer, wrap work in spans, propagate context to downstream services, attach the attributes that make a trace useful, and sample so the cost stays bounded.
What OpenTelemetry Provides
OpenTelemetry is a specification plus a set of SDKs and an API. A trace is a tree of spans; each span represents one unit of work with a start time, a duration, a name, attributes and a status. Spans are linked by a trace id and parent span id, so a downstream service that receives the trace context can attach its spans to the same trace. The SDK collects spans and exports them to a backend through an exporter, which may be an OTLP endpoint, a file, or a vendor collector.
The value of the standard is portability: you instrument once with the OpenTelemetry API and can change the backend without touching application code. It also unifies the three signals, so a metric can be correlated with a log line and both with the trace that produced them, which is the practical difference between data you have and data you can use.
Initializing the Tracer and Exporter
Initialization must happen before the instrumented code runs, ideally at the very top of the process, so auto-instrumentation of the HTTP and database libraries can hook in. Configure a resource with the service name and environment, because every span inherits those attributes and they are how you filter traces by service in the backend. Configure an exporter with a batch span processor so spans are sent in groups rather than one request per span.
// tracing.js — require this before the app code
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
const { resourceFromAttributes } = require('@opentelemetry/resources');
const { ATTR_SERVICE_NAME, ATTR_DEPLOYMENT_ENVIRONMENT } = require('@opentelemetry/semantic-conventions');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const sdk = new NodeSDK({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: 'orders-api',
[ATTR_DEPLOYMENT_ENVIRONMENT]: 'production',
}),
traceExporter: new OTLPTraceExporter({ url: 'http://collector:4318/v1/traces' }),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
process.on('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0)));
Creating Spans Around Work
A span should wrap a meaningful unit of work: an inbound request, a database query, a call to another service, or an expensive computation. Name the span after the operation, not the code path, so traces read like a story. Use the tracer’s startActiveSpan so the span becomes the current context and any child work is automatically parented to it. Always end the span, and set its status to error when the operation fails so the backend can flag it.
const { trace, SpanStatusCode } = require('@opentelemetry/api');
const tracer = trace.getTracer('orders-api');
async function priceOrder(order) {
return tracer.startActiveSpan('price.order', async (span) => {
span.setAttribute('order.id', order.id);
span.setAttribute('order.items', order.items.length);
try {
const total = await computeTotal(order); // child spans auto-parented
span.setAttribute('order.total_cents', total);
return total;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
span.recordException(err);
throw err;
} finally {
span.end();
}
});
}
Propagating Context Across Services
Context propagation is what turns isolated spans into a trace. The W3C traceparent header carries the trace id, the parent span id and the sampling decision. Automatic instrumentation injects it into outbound HTTP calls and extracts it on inbound ones, so the next service continues the trace. When you cross a boundary instrumentation does not cover, such as a message queue, propagate the header yourself by injecting it into the message and extracting it on the consumer.
If context does not propagate, the trace breaks into unrelated fragments and the latency you were chasing is invisible across the gap. Test propagation explicitly by sending a request through two services and asserting that one trace id appears on spans from both.
Adding Attributes, Events and Errors
Attributes are the query surface of a trace: the order id, the tenant, the HTTP status, the database statement type. Keep them low-cardinality and avoid putting anything personally identifiable or high-churn in them, because attributes are indexed and a unique value per span makes queries expensive. Use semantic conventions where they exist so the same attribute name means the same thing across services.
Events mark points in time inside a span, such as a retry or a cache miss, and exceptions attach the error and its stack to the span without flooding logs. Record the exception on the span rather than only logging it, so an error trace is visible in the same view as its timing.
Sampling to Control Cost
Tracing every request at high volume is expensive in storage and network. Head-based sampling decides at the start of the trace whether to record it, which keeps the decision consistent across all services in the trace. A parent-based sampler honours the upstream decision so a sampled trace is sampled everywhere. The downside is that you miss the rare slow request that was not sampled.
Tail-based sampling collects all spans briefly and decides after the trace completes, so it can keep every slow or erroring trace and discard the fast, boring ones. It costs more infrastructure because spans must be buffered, so it is typically done in a collector rather than in each service. Start with a modest head-based rate in development and tail-based sampling for errors in production.
Conclusion
Instrumenting with OpenTelemetry means initializing the SDK before the app, wrapping meaningful work in spans, propagating the trace context across every boundary, attaching low-cardinality attributes and exceptions, and sampling so the cost stays bounded. Do that and a slow request stops being a mystery: you open the trace and see the exact hop that cost the time. The same instrumented code can point at any backend, so the investment survives a change of vendor.
Sources: OpenTelemetry documentation, W3C Trace Context, OpenTelemetry JavaScript SDK.
FAQ
- Do I need to change my code to use OpenTelemetry?
- For common libraries, auto-instrumentation hooks HTTP, database and cache clients with no code changes. You add manual spans only for business logic you want to see explicitly, such as a pricing computation or a queue consumer.
- What is the difference between head and tail sampling?
- Head sampling decides at trace start and applies consistently to every span, but cannot see the trace outcome. Tail sampling decides after the trace finishes, so it can keep all slow or erroring traces, at the cost of buffering spans in a collector.
Report a problem with this articleOpens a pre-filled issue on GitHub.