Part 6 ยท Chapter 20

Distributed Tracing: Following the Breadcrumbs

When a request touches 10 microservices and the response is slow, how do you know which one caused it? OpenTelemetry has the answer.

What you'll learn in this chapter

  • What a trace is and what a span is โ€” with real analogies
  • Why distributed tracing is the third pillar of observability
  • OpenTelemetry โ€” the vendor-neutral standard
  • Auto-instrumenting Node.js, Python, and Java
  • The OpenTelemetry Collector
  • Viewing traces in Jaeger
  • Context propagation across services
  • Grafana Tempo for the full open-source stack

The Package Tracking Analogy

Imagine a package traveling through a logistics network. It leaves Lagos โ†’ arrives at a sorting depot โ†’ loaded onto a truck โ†’ regional hub โ†’ local delivery rider โ†’ delivered to your door. If the package is three days late, which step was the problem? Without a tracking number scanned at every checkpoint, you have no idea.

In a microservices system, a single user request might travel through: API Gateway โ†’ Auth Service โ†’ User Service โ†’ Product Service โ†’ Inventory Service โ†’ Payment Service. If the final response takes 4 seconds instead of 200 ms, which service is the bottleneck? Distributed tracing gives every request a unique ID โ€” the tracking number โ€” and records exactly how long each service took to handle its part.

๐Ÿ“Œ Key Terms
  • Trace: the complete journey of one request through all services
  • Span: a single operation within a trace (one service handling its part)
  • Trace ID: the unique ID that connects all spans of one request
  • Parent span / child span: spans nest โ€” Service A calls B (B is a child of A)
  • Attributes: key-value metadata on a span (HTTP method, user ID, status code)

What a Trace Looks Like

Trace ID: abc-123-xyz (total: 380ms) โ”‚ โ”œโ”€โ”€ API Gateway [0ms โ†’ 380ms] โ”‚ โ”œโ”€โ”€ Auth Service [5ms โ†’ 25ms] โœ“ fast โ”‚ โ”œโ”€โ”€ User Service [25ms โ†’ 60ms] โœ“ fast โ”‚ โ””โ”€โ”€ Product Service [60ms โ†’ 350ms] โ† SLOW โ”‚ โ”œโ”€โ”€ Database Query (no index) [60ms โ†’ 310ms] โ† ROOT CAUSE โ”‚ โ””โ”€โ”€ Redis Cache Lookup [310ms โ†’ 320ms] โœ“ โ””โ”€โ”€ Response serialization [350ms โ†’ 380ms] โœ“

In seconds, you can see that Product Service took 290 ms โ€” and within it, a database query with a missing index took 250 ms. Without tracing, you'd grep logs for hours and still not find this.

OpenTelemetry โ€” Instrument Once, Export Anywhere

Before OpenTelemetry existed, every vendor (Datadog, New Relic, Jaeger, Zipkin, AWS X-Ray) had its own proprietary SDK. If you instrumented your code for Datadog and then switched to Jaeger, you'd have to re-instrument everything.

OpenTelemetry (OTel) created a vendor-neutral standard. You instrument your code once with the OTel SDK. Then you export to any backend: Jaeger, Zipkin, Datadog, New Relic, Grafana Tempo, AWS X-Ray โ€” without changing your application code.

Your App (OTel SDK) โ”‚ OTLP protocol โ–ผ OTel Collector โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Jaeger โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ–บ Grafana Tempo โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ–บ Datadog โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ””โ”€โ”€โ”€โ”€โ”€โ”€โ–บ AWS X-Ray

Instrumenting Node.js with OpenTelemetry

The auto-instrumentations package automatically traces HTTP requests, Express routes, database calls (PostgreSQL, MySQL, Redis), and outgoing HTTP calls โ€” without writing a single line of tracing code in your handlers.

# Install packages
npm install @opentelemetry/sdk-node \
  @opentelemetry/auto-instrumentations-node \
  @opentelemetry/exporter-trace-otlp-http \
  @opentelemetry/resources \
  @opentelemetry/semantic-conventions
// tracing.js โ€” import this FIRST in your app entrypoint
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

const sdk = new NodeSDK({
  resource: new Resource({
    [SEMRESATTRS_SERVICE_NAME]: 'my-api',
  }),
  traceExporter: new OTLPTraceExporter({
    url: 'http://otel-collector:4318/v1/traces',
  }),
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();
process.on('SIGTERM', () => sdk.shutdown());

Then in your package.json start script:

"start": "node --require ./tracing.js server.js"

Manual Spans for Custom Operations

import { trace, SpanStatusCode } from '@opentelemetry/api';

const tracer = trace.getTracer('my-api');

async function processPayment(orderId, amount) {
  return tracer.startActiveSpan('process-payment', async (span) => {
    try {
      span.setAttributes({
        'payment.order_id': orderId,
        'payment.amount': amount,
      });
      const result = await chargeCard(orderId, amount);
      span.setStatus({ code: SpanStatusCode.OK });
      return result;
    } catch (error) {
      span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
      span.recordException(error);
      throw error;
    } finally {
      span.end();
    }
  });
}

Instrumenting Python with OpenTelemetry

# Install
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install

# Run FastAPI with auto-instrumentation
opentelemetry-instrument \
  --service_name my-api \
  --exporter_otlp_endpoint http://otel-collector:4317 \
  uvicorn main:app --host 0.0.0.0 --port 8000

Or configure in code:

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

provider = TracerProvider()
provider.add_span_processor(
    BatchSpanProcessor(OTLPSpanExporter(endpoint="http://otel-collector:4318/v1/traces"))
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("my-api")

The OpenTelemetry Collector

The Collector is a middleman that sits between your apps and your tracing backends. Apps send traces to the Collector; the Collector forwards them to Jaeger, Tempo, Datadog, or all three simultaneously.

# otel-collector-config.yaml
receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318
      grpc:
        endpoint: 0.0.0.0:4317

processors:
  batch:
    timeout: 5s
  memory_limiter:
    limit_mib: 400

exporters:
  jaeger:
    endpoint: jaeger:14250
    tls:
      insecure: true
  logging:
    loglevel: debug

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

Running Jaeger for Local Development

docker run -d \
  -p 16686:16686 \   # Jaeger UI
  -p 14250:14250 \   # gRPC receiver
  -p 6831:6831/udp \ # Jaeger compact thrift
  --name jaeger \
  jaegertracing/all-in-one:latest

Open http://localhost:16686. Search by service name or trace ID. Click any trace to see the full span waterfall.

Context Propagation โ€” How Traces Cross Services

When Service A makes an HTTP call to Service B, it must pass the trace ID so that Service B's spans are attached to the same trace. This is done via HTTP headers:

# W3C TraceContext header (the standard)
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
#            version-traceId (32 hex)-spanId (16 hex)-flags

OpenTelemetry auto-instrumentations propagate this header automatically for all outgoing HTTP calls. For message queues (Kafka, RabbitMQ), you inject the header into the message metadata and extract it on the consumer side.

Grafana Tempo โ€” Traces in the Grafana Stack

If you're already using Prometheus (metrics) and Loki (logs) with Grafana, adding Grafana Tempo completes the observability triangle. Tempo stores traces efficiently, and Grafana links traces to logs and metrics automatically.

The full open-source stack: Prometheus (metrics) + Loki (logs) + Tempo (traces) + Grafana (visualization). Everything from one vendor, all open source, no cloud lock-in.

Chapter Summary

  • A trace is a request's complete journey; a span is one operation within that journey
  • OpenTelemetry is the vendor-neutral standard โ€” instrument once, export anywhere
  • Auto-instrumentations handle HTTP, databases, and queues with no code changes
  • The OTel Collector decouples apps from specific tracing backends
  • Context propagation via traceparent headers ties spans across services
  • Jaeger provides an open-source trace viewer; Grafana Tempo integrates with the PLG stack