Opentelemetry Instrumentation

Production-grade guide to opentelemetry instrumentation covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

OpenTelemetry Instrumentation is the practice of embedding observability into software through standardized, cross-platform APIs and SDKs that emit structured telemetry—traces, metrics, and logs—from applications and services. It matters when you need to correlate behavior across distributed systems, whether in microservices, serverless functions, or hybrid cloud deployments, and when you want to avoid vendor lock-in while achieving consistent, high-fidelity data.

Instrumenting a Service with OpenTelemetry

To begin instrumentation, add the OpenTelemetry SDK to your application and configure it to export data to a backend. For a Go service using opentelemetry-go, include the SDK and a batch exporter for signals.

package main

import (
	"context"
	"log"
	"net/http"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/trace"
)

func main() {
	ctx := context.Background()

	// Configure OTLP trace exporter
	traceExp, err := otlptrace.New(ctx, otlptrace.WithInsecure(), otlptrace.WithEndpoint("localhost:4317"))
	if err != nil {
		log.Fatal(err)
	}

	// Configure OTLP metric exporter
	metricExp, err := otlpmetric.New(ctx, otlpmetric.WithInsecure(), otlpmetric.WithEndpoint("localhost:4318"))
	if err != nil {
		log.Fatal(err)
	}

	// Create resource with service name
	res, err := resource.New(ctx,
		resource.WithAttributes(
			// Key-value pairs for service metadata
			attribute.String("service.name", "order-service"),
			attribute.String("service.version", "1.2.0"),
		),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create trace provider
	traceProvider := sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(traceExp),
		sdktrace.WithResource(res),
	)
	otel.SetTracerProvider(traceProvider)

	// Create metric provider
	metricProvider := metric.NewProvider()
	otel.SetMeterProvider(metricProvider)

	// Register metric exporter
	metricProvider.RegisterExporter(metricExp)

	// Start the SDK
	otel.Shutdown(ctx)

	// Use the global tracer
	tracer := otel.Tracer("example-tracer")

	http.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {
		ctx, span := tracer.Start(r.Context(), "handle-order")
		defer span.End()

		// Simulate work
		span.AddEvent("processing-order", trace.WithAttributes(
			attribute.String("order.id", "12345"),
			attribute.Int64("order.value", 99900),
		))

		// Record a metric
		meter := otel.Meter("order-service")
		counter := meter.Meter("orders", "count", "Number of orders processed")
		counter.Add(ctx, 1)

		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("Order processed"))
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

The otlp exporter sends data over gRPC to a collector. The collector must be running on localhost:4317 (for traces) and localhost:4318 (for metrics). If these ports are unreachable, the SDK silently drops data during startup and emits logs on error.

Configuring the OpenTelemetry Collector

The OpenTelemetry Collector is the central component that receives, processes, and exports telemetry. It is configured via a YAML file.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: "0.0.0.0:4317"
      http:
        endpoint: "0.0.0.0:4318"

  prometheus:
    config:
      scrape_configs:
        - job_name: "my-service"
          static_configs:
            - targets: ["localhost:9090"]

processors:
  batch:
    timeout: 10s
    send_batch_max_size: 1000
    send_batch_size: 100
  memory_limiter:
    check_interval: 5s
    limit_mib: 100
    watermark_high: 0.9
    watermark_low: 0.7

exporters:
  jaeger:
    endpoint: "jaeger-collector:14250"
    insecure: true
  prometheus:
    endpoint: "0.0.0.0:8888"
    namespace: "myapp"
  logging:
    loglevel: "debug"
    encoding: "json"

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch, memory_limiter]
      exporters: [jaeger, logging]
    metrics:
      receivers: [otlp, prometheus]
      processors: [batch]
      exporters: [prometheus, logging]

The collector starts with otelcol --config config.yaml. If the file is missing, it logs:

failed to load config: open config.yaml: no such file or directory

If a processor fails, it logs the error and continues processing. The batch processor buffers data and flushes on timeout or size threshold. A common failure mode is memory exhaustion: if the memory_limiter detects high memory usage, it starts dropping spans and metrics until the watermark drops below the low threshold.

Exporting Logs with OpenTelemetry

Logs are instrumented using the log package in the OpenTelemetry SDK. Each log entry is a structured record with a timestamp, severity, and key-value attributes.

import (
	"go.opentelemetry.io/otel/log"
	"go.opentelemetry.io/otel/log/attribute"
)

func logOrderEvent(ctx context.Context, orderID string, event string) {
	logger := otel.Log().Logger("order-service")
	logger.Log(ctx, log.Event{
		Body:        "Order event",
		Attributes: []attribute.KeyValue{
			attribute.String("order.id", orderID),
			attribute.String("event", event),
			attribute.Int64("timestamp", time.Now().UnixNano()),
		},
		Severity: log.SeverityInfo,
	})
}

The OpenTelemetry logging system supports structured logs natively. When exported to a backend, each log entry maps to a row with the following keys: timestamp, severity, body, and attributes as a map of strings to values. The collector supports logging and otlp exporters for logs.

Correlating Traces Across Services

To propagate context across service boundaries, use the TextMapPropagator in the OpenTelemetry SDK. The default format is W3C Trace Context.

import (
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/trace"
)

func init() {
	// Set the global propagator
	propagator := propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	)
	otel.SetTextMapPropagator(propagator)
}

func makeHTTPCall(ctx context.Context, url string) error {
	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
	if err != nil {
		return err
	}

	// Inject context into HTTP headers
	otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Extract context from response headers
	ctx = otel.GetTextMapPropagator().Extract(resp.Header, propagation.HeaderCarrier{})

	// Set trace context for subsequent work
	trace.SpanFromContext(ctx).AddEvent("response-received")
	return nil
}

The TraceContext propagator uses two headers: traceparent and tracestate. The traceparent header is a single string:

00-0af7651916cd43dd8448eb211c80319c-b7ad94431b363d97-01

where:

The tracestate header is a comma-separated list of key-value pairs:

rojo=00f067aa0ba902b7,congo=t61rcWkgMzd+2eY8bJg5rQ

When a service receives a request, it extracts the trace context from the headers and starts a new span. If a new trace is started, the traceparent header is generated and sent back to the caller.

Instrumenting Libraries and Frameworks

OpenTelemetry supports automatic instrumentation via a set of pre-built instrumentation libraries. These libraries hook into common frameworks and libraries.

For a Node.js application using Express, add the opentelemetry-instrumentation-express package:

npm install @opentelemetry/instrumentation-express @opentelemetry/sdk-node
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter({
    url: 'http://localhost:4317',
  }),
  instrumentations: [new ExpressInstrumentation()],
});

sdk.start();

The ExpressInstrumentation captures HTTP spans for every route, including path parameters and query string. It also instruments the http and fs modules, and adds a span.kind of SERVER for incoming requests.

The instrumentation library adds attributes to spans:

It also records a http.request.body.size and http.response.body.size if the body is available.

Common Pitfalls and Failure Modes

  error sending batch: 500 Internal Server Error
  memory limit reached, dropping 123 spans

Advanced Patterns

  sampler := sdktrace.NewParentBased(sdktrace.NewProbabilitySampler(0.1))
  traceProvider := sdktrace.NewTracerProvider(
    sdktrace.WithBatcher(traceExp),
    sdktrace.WithResource(res),
    sdktrace.WithSampler(sampler),
  )
  meter := otel.Meter("order-service")
  latency := meter.NewInt64Histogram("order.latency.ms",
    metric.WithDescription("Time to process an order"),
    metric.WithUnit("ms"),
  )

  latency.Record(ctx, 230, attribute.String("region", "us-west"))
  span.SetStatus(codes.Error, "Database query failed")
  span.RecordError(err, trace.WithAttributes(
    attribute.String("db.operation", "SELECT"),
    attribute.String("db.statement", "SELECT * FROM orders WHERE id = ?"),
  ))

Summary

OpenTelemetry Instrumentation is the foundation for observability in distributed systems. It enables consistent, structured, and interoperable telemetry across services. The key to success is understanding how to configure the collector, how to propagate context, and how to instrument libraries and frameworks. The most common failures involve misaligned attribute names, batch configuration, and missing or malformed context headers. The pattern is standardized—no platform-specific hooks or defaults—but the implementation must be precise.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.