Back to Blog
TutorialsFullstack

Distributed Tracing with OpenTelemetry: Diagnosing Microservice Performance and Failures

Mustaf Abubakar
Mustaf Abubakar
•15 min read
Distributed Tracing with OpenTelemetry: Diagnosing Microservice Performance and Failures

A customer reports that an order page takes six seconds to load. The API gateway reports a successful response, the application logs contain no obvious exception, and the database dashboard shows normal average CPU utilization. Each component appears healthy in isolation, yet the user experience is poor.

This is a typical observability problem in distributed systems. A request may cross several application services, databases, caches and message brokers. Looking at each component separately does not necessarily explain what happened to an individual request.

Distributed tracing makes that journey visible. OpenTelemetry provides a vendor-neutral way to instrument applications and collect the telemetry needed to reconstruct it. This guide explains how to design a useful tracing system, interpret its results and avoid common operational and security mistakes. All service names, timing examples and configuration endpoints below are illustrative.

1. Understand traces and spans

A trace describes a logical operation across one or more components. A span represents an individual unit of work within that operation, such as handling an HTTP request, querying a database or calling a downstream service.

A well-instrumented request may produce a hierarchy like this:

checkout.request
  |-- inventory.reserve
  |     |-- database.query
  |-- pricing.calculate
  |-- payment.authorize
        |-- provider.request

The trace identifier associates these operations with the same request. Individual span identifiers distinguish work within that trace. Parent relationships indicate how operations are connected. Spans can also contain timestamps, attributes, events and status information.

For asynchronous or batched operations, a strict parent-child hierarchy may not adequately describe causality. Span links can express relationships to other span contexts, such as several messages contributing to one processing operation.

The official OpenTelemetry tracing concepts and trace data model describe these building blocks.

2. Propagate context between services

Instrumentation inside a single process provides only a local view. The next step is to carry the trace context when the request crosses a service boundary.

For HTTP communication, the W3C Trace Context standard defines interoperable headers, including traceparent and tracestate. A client-side instrumentation layer injects the appropriate context into an outgoing request, while server-side instrumentation extracts it and uses it when creating a receiving span.

The following sequence illustrates the relationship:

Gateway: trace A, span 1
    |
    | HTTP request with propagated trace context
    v
Order service: trace A, span 2
    |
    | HTTP request with updated parent context
    v
Inventory service: trace A, span 3

Use maintained framework and HTTP client instrumentation instead of manually constructing trace headers. Ensure that instrumentation also covers task queues, asynchronous execution and the relevant messaging boundaries.

Trace propagation is not authentication. Incoming trace headers are caller-controlled data and must never establish user identity, permissions or tenancy. At external trust boundaries, define which context is accepted, replaced or filtered. Avoid forwarding sensitive information through baggage or propagating internal context to unrelated external destinations.

3. Start with a small instrumentation exercise

Before attempting to instrument a complete application, establish that the SDK creates spans with the intended relationships. The following example uses Python 3 and the OpenTelemetry Python API and SDK. Choose compatible package versions for your environment and lock them in your project's dependency manifest.

For an isolated development environment, install the packages:

python -m pip install opentelemetry-api opentelemetry-sdk

Create a file called tracing_demo.py:

import time

from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    ConsoleSpanExporter,
    SimpleSpanProcessor,
)

provider = TracerProvider(
    resource=Resource.create({"service.name": "checkout-demo"})
)
provider.add_span_processor(
    SimpleSpanProcessor(ConsoleSpanExporter())
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("checkout.demo")

try:
    with tracer.start_as_current_span("checkout.request"):
        with tracer.start_as_current_span("inventory.reserve"):
            time.sleep(0.03)
        with tracer.start_as_current_span("payment.authorize"):
            time.sleep(0.08)
finally:
    provider.shutdown()

Run the file with Python. The console output should contain three spans. The two inner spans should share the outer span's trace identifier and reference its span identifier as their parent. The sleep calls simulate work; they do not connect to real inventory or payment services.

This exercise intentionally uses a synchronous console exporter to make the relationships easy to inspect. A production service generally needs bounded buffering and asynchronous export rather than writing each completed span to the console.

For a distributed test, use your actual server and client instrumentation libraries, send a synthetic request between two test services and verify the trace identifier is preserved across the boundary. The Python instrumentation documentation provides additional examples.

4. Introduce a telemetry collection pipeline

A common production architecture separates application instrumentation from telemetry routing and processing:

Instrumented services
        |
        | OTLP
        v
OpenTelemetry Collector
        |
        | configured exporters
        v
Trace storage and analysis backend

The Collector can receive telemetry, apply configured processing and export the resulting data to a compatible destination. This lets teams centralize filtering, batching and routing rather than embedding every backend-specific integration in application code.

For a local Collector distribution that includes the OTLP receiver, batch processor and debug exporter, the following minimal configuration illustrates the pipeline:

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 127.0.0.1:4317
      http:
        endpoint: 127.0.0.1:4318

processors:
  batch: {}

exporters:
  debug:
    verbosity: basic

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [debug]

The receiver is intentionally bound to loopback for this local test. If the application and Collector run in different containers or hosts, the network address and access controls must be adjusted appropriately. Install a compatible OTLP exporter for the application and configure the corresponding transport; the console example above does not itself send OTLP data.

Consult the Collector configuration guide for component availability and configuration options. Before production deployment, validate the configuration using your selected Collector distribution, configure protected transport and establish resource limits.

5. Diagnose latency using trace timelines

Imagine that a sampled checkout trace contains the following spans. These are invented measurements intended to demonstrate interpretation.

OperationStart relative to requestDuration
Checkout request0 ms900 ms
Authentication20 ms40 ms
Inventory lookup70 ms120 ms
Price calculation70 ms180 ms
Payment authorization260 ms600 ms

The inventory and pricing operations overlap. Adding every child duration would double-count some elapsed time. Instead, inspect the dependency path that determines when the response can finish.

The payment authorization occupies a large part of the example request. That does not establish why the operation is slow. Its child spans may reveal network waiting, retries, connection-pool acquisition or an external dependency. Missing instrumentation can also leave unexplained gaps.

A useful investigation begins with the affected route and time window, identifies representative slow and normal traces, compares their structure and then checks the corresponding service metrics and logs. Look for recurring patterns rather than assuming a single trace represents the entire system.

For example, if slow traces consistently show a long database connection acquisition span but short query execution, the investigation should focus on pool contention before rewriting the SQL. If the time instead appears inside a database execution span, execution plans and database statistics become useful supporting evidence.

6. Balance visibility and cost with sampling

Tracing every request can become expensive as traffic grows. Sampling is an operational policy for deciding which traces to retain.

Head sampling makes a decision near the beginning of a trace. It is efficient because it can reduce the amount of telemetry recorded and transported early. However, the final latency and outcome of the request are not yet known.

Tail sampling makes a later decision using received span information. It can prioritize traces with errors or unusual duration, but requires the pipeline to buffer and correlate relevant spans. In a scaled pipeline, route spans belonging to a trace consistently to the sampling stage responsible for that trace.

Neither strategy automatically guarantees complete visibility. An error occurring in a request discarded by an earlier sampling stage cannot be recovered simply by adding a later tail sampler. Late spans, overload and exporter failures can also affect completeness.

Start with a documented policy appropriate to your traffic and incident-response needs. Measure the effect on telemetry volume and representative trace coverage before reducing the sampling rate further. See the OpenTelemetry sampling guide for the design trade-offs.

7. Protect telemetry as sensitive operational data

Observability systems frequently receive information from across the infrastructure. Poorly designed instrumentation can become an unintended data-disclosure channel.

Use consistent service identifiers and stable operation names. Follow the HTTP semantic conventions supported by your instrumentation version. Prefer route templates to arbitrary identifiers in operation names, and keep unbounded values out of metric labels.

Do not record access tokens, session cookies, payment credentials, customer records or raw request bodies by default. Review database instrumentation carefully because query text and parameters may contain sensitive information. Apply minimization at instrumentation time rather than relying entirely on downstream filtering.

Protect Collector receivers, exporters and trace storage through authentication, encryption where applicable, network restrictions and role-based access. Document retention rules and audit access to sensitive traces. For multitenant applications, enforce data isolation in the telemetry pipeline and analysis backend rather than trusting a tenant attribute supplied by the client.

8. Verify the tracing system before relying on it

A trace dashboard is useful only if the collection pipeline behaves predictably. Test a normal request, an authorized failure scenario and a slow dependency in a staging environment. Check that all expected service spans appear, parent relationships are correct, sensitive fields are absent and the correct service identity is attached.

Also test what happens when the Collector or backend is unavailable. Telemetry should not create an uncontrolled application failure cascade. Bound exporter queues and retries, monitor dropped telemetry and record the impact of overload. Keep application availability and telemetry availability distinct in your operational alerts.

Finally, make tracing part of incident response. Establish who owns instrumentation quality, how engineers locate affected requests and which evidence must be checked before attributing a failure to another service.

Conclusion

Distributed tracing provides a request-level view of behavior that isolated component dashboards cannot offer. OpenTelemetry helps standardize instrumentation, context propagation and telemetry collection without requiring a single proprietary backend.

Start with a small verified trace, extend it across real service boundaries and then introduce a controlled collection and sampling pipeline. Combine trace evidence with metrics, logs and domain knowledge. The objective is not to collect the maximum number of spans, but to obtain enough reliable and protected evidence to diagnose problems and improve service performance.

References and further reading

Comments

No comments yet

Be the first to share your thoughts!

Leave a Comment

Your email will not be published

0/1000 characters

Want to work together?

I'm always open to discussing new projects and opportunities.

Get in Touch