Production OpenTelemetry: Distributed Tracing, Trace Context, Sampling, and Cost Control

Production OpenTelemetry: Distributed Tracing, Trace Context, Sampling, and Cost Control

In a distributed application, a user request is rarely handled by one process. It may pass through an API gateway, an ASP.NET Core service, a downstream HTTP API, SQL Server, and a message broker. When a user reports that a page is slow, application logs often show only the total request duration. They do not explain whether the time was spent in a database query, a remote call, connection-pool waiting, or application code.

OpenTelemetry addresses this problem with a shared trace context and spans that represent individual operations. A production implementation, however, requires more than installing an SDK package. Context propagation, span naming, sensitive-data handling, sampling, and Collector capacity must be designed together.

The practical problem: latency has no visible owner

Assume GET /orders/4812 normally completes in 180 milliseconds, but some requests take 2.8 seconds. An API log can show the total duration, yet it cannot prove whether 2.4 seconds were spent in SQL Server, a downstream HTTP request, or waiting for an available connection.

A distributed trace exposes the operation as a hierarchy:

  • Server span: GET /orders/{orderId}
  • Child span: HTTP GET inventory service
  • Child span: SQL SELECT orders
  • Child span: SQL SELECT order_items

This lets an engineer compare the duration, status, and attributes of each step instead of guessing from aggregate logs. In OpenTelemetry, a trace is a related set of spans representing one logical operation. For a trace to cross service boundaries, its context must travel through HTTP headers or message metadata.

Why trace context matters

OpenTelemetry can use the W3C Trace Context format so that independent services recognize the same trace. The essential information is commonly carried in the traceparent header. The first service creates a trace; downstream services extract the context and create child spans linked to the upstream operation.

When propagation breaks, the observability backend displays several unrelated traces instead of one request chain. Test the following boundaries explicitly:

  1. Does the server extract context from incoming HTTP requests?
  2. Does the outgoing HttpClient request inject context?
  3. Is context preserved across asynchronous tasks and background execution?
  4. Are trace values copied into message headers when a message is published?
  5. Are incoming trace headers from untrusted clients validated and handled safely?

In .NET, Activity and ActivitySource provide the core tracing primitives. Application code can use these standard APIs without coupling itself to a particular APM vendor.

A practical ASP.NET Core setup

The following example enables application spans, ASP.NET Core requests, outgoing HTTP calls, SQL Client instrumentation, and OTLP export:

using System.Diagnostics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

const string serviceName = "orders-api";
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService(serviceName: serviceName, serviceVersion: "1.0.0"))
    .WithTracing(tracing =>
    {
        tracing.AddAspNetCoreInstrumentation()
               .AddHttpClientInstrumentation()
               .AddSqlClientInstrumentation()
               .AddSource(serviceName)
               .AddOtlpExporter();
    });

var app = builder.Build();
app.MapGet("/orders/{id:int}", async (int id, OrderService service) =>
{
    using var activity = OrdersTelemetry.Source.StartActivity("Order.Load");
    activity?.SetTag("order.id", id);
    return await service.LoadAsync(id);
});
app.Run();

static class OrdersTelemetry
{
    public static readonly ActivitySource Source = new("orders-api");
}

The AddSource(serviceName) call registers the application ActivitySource with the SDK. Without that registration, custom spans may be created in code but never reach the exporter. ASP.NET Core can also emit HTTP server Activities; depending on the .NET version and instrumentation packages, the framework ActivitySource may need to be registered explicitly.

Designing span names and attributes

A span name should not contain a unique value for every request. Both GET /orders/4812 and GET /orders/4813 should normally use a stable name such as GET /orders/{id}. Otherwise, the backend receives a large number of low-value time series and query performance and storage costs increase.

Separate useful diagnostic attributes from dangerous or excessively variable data:

Better choiceRisky choice
order.status=paidFull customer name
tenant.region=eu-westEmail address
db.operation=SELECTRaw SQL parameters
payment.provider=stripeToken, password, or card data

High-cardinality values such as order IDs or user IDs can occasionally be useful for investigation, but indexing every value is expensive. Avoiding sensitive data at the source is safer than attempting to redact it later.

Sampling: do not retain every successful trace

At high traffic volumes, storing every successful request with full detail can create unnecessary cost. Sampling determines which traces are retained. A fixed percentage is simple, but it can randomly discard the failed requests that engineers most need to inspect.

A more useful production policy often combines these rules:

  • Keep traces with errors or unusually high latency.
  • Sample a smaller percentage of fast, successful requests.
  • Filter health checks, static files, and other predictable noise.
  • Use a higher rate for critical payment or data-change operations.

Sampling decisions should remain coherent across a distributed request. If one service accepts a trace while another independently rejects it, the backend may show incomplete trees with missing root or child spans.

Use a Collector to separate applications from backends

Placing an OpenTelemetry Collector between applications and the observability backend provides a flexible control point. Applications send OTLP data to the Collector, while the Collector handles batching, filtering, routing, and forwarding to one or more backends.

receivers:
  otlp:
    protocols:
      grpc:
      http:

processors:
  batch:
  memory_limiter:
    limit_mib: 512

exporters:
  otlphttp:
    endpoint: https://observability.example.com

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [otlphttp]

Monitor the Collector itself. If the export destination slows down, memory must not grow without limits. Batch sizes, timeouts, queue behavior, and memory limits should be tested with a traffic profile that resembles production rather than selected only from a development laptop.

Connect logs, metrics, and traces

Do not investigate an incident in the trace interface alone. Include the current TraceId and SpanId in application logs so an engineer can move directly from a log entry to the related trace. Metrics such as request duration, error rate, and queue length are better for alerting; traces explain the cause behind an alert.

Production readiness checklist

  • Does every service have a stable service name and version?
  • Has context propagation been tested across HTTP, database, and messaging boundaries?
  • Are span names normalized to avoid uncontrolled cardinality?
  • Are passwords, tokens, personal data, and raw query parameters excluded?
  • Does the sampling policy preserve failed and slow operations?
  • Can Collector backpressure block the main business workflow?
  • Can engineers navigate from a trace ID to related logs and metrics?

The value of OpenTelemetry is not collecting the largest possible amount of data. It is collecting the right data with the right context. Start with one critical business flow, verify propagation end to end, remove unnecessary attributes, and measure the cost limits. Then extend the same telemetry contract to other services, database calls, and asynchronous message flows.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published