Comprehensive guide to opentelemetry implementation for production observability and monitoring systems.
OpenTelemetry is a vendor-neutral observability framework for instrumenting, generating, and collecting telemetry data—traces, metrics, and logs—from distributed applications. It matters when you need to unify instrumentation across services, eliminate vendor lock-in, and produce consistent, interoperable telemetry from microservices to serverless functions. This guide covers the practical steps, common pitfalls, and real-world configurations for implementing OpenTelemetry in production systems.
To begin, embed the OpenTelemetry SDK into your application code using one of the official language-specific packages. The SDKs are lightweight, modular, and designed to work with any telemetry backend.
package main
import (
"context"
"log"
"net/http"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.20.0"
)
func main() {
ctx := context.Background()
// Create OTLP trace exporter to send data to a collector
exporter, err := otlptrace.New(
ctx,
otlptracegrpc.WithInsecure(),
otlptracegrpc.WithEndpoint("collector:4317"),
)
if err != nil {
log.Fatalf("Failed to create trace exporter: %v", err)
}
// Create a resource describing this service
res, err := resource.New(
ctx,
resource.WithAttributes(
semconv.ServiceNameKey.String("payment-service"),
semconv.ServiceVersionKey.String("1.2.0"),
semconv.DeploymentEnvironmentKey.String("production"),
),
)
if err != nil {
log.Fatalf("Failed to create resource: %v", err)
}
// Create a tracer provider with the exporter and resource
tp := trace.NewTracerProvider(
trace.WithBatcher(exporter),
trace.WithResource(res),
trace.WithConfig(trace.Config{DefaultSampler: trace.AlwaysSample()}),
)
// Register the provider globally
otel.SetTracerProvider(tp)
// Create a tracer
tracer := otel.Tracer("payment-service")
// Start a simple HTTP server
http.HandleFunc("/process", func(w http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "process-payment")
defer span.End()
// Simulate work
time.Sleep(100 * time.Millisecond)
span.AddEvent("payment-processed", trace.WithAttributes(
"go.opentelemetry.io/otel/attribute/string", "payment.id", "p12345",
))
w.WriteHeader(200)
_, _ = w.Write([]byte("OK"))
})
// Start the server
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Server failed: %v", err)
}
}
The otlptracegrpc.WithEndpoint("collector:4317") configures the client to use gRPC to send trace data to a collector running on collector:4317. The WithBatcher ensures spans are aggregated before sending, reducing network overhead. A common mistake is using WithSyncer instead of WithBatcher, which leads to one HTTP request per span and high latency.
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPTraceExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.context import get_current
from opentelemetry.trace import SpanKind
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
exporter = OTLPTraceExporter(endpoint="http://collector:4318", protocol="grpc")
processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(processor)
with tracer.start_as_current_span("fetch-user-data", kind=SpanKind.CLIENT) as span:
span.set_attribute("user.id", "u456")
span.set_attribute("db.query", "SELECT * FROM users WHERE id = ?")
# Simulate network call
time.sleep(0.12)
span.add_event("user-data-retrieved", {"user.id": "u456"})
The protocol="grpc" key is critical. Using protocol="http" sends JSON over HTTP/1.1, which is slower and heavier. The BatchSpanProcessor is the default, but forgetting to add it results in spans being sent immediately—often causing delays and unbounded memory usage.
The OpenTelemetry Collector is the central component for receiving, processing, and exporting telemetry. It runs as a sidecar, daemon, or standalone service.
receivers:
otlp:
protocols:
grpc:
endpoint: "0.0.0.0:4317"
http:
endpoint: "0.0.0.0:4318"
processors:
batch:
send_batch_max_size: 1000
timeout: 10s
send_batch_max_size: 1000
timeout: 10s
exporters:
logging:
loglevel: debug
prometheus:
endpoint: "0.0.0.0:8888"
namespace: "myapp"
const_labels:
service: "user-service"
jaeger:
endpoint: "jaeger:14250"
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [logging, prometheus, jaeger]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [prometheus]
The batch processor configuration is often misconfigured. The send_batch_max_size and timeout keys are frequently confused: send_batch_max_size triggers a flush when the batch reaches a certain number of items, while timeout forces a flush after a fixed duration. Using only one leads to either delayed exports or excessive network traffic.
Deploy the collector as a sidecar with your application using Docker Compose:
version: '3.8'
services:
app:
image: myapp:v1.2
ports:
- "8080:8080"
depends_on:
- collector
environment:
- OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317
collector:
image: otel/opentelemetry-collector:0.88.0
command:
- --config=/etc/otel-collector-config.yaml
volumes:
- ./collector-config.yaml:/etc/otel-collector-config.yaml
ports:
- "4317:4317"
- "4318:4318"
- "8888:8888"
networks:
- observability
networks:
observability:
The OTEL_EXPORTER_OTLP_ENDPOINT environment variable is the primary way to configure the exporter. It accepts both HTTP and gRPC endpoints. A common error is assuming the collector receives only gRPC; otlp receiver supports both protocols, so a service sending traces over HTTP/1.1 to 4318 works out of the box.
When your system grows, you need to export traces and metrics to multiple systems. The collector’s pipeline architecture enables this.
processors:
filter:
include:
attributes:
- key: "service.name"
value: "payment-service"
- key: "span.kind"
value: "SERVER"
exclude:
attributes:
- key: "otel.library.name"
value: "opentelemetry-python"
# Apply only to specific spans
batch:
timeout: 5s
send_batch_max_size: 500
exporters:
jaeger:
endpoint: "jaeger:14250"
insecure: true
zipkin:
endpoint: "zipkin:9411/api/v2/spans"
prometheus:
endpoint: "0.0.0.0:8888"
service:
pipelines:
traces:
receivers: [otlp]
processors: [filter, batch]
exporters: [jaeger, zipkin]
traces-high-traffic:
receivers: [otlp]
processors: [batch]
exporters: [prometheus, zipkin]
# This pipeline receives all traces, but only applies prometheus and zipkin to high-traffic services
The filter processor includes spans matching specific attributes. It is often used to route high-traffic or high-latency spans to more expensive backends. A subtle failure mode is forgetting to set include and exclude as top-level keys under filter, leading to a configuration that does nothing.
Auto-instrumentation captures common patterns with minimal code. The OpenTelemetry SDKs support auto-instrumentation for HTTP servers, databases, and message queues.
For a Node.js service, enable auto-instrumentation with:
{
"instrumentations": [
{
"name": "@opentelemetry/instrumentation-http",
"options": {
"requestHook": (span, request) => {
span.setAttribute("http.request.method", request.method);
span.setAttribute("http.request.url", request.url);
},
"responseHook": (span, response) => {
span.setAttribute("http.response.status_code", response.statusCode);
}
}
},
{
"name": "@opentelemetry/instrumentation-express",
"options": {
"enabled": true,
"spanName": "express.request"
}
}
]
}
The requestHook and responseHook are called before and after each request. A common oversight is missing spanName in the express instrumentation, resulting in spans named request instead of express.request, which complicates correlation.
func ProcessPayment(ctx context.Context, paymentID string) error {
tracer := otel.Tracer("payment-service")
ctx, span := tracer.Start(ctx, "ProcessPayment")
defer span.End()
span.SetAttributes(
attribute.String("payment.id", paymentID),
attribute.Int64("amount", 1500),
attribute.String("currency", "USD"),
)
// Simulate external service call
ctx, clientSpan := tracer.Start(ctx, "CallBillingService")
defer clientSpan.End()
// Add event with metadata
span.AddEvent("payment-validated", trace.WithAttributes(
attribute.Bool("is_valid", true),
attribute.String("validator", "fraud-checker"),
))
// Add attributes after a step
clientSpan.SetAttributes(
attribute.String("billing.service", "stripe"),
attribute.String("billing.operation", "charge"),
)
return nil
}
The AddEvent function is crucial for diagnosing issues. A typical mistake is adding events only at the end, missing key steps. The WithAttributes wrapper is often confused with SetAttributes, which updates the span’s attributes in place, while AddEvent creates a timestamped event with a snapshot of attributes.
otlp.WithTimeout(60s) for gRPC exporters.resource processor does not detect service name, version, or environment. Ensure OTEL_RESOURCE_ATTRIBUTES is set, or use the file resource detector.trace_id but no parent_id, causing broken traces. The traceparent header from distributed tracing is often missing in HTTP requests.timeout or use send_batch_max_size with smaller values.otlp receiver is configured for both traces and metrics, and that the exporters pipeline includes both.When the collector is not exporting data, check logs from the collector:
docker logs collector
Look for:
Failed to connect to OTLP endpoint: dial tcp 10.0.0.1:4317: connect: connection refusedReceived 123 spans, but 100 were exportedPipeline traces: Exporter jaeger failed: Status: 500, Body: {"error":"Invalid payload"}Use curl http://collector:8888/metrics to verify Prometheus metrics are exposed. A common error is misconfiguring the namespace in Prometheus exporter, leading to metrics without the expected prefix.
OTEL_EXPORTER_OTLP_ENDPOINT: http://collector:4318 or grpc://collector:4317OTEL_RESOURCE_ATTRIBUTES: service.name=payment-service,service.version=1.2.0OTEL_TRACES_EXPORTER: otlp, jaeger, zipkin, loggingOTEL_METRICS_EXPORTER: otlp, prometheus, statsdOTEL_LOGS_EXPORTER: otlp, file, consoleOTEL_SERVICE_NAME: fallback for service name when no resource attributes are available.The OpenTelemetry implementation is not just about adding code—it is about aligning telemetry across services, ensuring consistency, and building a shared understanding of system behavior.
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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy