Skip to content

Instrumenting Go services with the OpenTelemetry SDK

Wire OpenTelemetry tracing, metrics, and logs into a Go service — OTLP exporter, resource attributes, propagation, and how to keep span cardinality under control.

OpenTelemetry is the standard for exporting traces, metrics, and logs out of a service into a collector that fans them to your vendor of choice (Datadog, Honeycomb, Grafana Tempo, etc.). The Go SDK is mature, the OTLP exporter is reliable, and the contrib packages auto-instrument net/http, gRPC, and the major databases. This article shows the OpenTelemetry layout Stack Harbor uses on Go services.

How to verify

After wiring OTel, run a tiny collector locally and watch spans arrive:

docker run --rm -p 4317:4317 -p 4318:4318 \
  -v $PWD/otel-config.yaml:/etc/otelcol/config.yaml \
  otel/opentelemetry-collector-contrib:0.105.0

OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
OTEL_SERVICE_NAME=myapp \
OTEL_RESOURCE_ATTRIBUTES='service.namespace=billing,service.version=1.0.0,deployment.environment=dev' \
go run .

curl http://localhost:8080/api/v1/users/42

The collector logs should show a span named GET /api/v1/users/{id} with a child span for the DB query. If your app instruments outbound HTTP, you also see a child span for the upstream call.

What’s happening

OpenTelemetry separates three concerns:

  • API (go.opentelemetry.io/otel) — what your code calls (tracer.Start, meter.Int64Counter). Stable, slow-moving.
  • SDK (go.opentelemetry.io/otel/sdk) — the implementation that does the heavy lifting (batching, sampling, propagation, resource detection).
  • Exporters (otlptracegrpc, otlptracehttp, etc.) — push spans/metrics to a collector or backend.

Auto-instrumentation lives in go.opentelemetry.io/contrib/instrumentation/.... The two you almost always want: net/http instrumentation (server + client) and gRPC instrumentation (otelgrpc). Database libraries have their own modules (go.opentelemetry.io/contrib/instrumentation/database/sql/otelsql).

Propagation is W3C TraceContext by default. Every HTTP/gRPC client your service makes inherits the trace from the incoming request, so end-to-end distributed traces stitch together if every hop is instrumented.

The procedure

  1. Install the SDK and exporters.

    go get go.opentelemetry.io/otel \
           go.opentelemetry.io/otel/sdk \
           go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc \
           go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc \
           go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
  2. Bootstrap the tracer and meter providers.

    package telemetry
    
    import (
        "context"
        "time"
    
        "go.opentelemetry.io/otel"
        "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
        "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
        "go.opentelemetry.io/otel/sdk/resource"
        sdktrace "go.opentelemetry.io/otel/sdk/trace"
        sdkmetric "go.opentelemetry.io/otel/sdk/metric"
        semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
        "google.golang.org/grpc"
        "google.golang.org/grpc/credentials/insecure"
    )
    
    func Init(ctx context.Context) (func(context.Context) error, error) {
        res, err := resource.New(ctx,
            resource.WithFromEnv(),
            resource.WithProcess(),
            resource.WithHost(),
            resource.WithContainer(),
            resource.WithAttributes(semconv.ServiceName("billing")),
        )
        if err != nil { return nil, err }
    
        conn, err := grpc.NewClient("otel-collector:4317", grpc.WithTransportCredentials(insecure.NewCredentials()))
        if err != nil { return nil, err }
    
        traceExp, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn))
        if err != nil { return nil, err }
    
        tp := sdktrace.NewTracerProvider(
            sdktrace.WithResource(res),
            sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(0.10))),
            sdktrace.WithBatcher(traceExp, sdktrace.WithBatchTimeout(2*time.Second)),
        )
        otel.SetTracerProvider(tp)
    
        metricExp, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithGRPCConn(conn))
        if err != nil { return nil, err }
    
        mp := sdkmetric.NewMeterProvider(
            sdkmetric.WithResource(res),
            sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, sdkmetric.WithInterval(15*time.Second))),
        )
        otel.SetMeterProvider(mp)
    
        return func(ctx context.Context) error {
            _ = tp.Shutdown(ctx)
            _ = mp.Shutdown(ctx)
            return nil
        }, nil
    }

    The sampler TraceIDRatioBased(0.10) keeps 10% of traces — pick a rate that fits your traffic and budget.

  3. Instrument HTTP servers and clients. The contrib middleware does this automatically:

    import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
    
    mux := http.NewServeMux()
    mux.HandleFunc("/api/v1/users/{id}", getUser)
    handler := otelhttp.NewHandler(mux, "http-server")
    srv := &http.Server{Addr: ":8080", Handler: handler}

    Outbound clients:

    client := &http.Client{
        Transport: otelhttp.NewTransport(http.DefaultTransport),
    }
    resp, _ := client.Get("https://upstream.internal/x")
  4. Add custom spans where the request flow needs them.

    import "go.opentelemetry.io/otel"
    
    func chargeCustomer(ctx context.Context, id string) error {
        ctx, span := otel.Tracer("billing").Start(ctx, "chargeCustomer")
        defer span.End()
        span.SetAttributes(attribute.String("customer.id", id))
    
        if err := verifyBalance(ctx, id); err != nil {
            span.RecordError(err)
            span.SetStatus(codes.Error, "balance check failed")
            return err
        }
        return execCharge(ctx, id)
    }
  5. Emit metrics from business code.

    meter := otel.Meter("billing")
    chargeCounter, _ := meter.Int64Counter("billing.charges.completed",
        metric.WithDescription("Number of successful charges"))
    chargeLatency, _ := meter.Float64Histogram("billing.charges.latency",
        metric.WithUnit("ms"))
    
    t0 := time.Now()
    if err := execCharge(ctx, id); err == nil {
        chargeCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("currency", currency)))
    }
    chargeLatency.Record(ctx, float64(time.Since(t0).Milliseconds()))

    Resist the urge to put high-cardinality fields (user ID, request ID) on attributes — they create a fresh metric series per value and blow up your backend bill.

  6. Wire shutdown into your service. The shutdown hook flushes batched spans:

    shutdown, err := telemetry.Init(ctx)
    if err != nil { log.Fatal(err) }
    defer shutdown(context.Background())

    Without this, the process can exit before the batcher flushes — last few seconds of traces are lost.

  7. OpenTelemetry Collector config. A minimal otel-config.yaml:

    receivers:
      otlp:
        protocols:
          grpc: { endpoint: 0.0.0.0:4317 }
          http: { endpoint: 0.0.0.0:4318 }
    processors:
      batch: {}
      memory_limiter:
        check_interval: 5s
        limit_mib: 256
    exporters:
      debug: { verbosity: detailed }
      # otlphttp: { endpoint: https://vendor.example.com }
    service:
      pipelines:
        traces:  { receivers: [otlp], processors: [memory_limiter, batch], exporters: [debug] }
        metrics: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [debug] }

Common pitfalls

  • High-cardinality attributes blow up backend bills. Customer IDs and request IDs belong on the span, NOT on metric labels. Use a service.namespace, service.name, http.route shape for metrics.
  • TracerProvider and MeterProvider need explicit shutdown. Missing it loses the tail. Wire it into defer shutdown(...) from main.
  • Auto-detected resource attributes can leak. resource.WithHost() adds the hostname — fine on bare metal, exposes pod IPs in Kubernetes. Filter or override.
  • Sampling at 100% in production is costly. A ratio between 1% and 10% is typical; use head-based sampling with ParentBased so child spans inherit the parent’s sampling decision.
  • otelhttp.NewHandler sets the span name from the request path by default. Replace with WithSpanNameFormatter so dynamic paths group correctly (e.g. /users/42 rolls up to GET /users/:id).

Stack Harbor wires OpenTelemetry into every Go service we operate, ships an OpenTelemetry Collector in the same cluster, and feeds it to the observability stack the client already pays for. See how that fits into our managed operations practice.