ARTICLE - Monitoring & Alerting

APM and Distributed Tracing: OpenTelemetry in Practice

Without tracing, cross-service performance problems are guesses. This article covers trace, span, and context propagation, treats sampling as a design decision rather than a toggle, and focuses on head versus tail sampling, which span labels let you filter by business dimension, five common causes of broken traces, and how tracing divides work with metrics and logs.

2026-08-06 OpenTelemetry Docs

APM and Distributed Tracing: OpenTelemetry in Practice

In a monolith, "slow" was a problem you could follow down through the logs. After splitting into a frontend, a gateway, several services, a database, and third-party APIs, the same "slow" becomes a set of questions: which service, at the entry or at a dependency, all requests or one class of request, one user or everyone. Metrics answer part of it, but they rarely answer which hop.

Distributed tracing solves that localization problem. It strings every stage a request passes through into a single timeline, with duration, status, and attributes attached to each stage, so "which hop is slow" turns from inference into reading. The cost is volume and complexity: one request can produce dozens of spans, and a site handling billions of requests a day cannot store all of it.

This article follows that trade-off: the three objects of trace, span, and context; then sampling as a required design decision - where head sampling and tail sampling differ and why troubleshooting actually needs tail sampling; label design; five common causes of broken traces; how tracing divides work with metrics and logs; and finally cost governance plus two common misuses. For what metrics to watch, see what to monitor; this piece is about localizing an anomaly to one hop.

1. Without Tracing, Cross-Service Performance Problems Are Guesses

1.1 Metrics Show That It Is Slow, Not Which Hop Is Slow

Aggregate metrics are address-free: they say a service's P95 moved up, but not which branches those slow requests took, which dependency they waited on, or whether the delay was a timeout or a queue. Investigation degrades into layered guesses: suspect the database, check it, it looks fine; suspect the cache, check the hit rate, it looks fine; check the downstream service, also fine. Each guess costs time while the incident continues.

Logs add context, but they are scattered across services and share no common key. Reconstructing one request from logs means searching several systems by time window and guessing which entries belong together based on timestamps and parameters. As volume grows, that approach gets exponentially more expensive and easily mixes two concurrent requests.

Tracing closes exactly this gap: it assigns an identifier to a request in advance, so every related record carries the same identifier and a parent-child relation, and "reconstruct the path" becomes a query rather than detective work. The difference is invisible on a normal day and is the difference between minutes and hours during a cross-service failure.

1.2 Trace, Span, and Context: What Each Object Owns

A trace is the full path of one request. It is not data itself but an identifier plus a set of spans. Every operation belonging to that request shares the same trace identifier, and that identifier is the basis for all later correlation.

A span is one unit of work in the path. It records an operation name, start and end times, status, attributes, and a reference to its parent span. Parent-child relations form a tree, and the duration of a request can be decomposed level by level: total duration minus child spans leaves the overhead of that segment. Without that subtraction, "which hop is slow" can only be guessed by reading code.

Context propagation is the mechanism that ties the three together: as a request leaves one service, the trace identifier and current span identifier are written into request headers (or message attributes), and the next service reads them and attaches its own span. Once propagation breaks, the trace breaks there - subsequent spans form a new, isolated tree. Chapter four covers why this fails so often.

2. Sampling Is a Design Decision, Not a Toggle

2.1 Why Full Collection Is Not Viable

The number of spans per request scales with call depth, and depth in microservice architectures usually far exceeds intuition: one page request can fan out into dozens of internal calls. Multiply spans by request volume, then by storage and indexing cost per record, and the result is normally one to two orders of magnitude above the entire metrics system. Full collection is not "a bit expensive"; it is unsustainable.

Full collection also slows the system down. Creating, serializing, and exporting each span consumes CPU and network, and under high load that overhead lands exactly when you can least afford it. The first principle of tracing is that observation must not change the observed system, and full collection routinely violates it.

So sampling is not an optional optimization but foundational design. The question it must answer: given that only a fraction of data survives, how do we ensure the requests we will want to inspect during an incident are probably among them? The answer determines whether the tracing system is useful when it matters.

2.2 Head Sampling: Decided at Ingress, Cheap but Loses the Samples That Matter

Head sampling decides at the entrance of a request: a fixed ratio or a rule determines whether this request is sampled, and the whole trace follows that decision. It is simple to implement, cost is predictable, downstream services need no judgment, and the decision can be written into the context so the trace stays complete.

The problem comes from deciding at ingress: at that moment you do not yet know this request will be slow or will fail. With a fixed ratio, slow requests and error requests are dropped at the same rate as everything else - and those are precisely what you need during an incident. In the extreme, a failure that affects one request in a thousand with a one percent sampling rate may yield no sample at all.

An improved head sampling applies rules: exclude low-value traffic such as health checks and static assets entirely, raise the sampling rate for key endpoints, and attach keep rules for error statuses. This improves signal-to-noise noticeably, but it still cannot know at ingress whether a request will be slow, so efficiency for long-tail problems stays limited.

2.3 Tail Sampling: Collect First, Keep What Troubleshooting Needs

Tail sampling postpones the decision until after the request finishes: each service reports spans to a collection tier, and that tier evaluates the completed trace - was it slow, did it error, does it match a label - then decides to keep or drop.

That reordering matches troubleshooting exactly: slow and failed are properties known only after the fact. Tail sampling can therefore keep all slow and error traces while sampling the rest, giving a far higher hit rate for incident samples at the same storage cost than head sampling.

The price is a stateful collection tier: it must buffer traces in memory, wait for completion, handle incomplete traces where downstream spans arrive late or never, and scale horizontally itself. That engineering complexity is a real cost, but what it buys is "there will be a sample when it matters", which is usually worth it.

The two are not mutually exclusive: a common pattern is coarse head sampling at ingress to reduce volume, then tail sampling to refine the survivors. The key is to never let "drop by ratio" be the only strategy, because that amounts to randomly discarding evidence during an incident. Platform implementations differ; see vendor documentation such as Datadog for how a commercial APM handles sampling.

3. What Labels a Span Should Carry

3.1 Three Mandatory Groups: Service, Operation, Status

The service name says who did this segment, the operation name says what it was doing, and the status says whether it succeeded. With all three, a trace becomes readable: you can see call order, duration distribution, and where failures occurred. Missing any one degrades the trace into a set of anonymous fragments with only durations.

Status should distinguish at least three cases: success, business failure (the service responded normally but the result means failure), and technical failure (timeout, connection error, 5xx). Collapsing these into one boolean makes it impossible to separate "the user's action was correctly rejected" from "the system broke", and those two differ by orders of magnitude in volume.

Operation names must be stable and aggregatable. Concatenating dynamic content into the name, such as a user ID or order number, turns one operation into hundreds of thousands, breaking aggregation and exploding the index. An operation name should come from a small finite set, like verb plus resource, with dynamic parts moved into attributes.

3.2 Business Fields Decide Whether You Can Filter by Business Dimension

One of the most valuable uses of tracing is filtering by business dimension: only this class of order, only this tenant, only this channel. That requires the corresponding business fields on spans. Without them you can only see that "an endpoint got slower", never "which kind of user's which kind of request got slower".

span.set_attribute("order_type", order.type)
span.set_attribute("tenant_tier", tenant.tier)
span.set_attribute("payment_method", payment.method)

The hard part is cardinality. Unique identifiers such as order numbers have extremely high cardinality; using them as labels inflates the index quickly, so they belong in fields that are searchable but not aggregatable, or only on retained sampled traces. Finite enumerations such as order type, tenant tier, and payment method have controlled cardinality and high aggregation value, and should be attached by default.

A practical test: how large is the value set of this field? Tens of values suit a label; hundreds of thousands or millions are better as log fields or attached only when needed. This test blocks most high-cardinality incidents before they happen; chapter six covers why.

4. Five Common Causes of Broken Traces

4.1 Async Queues and Batch Processing: The Two Easiest Places to Break

Async queues are the most common break point. In a synchronous call, context travels naturally in HTTP headers; once a message queue is involved, that carrier is gone, and the producer must explicitly write context into message attributes while the consumer must explicitly read it and use it as the parent span. This step is often skipped because it has no functional impact - messages are still published and consumed, the trace simply breaks in two.

Harder to spot is batch processing. To improve throughput, consumers merge several messages into one batch; if a span is created at the batch level, that span belongs to multiple traces at once and parent-child relations lose meaning. The correct approach is to restore context per message and create a span per message, recording batch-level overhead as a separate operation that belongs to no trace.

Both share a trait: they do not affect function, only observability. Functional tests will never catch them, and they surface during some cross-service investigation - when you are already paying for localization with time.

4.2 Gateways, Third-Party Calls, and SDK Versions

The gateway is the third break point. Some gateways drop headers they do not recognize, or rename and strip custom headers. Trace context travels in custom headers, so the trace breaks at the gateway. The signature is distinctive: the entry service has a complete trace, internal services each form their own tree, and the two trees share no link.

Third-party calls are the fourth. You cannot force an external service into your trace, but you should at least record the hop on your side: when it was sent, how long it took, what came back. Without that hop, a trace shows "total duration three seconds" while internal spans sum to three hundred milliseconds, and the remaining 2.7 seconds vanish.

The fifth is mismatched SDK and protocol versions. When the same trace context travels between implementations in different languages, format, field names, and encoding must agree; in multi-language systems one service commonly uses an older propagation format while another uses a newer one, neither recognizes the other, and the trace breaks at the language boundary. During upgrades, either unify everything or support both formats for a transition period.

5. How Tracing, Metrics, and Logs Divide the Work

5.1 Three Layers Answer Three Different Questions

Metrics answer whether something is abnormal: aggregated, cheap, long-lived, good at trends and triggering alerts. They are poor at saying who, because compression sacrifices per-request identity.

Traces answer which hop is abnormal: they preserve the structure of individual requests, decompose duration, locate failure points, and show call relations. They are poor at saying why, because they record what happened, not internal state and decisions.

Logs answer why: they record events and context, including parameters, stack traces, branch decisions, and business state. They are poor at saying which hop, because entries lack structured causality and can only be strung together through correlation identifiers.

The three are complementary, not substitutable. Metrics alone stall at localization; traces alone stall at explanation; logs alone stall at detection, because their volume is too large and too scattered.

5.2 Joining Them: Alert, Then Trace, Then Logs

An effective investigation path converges step by step: an alert surfaces the anomaly from metrics, a trace finds a representative request in that time window and pins down the hop, and logs from that hop explain the cause. Each step narrows the range and consumes the previous step's output.

Making that path walkable requires three shared keys: time, service identity, and trace identifier. Time alignment enables the jump from metrics to traces; service identity enables the jump from traces to logs; the trace identifier lets logs filter precisely to one request. The most commonly missing one is the last - many systems do not print trace identifiers in logs, so the trace-to-log step is left to timestamp guessing.

So one acceptance criterion for tracing is that going from an alert to a specific line of code requires no more than one manual copy-paste. Failing that criterion means one of the three keys is missing, not that the tooling is inadequate. For log aggregation and querying, see log aggregation with Loki queries; for metrics and dashboards, see Prometheus and Grafana basics.

6. Cost Governance

6.1 Sampling Rate, Retention, and Pre-Aggregation

The first lever is sampling rate, but it must be applied by category: error and slow traces should be kept as completely as possible, while healthy traces can be sampled far lower because their value lies in distribution rather than individual detail. Allocating the sampling budget by outcome rather than by ingress is the highest-return practice.

The second lever is retention. Most investigation happens within hours of a failure; beyond that window individual traces lose value quickly, while aggregate metrics derived from traces - latency distributions per operation, error rates, call volumes - stay valuable for a long time. The sensible structure is short retention for individual traces and long retention for aggregates, not one retention period for everything.

The third lever is removing low-value spans. Health checks, static assets, and internal cache hits are frequent, low-information operations that can be filtered at collection or collapsed into counters. In traces they are almost always healthy and enormous in number, yet they consume a visible share of storage and indexing budget.

6.2 High-Cardinality Labels: The Most Common Self-Inflicted Wound

Using user IDs, order numbers, request IDs, or full URL paths as labels is the most common and most expensive mistake in tracing systems. The reason is how indexing works: each distinct label value may need its own timeseries or index entry, and as distinct values multiply, storage and query cost rise non-linearly, sometimes bringing the query tier down entirely.

The mistake is common because it is invisible at small scale: a test environment with a few hundred records behaves perfectly, and after launch the cost spirals while a large history has already accumulated.

Three defenses: maintain a label allowlist that admits only semantic-convention fields and a few business enumerations; demote high-cardinality fields to sampled-only data or push them into logs instead of traces; and audit label cardinality periodically to find fields whose value counts are growing abnormally. For cost attribution and budget splitting, see Grafana Cloud cost attribution.

7. Two Workload Misuses and a Rollout Order

7.1 Using Tracing as a Log Store; Tracing Without Business Dimensions

The first misuse is treating the tracing system as a log search tool: typing keywords and scanning text fields inside spans for an error message. It works technically, but costs a great deal and is very inefficient - trace indexes are not built for full-text search, and log systems are. Using the right tool for the job beats piling features into one.

The second misuse is tracing without business dimensions. Traces are complete, durations are clear, statuses are present, but every span carries only technical fields - no order type, tenant, or channel. The result: you can see that a P99 rose but cannot answer which users were affected. That is crippling in real incidents, because blast radius often matters more than root cause - it decides whom to notify and which feature to degrade first.

Both misuses share one root: treating traces as a record of technical detail rather than a record of the user journey. The value ceiling of a tracing system is set by how much business questions it can answer.

7.2 Self-Check Table and Rollout Order

Roll out from one critical journey rather than site-wide. Pick a journey such as checkout, make its context propagation complete, put business enumerations on its span labels, include trace identifiers in its logs, then use that journey as the template for others. Site-wide rollout means facing several break points and several high-cardinality problems simultaneously, where each masks the others.

Check Test First action if it fails
Trace completeness Spans of a critical journey form one tree Inspect queues, gateways, and language boundaries
Sampling strategy Slow and failed requests are retained Move from pure ratio to outcome-based sampling
Label convention Service, operation, and status present Fill in semantic convention fields
Business dimensions Filterable by order type or tenant Add low-cardinality business enumerations
Correlation key Logs carry the trace identifier Inject it centrally in logging middleware
Cardinality audit Label value counts stay controlled Demote high-cardinality fields
Cost visibility Trace cost attributable per service Build a cost attribution view
Response path Alert to code line needs at most one copy-paste Wire jumps across metrics, traces, and logs

One last point: acceptance for a tracing system should not be how many services are instrumented, but how long the last cross-service incident took to localize. Coverage is an input metric, localization time is the output metric, and only the latter tells you whether the system works. For how alerting supports localization, see alert design basics; for paging channels and fatigue governance, see alert fatigue and on-call practice; for external availability checks, see synthetic monitoring and uptime practice; for log investigation, see server log monitoring; and for linking traces to reliability targets, see SLO and error budget practice.

Source: OpenTelemetry documentation on traces, spans, context propagation, and sampling. Mechanism descriptions follow that official material, organized and interpreted by 16IDC.

Integration & Code Examples

Example 1: Create a business span with the OpenTelemetry SDK and export it

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

provider = TracerProvider(
    resource=Resource.create({"service.name": "checkout-api",
                              "deployment.environment": "prod"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
    endpoint=os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"),
)))
trace.set_tracer_provider(provider)

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("charge_card") as span:
    span.set_attribute("payment.provider", "acme")
    span.set_attribute("order.id", "20260714001")
    span.set_attribute("retry.count", 0)
    # downstream calls here are attached to the same trace automatically

Resource attributes pin the service name and environment; span attributes decide what you can filter on later.

Example 2: Collector config: keep errors and slow requests with tail sampling

# otel-collector.yaml
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }
processors:
  tail_sampling:
    decision_wait: 10s
    policies:
      - {name: errors, type: status_code, status_code: {status_codes: [ERROR]}}
      - {name: slow, type: latency, latency: {threshold_ms: 500}}
      - {name: baseline, type: probabilistic, probabilistic: {sampling_percentage: 5}}
exporters:
  otlphttp:
    endpoint: ${env:TRACE_BACKEND_ENDPOINT}
service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [tail_sampling]
      exporters: [otlphttp]

Tail sampling defers the decision until the trace ends, so slow and failed requests survive.

Limitations

  • The cost is volume and complexity: one request can produce dozens of spans, and a site handling billions of requests a day cannot store all of it.
  • The first principle of tracing is that observation must not change the observed system, and full collection routinely violates it.
  • The problem comes from deciding at ingress: at that moment you do not yet know this request will be slow or will fail.
  • Both share a trait: they do not affect function, only observability.
  • Some gateways drop headers they do not recognize, or rename and strip custom headers.

FAQ

What prerequisites come before deploying a collector?

Three things: the collector endpoint, the shared keys and a label allowlist. The collector listens on 4317 and 4318 by default, and resource attributes should fix the service name plus environment. The keys are time, service identity and trace ID — without the trace ID in logs, the chain cannot be joined.

Why does a cross-service trace split in two?

Rule out 5 places. Async queues without context in message attributes, batching that creates a span per batch, gateways dropping or renaming custom headers, third-party calls nobody records, and mixed SDK propagation formats. None of them breaks functionality; each one simply makes the trace disappear.

Do traces replace metrics and logs or sit alongside?

Alongside. Metrics answer whether something is abnormal, traces answer which hop, logs answer why. 3 keys join them: time jumps from metrics to traces, service identity from traces to logs, trace ID filters logs down to one request. Acceptance is an alert-to-code-line jump with at most 1 copy-paste.

Where can tracing cost be cut first?

Three levers: sampling rate, retention and span volume. Keep errors and slow traces nearly whole while compressing healthy traffic to something like 5%; retain individual traces briefly and aggregates long; filter health checks and static assets at collection. High-cardinality labels cost most — user IDs and order numbers grow the index non-linearly.

Related Providers

  • Datadog: when managed APM ingests OpenTelemetry spans into ready-made queries and alerts.
  • Grafana: when existing Prometheus and Tempo sources need one dashboard and alert entry point.

Community & Resources

Learning resources and tools

Original source: OpenTelemetry Docs ↗