StackPractices
advanced By Mathias Paulenko

Distributed Tracing: Propagate Trace Context Across Services

How to propagate trace context across service boundaries with OpenTelemetry. Covers span creation, context propagation, sampling, and trace analysis.

Overview

One user request in a microservices system can touch five, ten, or fifty services before a response goes back. When that request is slow or fails somewhere in the middle, per-service logs only tell you what happened inside each box — not how the boxes relate. Distributed tracing solves this by propagating a trace context alongside the request, so the spans each service creates connect into a single trace tree.

The context travels as headers: traceparent carries the trace ID, the parent span ID, and sampling flags; tracestate adds vendor-specific data; baggage carries user key-value pairs to every downstream hop. Every service that handles the request injects these headers into its outgoing calls and extracts them from incoming ones. That inject/extract pair is the whole pattern — instrumentation, sampling, and backends are built around it.

This goes beyond a correlation ID, which only tags log lines with a shared identifier. A trace also captures timing, causality, and attributes for every step, so you can see not just that a request passed through a service but how long it spent there and what it was waiting on. OpenTelemetry is the implementation most teams use today: it standardizes on W3C trace context and ships auto-instrumentation for the common frameworks. For the end-to-end setup with real backends, see the complete distributed tracing guide.

When to Use

Reach for this pattern when the request path itself is the thing you need to see:

  • A checkout call fans out to inventory, payments, and shipping, and users report it “feels slow” — the trace shows which hop eats the latency budget.
  • An error surfaces at the API gateway but the failing service sits three calls deep — the trace records the exact path and which span errored.
  • You’re mapping service dependencies before a migration — aggregated traces reveal who calls whom, including edges nobody documented.
  • Async work crosses a queue boundary — propagation keeps the consumer’s spans attached to the producing request instead of starting an orphan trace.

When NOT to Use

  • A monolith or a single-process app has no distributed boundary to cross — local profiling covers it.
  • Scripts and batch jobs with no inter-service calls gain nothing from propagation; instrument them only if you also want a job-level span view.
  • Very low-traffic services where aggressive sampling would leave you days between captured traces.
  • If all you need is “which log lines belong to this request”, correlation IDs are simpler and cheaper to operate.

Solution

OpenTelemetry handles most of the mechanics. The snippets below show the two halves of the pattern: creating spans inside a service, and moving the context across service boundaries.

Setting up OpenTelemetry (Python)

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

# Service identity — shows up as the service name in Jaeger/Zipkin
resource = Resource.create({
    "service.name": "order-service",
    "service.version": "1.0.0",
})

provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(endpoint="http://localhost:4317")  # OTLP/gRPC
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)

tracer = trace.get_tracer(__name__)

Creating spans manually

def process_order(order_id: str):
    with tracer.start_as_current_span("process_order") as span:
        span.set_attribute("order.id", order_id)

        validate_order(order_id)

        with tracer.start_as_current_span("charge_payment"):
            charge_payment(order_id)

        with tracer.start_as_current_span("update_inventory"):
            update_inventory(order_id)

Automatic instrumentation (FastAPI)

from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor

app = FastAPI()

FastAPIInstrumentor.instrument_app(app)
RequestsInstrumentor().instrument()

Injecting context into outgoing HTTP requests

import requests
from opentelemetry import trace, propagate

tracer = trace.get_tracer(__name__)

def call_payment_service(order_id: str, amount: float):
    with tracer.start_as_current_span("call_payment_service"):
        headers = {}
        # Writes traceparent (and tracestate/baggage when present) into headers
        propagate.inject(headers)

        response = requests.post(
            "http://payment-service/charge",
            json={"order_id": order_id, "amount": amount},
            headers=headers,
            timeout=5,
        )
        return response.json()

Extracting context on the receiving side

from fastapi import FastAPI, Request
from opentelemetry import trace, propagate

app = FastAPI()
tracer = trace.get_tracer(__name__)

@app.middleware("http")
async def tracing_middleware(request: Request, call_next):
    # Reads traceparent/tracestate from the incoming request
    ctx = propagate.extract(request.headers)

    with tracer.start_as_current_span(
        f"{request.method} {request.url.path}",
        context=ctx,
        kind=trace.SpanKind.SERVER,
    ) as span:
        span.set_attribute("http.request.method", request.method)
        span.set_attribute("url.path", request.url.path)
        span.set_attribute("url.scheme", request.url.scheme)

        response = await call_next(request)
        span.set_attribute("http.response.status_code", response.status_code)
        return response

Node.js with OpenTelemetry

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

const app = express();
const tracer = trace.getTracer("order-service");

app.post("/orders", async (req, res) => {
  const span = tracer.startSpan("create_order");
  try {
    span.setAttribute("order.id", req.body.orderId);
    await processOrder(req.body);
    res.json({ status: "created" });
  } catch (err) {
    span.recordException(err as Error);
    span.setStatus({ code: SpanStatusCode.ERROR });
    res.status(500).json({ error: "order failed" });
  } finally {
    span.end();
  }
});

Propagating context through message queues

import pika
import json
from opentelemetry import trace, propagate

tracer = trace.get_tracer(__name__)

# Producer — inject context into the message headers
def publish_order_event(order_data: dict):
    headers = {}
    propagate.inject(headers)

    connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
    channel = connection.channel()
    channel.basic_publish(
        exchange="",
        routing_key="orders",
        body=json.dumps(order_data),
        properties=pika.BasicProperties(headers=headers),
    )
    connection.close()

# Consumer — extract context so the span joins the same trace
def consume_order_events():
    connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
    channel = connection.channel()
    channel.queue_declare(queue="orders")

    def callback(ch, method, properties, body):
        headers = properties.headers or {}
        ctx = propagate.extract(headers)

        with tracer.start_as_current_span("process_order_event", context=ctx):
            process_order(json.loads(body))
        ch.basic_ack(delivery_tag=method.delivery_tag)

    channel.basic_consume(queue="orders", on_message_callback=callback)
    channel.start_consuming()
with tracer.start_as_current_span("process_payment") as span:
    span.add_event("payment.initiated", {"payment.id": "pay_123"})
    charge_credit_card()
    span.add_event("payment.completed", {"status": "success"})

Events are timestamps inside a span; links are different — they connect spans across async boundaries where there’s no single parent. A batch consumer that joins several messages can’t pick one traceparent as parent, so it links every incoming span context instead:

from opentelemetry import trace, propagate
from opentelemetry.trace import Link

def process_order_batch(messages):
    # Each message's extracted context becomes a link, not a parent
    links = [
        Link(
            trace.get_current_span(
                propagate.extract(m.headers or {})
            ).get_span_context()
        )
        for m in messages
    ]
    with tracer.start_as_current_span("process_order_batch", links=links):
        for m in messages:
            process_order(m.body)

Sampling strategies

from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.sampling import (
    TraceIdRatioBased,
    ParentBased,
    ALWAYS_OFF,
)

# Keep 10% of traces; a parent-based wrapper honors the upstream decision
sampler = ParentBased(root=TraceIdRatioBased(0.1))
provider = TracerProvider(sampler=sampler)
trace.set_tracer_provider(provider)

For tail sampling — deciding after the whole trace is collected — the decision lives in the collector, not the SDK. This fragment goes under processors in the collector config:

# Inside the collector's processors section — holds traces briefly, then decides
processors:
  tail_sampling:
    decision_wait: 10s
    policies:
      - name: keep-errors
        type: status_code
        status_code: { status_codes: [ERROR] }
      - name: keep-slow
        type: latency
        latency: { threshold_ms: 500 }

Java Spring Boot instrumentation

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.StatusCode;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    private final Tracer tracer;

    public OrderService(Tracer tracer) {
        this.tracer = tracer;
    }

    public void processOrder(String orderId) {
        Span span = tracer.spanBuilder("process_order").startSpan();
        try (var scope = span.makeCurrent()) {
            span.setAttribute("order.id", orderId);
            chargePayment(orderId);
            updateInventory(orderId);
        } catch (Exception e) {
            span.recordException(e);
            span.setStatus(StatusCode.ERROR);
            throw e;
        } finally {
            span.end();
        }
    }
}

OpenTelemetry Collector configuration

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

processors:
  batch:
    timeout: 5s

exporters:
  otlp/jaeger:
    endpoint: jaeger:4317
    tls:
      insecure: true
  zipkin:
    endpoint: http://zipkin:9411/api/v2/spans
  otlp/tempo:
    endpoint: tempo:4317
    tls:
      insecure: true

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp/jaeger, zipkin, otlp/tempo]

The dedicated jaeger exporter no longer exists — it was removed from the collector in v0.86.0. Jaeger (≥1.35) accepts OTLP directly, so spans go over otlp/jaeger on port 4317 like any other backend.

Explanation

What the headers actually carry

A traceparent header looks like 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01: a version byte, the 32-hex-digit trace ID, the 16-hex-digit parent span ID, and flags (the 01 marks the trace as sampled). tracestate is an optional companion header where vendors stash their own data. The receiving service extracts these, starts its span as a child of the incoming parent ID, and injects the updated context — same trace ID, its own span ID as the new parent — into every outgoing call. That chain of parent pointers is what rebuilds the tree in the backend.

sequenceDiagram diagram: participant C as Client

Consequences and trade-offs

The upside: root-cause analysis stops being guesswork. Instead of grep-ing five log streams for timestamps, you open one trace and see the request’s full path — which service was slow, which span errored, and what each step was waiting on. Trace-derived metrics (latency per operation, error rate per service, dependency graphs) come almost for free once spans flow.

The costs are real:

  • Instrumentation effort: auto-instrumentation covers HTTP and common libraries, but messaging, custom protocols, and hand-rolled HTTP clients need manual inject/extract code — and every uninstrumented hop silently splits the tree.
  • Runtime and storage overhead: each span costs microseconds to create and bytes to export. At high throughput, naive always-on sampling can make the tracing bill rival the app’s compute bill — which is why sampling strategy matters.
  • High-cardinality attributes: span attributes get indexed by the backend. order.id with millions of distinct values is expensive to store and query; keep attributes to dimensions you will actually filter on, and put high-volume detail in span events instead.
  • PII leakage: attributes are exported verbatim. user.email in a span is user.email in your tracing backend — scrub or hash identifiers where policy requires it.

W3C Trace Context vs B3

Two propagation formats are in the wild. W3C Trace Context (traceparent/tracestate) is the standard and the OTel default. B3 (X-B3-TraceId, X-B3-SpanId, X-B3-Sampled, or the single b3 header) comes from Zipkin and survives mostly in older services and some service meshes. If one service speaks W3C and the next speaks B3 without translation, the tree breaks at that boundary — either standardize on W3C everywhere or configure the collector/proxy to translate. Baggage is a third, separate mechanism: it propagates arbitrary key-value pairs (like tenant.id) alongside the trace context, and it rides on every hop, so keep it small.

Sampling: deciding what to keep

Head-based sampling decides at the start of the trace — the root span rolls the dice (e.g. TraceIdRatioBased(0.1) keeps 10%) and the sampled flag propagates downstream so every service honors it. It’s cheap and uniform, but it’s blind: a routine 10% keeps ten boring traces for every interesting error.

Tail-based sampling decides after the full trace is collected in the collector — you can keep every trace with an error or over a latency threshold and sample the rest. The catch: the collector must buffer all spans of a trace for the decision window (decision_wait), which costs memory and adds a hop of complexity. The common production setup is tail sampling in the collector when you run one, parent-based head sampling in the SDK when you don’t.

Variants

Trace context with gRPC

import grpc
from opentelemetry import trace, propagate
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

propagator = TraceContextTextMapPropagator()

def call_payment_grpc(order_id: str, amount: float):
    carrier = {}
    propagator.inject(carrier)

    metadata = [(k, v) for k, v in carrier.items()]
    channel = grpc.insecure_channel("payment-service:50051")
    stub = PaymentServiceStub(channel)

    response = stub.Charge(
        ChargeRequest(order_id=order_id, amount=amount),
        metadata=metadata,
    )
    return response

Custom span attributes for business context

with tracer.start_as_current_span("process_order") as span:
    span.set_attributes({
        "order.id": order_id,
        "customer.tier": customer.tier,
        "order.total": order.total,
        "order.region": customer.region,
    })

Best Practices

  • Start with auto-instrumentation for HTTP, database, and messaging libraries — it covers 80% of boundaries — then add manual spans only where business logic needs visibility.
  • Name spans after operations (process_order, charge_payment), not functions or generic handlers. The span name is the primary filter in every trace UI.
  • Attach business attributes you will actually query — customer.tier, order.region — and skip the rest. Each indexed attribute has a storage cost.
  • Propagate context at every boundary without exception. One uninstrumented hop splits the trace tree into two forests.
  • Record exceptions on the span (record_exception plus an ERROR status). A span that only reports “took 240 ms” doesn’t tell you why it failed.
  • Prefer tail sampling in production: keep all error and slow traces, sample the routine traffic. Fall back to parent-based head sampling at 1–10% when a collector isn’t in the path.

Common Mistakes

  • Forgetting the extract side. Injecting traceparent on the client but never calling propagate.extract in the consumer or middleware forks the trace into a new root. It’s the single most common cause of broken trees, and it happens most often at queue and cron boundaries.
  • Generic span names. handle_request on every endpoint makes the waterfall useless — name the operation, not the plumbing.
  • A span per function call. Hundreds of ten-microsecond spans bury the signal. One span per meaningful operation: a DB call, a remote call, a business step.
  • Caught-but-not-recorded errors. Catching an exception without record_exception leaves a green-looking trace behind a red response.
  • Sampling 100% in production. At scale, the tracing bill and storage outgrow the benefit — keep errors and outliers, sample the rest.

See Also

Frequently Asked Questions

What is a span?

A span is one timed operation inside a trace — a database call, an HTTP request, a function. It carries a name, start/end timestamps, key-value attributes, and events. Spans link into a tree through parent span IDs, which is what reconstructs the request's path across services.

Why does my trace show disconnected spans?

Almost always a propagation gap: some hop didn't forward traceparent, or the receiving side never extracted it — common with message queues, custom HTTP clients, and cron-triggered jobs. The downstream service then starts a new root span instead of joining the existing trace. Check every boundary for matching inject/extract pairs.

How is distributed tracing different from correlation IDs?

A correlation ID tags log lines so you can group them by request; a trace models the request as a tree of timed operations with causality, attributes, and status. Correlation IDs are the cheaper first step — tracing is what you add when you need to see where the time went, not just which logs belong together.

Can I use distributed tracing with message queues and cron jobs?

Yes — queues are a first-class boundary. The producer injects context into message headers and the consumer extracts it before starting its span, exactly like HTTP. Cron jobs have no incoming context, so they start a new root trace; if a cron triggers downstream work, propagate from there as usual.

What sampling rate should I use in production?

Start at 1–10% head sampling to keep costs predictable, or run tail sampling in the collector and keep 100% of error and slow traces while sampling healthy traffic harder. The right number depends on volume — the goal is enough traces to debug real issues, not every request that ever succeeded.

Which backend should I choose: Jaeger, Zipkin, or Tempo?

Jaeger is the most feature-complete OSS option and the usual default. Zipkin is older and simpler — fine for small setups, thin on analysis tooling. Grafana Tempo stores traces in cheap object storage and trades a dedicated trace DB for Grafana integration — attractive if you already run Grafana. All three accept OTLP, so the backend choice doesn't change your instrumentation.