Distributed Tracing Patterns

Comprehensive guide to distributed tracing patterns for production observability and monitoring systems.

Distributed tracing is the practice of following a request as it flows through multiple services in a microservices architecture. It matters when a single user action—like a payment checkout—requires coordination across databases, message queues, external APIs, and background workers. Without distributed tracing, diagnosing latency, failures, or mismatches becomes a guessing game.

Request Flow Visualization

Visualize the full lifecycle of a request from client to service, across network boundaries, using a single trace ID.

A trace is a tree of spans where the full path of a request is visible. The most common way to propagate trace context is via HTTP headers. A standard set of headers includes:

X-Trace-ID: 1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d
X-Span-ID: 5c6d7e8f-9a0b-1c2d-3e4f-5a6b7c8d9e0f
X-Parent-Span-ID: 1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d

The X-Trace-ID is shared across all spans in the same trace. X-Span-ID uniquely identifies the current span. X-Parent-Span-ID links the current span to its parent.

When a service makes an HTTP call to another service, it must:

  1. Extract the current trace context from incoming headers (e.g., X-Trace-ID).
  2. Create a new span for the outgoing call.
  3. Inject trace context into outgoing headers.
  4. Set the current span as the active span in the execution context.

Failure to correctly propagate X-Parent-Span-ID is a common source of broken traces. If a service forgets to set the parent ID when calling another service, spans appear as siblings instead of a hierarchical flow.

Common Failure Modes

Service-Level Latency Analysis

Identify bottlenecks within a single service by analyzing span duration, service boundaries, and internal operation breakdowns.

Each service should record spans for:

A span for a database query might include:

{
  "name": "db.query",
  "span_id": "a1b2c3d4",
  "trace_id": "1a2b3c4d",
  "start_time": 1712345678901234,
  "end_time": 1712345679150345,
  "attributes": {
    "db.system": "postgresql",
    "db.operation": "SELECT * FROM orders WHERE user_id = ?",
    "db.statement": "SELECT * FROM orders WHERE user_id = 12345",
    "db.rows": 47,
    "db.duration_ms": 249
  }
}

The db.duration_ms attribute is critical for identifying slow queries. Services often aggregate spans into metrics:

Spans can be annotated with events:

{
  "name": "db.query",
  "events": [
    {
      "name": "query.started",
      "timestamp": 1712345678901234
    },
    {
      "name": "query.rows.fetched",
      "timestamp": 1712345679000000,
      "attributes": {
        "rows": 23
      }
    },
    {
      "name": "query.completed",
      "timestamp": 1712345679150345
    }
  ]
}

Events help correlate internal steps with external observations.

Latency Surprise: Span Overlap and Parallelism

A service may make multiple parallel calls—e.g., fetching user profile, order history, and preferences in parallel. If spans are not properly nested, the overall request appears as a sequence of calls, not a parallel flow.

To represent parallelism, use span_id and parent_span_id correctly:

A common mistake is using the same span_id for all parallel calls, causing them to appear as nested sub-spans rather than siblings. This inflates the observed latency of the root request.

Another issue: a service calls two external APIs in parallel but only records the first call’s span, missing the second. The result is an undercount of work, leading to misdiagnosed latency.

Cross-Service Error Propagation

Trace a failure from the client all the way to the root cause, even when multiple services fail.

When a service fails, it sets:

{
  "error": true,
  "error.message": "Failed to fetch user from cache",
  "error.type": "CacheMiss",
  "error.stack": "at UserService.fetchUser(UserService.java:42)\nat UserController.getProfile(UserController.java:23)"
}

The error.type field is used to classify errors: Timeout, Validation, Database, Network.

A request is considered failed if any span in the trace has error=true, and the trace’s root span is marked as failed.

To correlate failures across services:

When a service fails, it may:

A request fails with a NotFound error at the User Service, but the Order Service reports a Timeout error. The trace shows:

The trace reveals that the User Service took 500ms and returned a 404 response, but the Order Service waited 1200ms and timed out. The root cause is not the User Service but the Order Service’s backend.

Silent Failure: Error Propagation in Message Queues

When a service consumes a message from a queue, it may fail to extract X-Trace-ID from the message body or headers. The result: all spans created in the consumer service appear as independent traces, even though they belong to the same logical flow.

To ensure error propagation:

Failure to set X-Parent-Span-ID when a message is consumed leads to a single span at the consumer level, without any internal breakdown.

Contextual Correlation with Logs

Combine distributed traces with logs to enrich observability.

Each log entry includes:

A typical log line might be:

{
  "timestamp": "2024-04-05T12:34:56.789Z",
  "level": "info",
  "service": "user-service",
  "trace_id": "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d",
  "span_id": "a1b2c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d",
  "message": "User profile fetched from cache",
  "user_id": 12345,
  "cache_hit": true
}

When a trace is visualized, each span can be linked to its corresponding log entries. A span with name: db.query might show all log lines produced during that query.

To correlate logs and traces:

A trace with a slow span may show a log entry with message: "Query took 300ms" and duration_ms: 312, but the log does not capture the full execution context. The span provides the timeline, the log provides the narrative.

Log-Trace Gap: When Span and Log Are Out of Sync

A service logs User saved to database, but the db.save span is missing from the trace. This often happens when:

The result: a log entry appears in the trace but does not align with any span, making it difficult to correlate.

To fix:

Distributed Context Propagation

Ensure consistent trace context across service boundaries.

Every service must:

The extraction process:

  1. Read X-Trace-ID from headers or message fields.
  2. Read X-Span-ID and X-Parent-Span-ID.
  3. Create a new span for the incoming request.
  4. Set the current span to the extracted span.

The injection process:

  1. Get the current span’s trace_id, span_id, and parent_span_id.
  2. Add X-Trace-ID, X-Span-ID, and X-Parent-Span-ID to outgoing request headers.

A service may also inject additional context:

A typical service may:

Common Pitfalls in Propagation

Trace-Based Alerting

Trigger alerts based on distributed traces.

An alert condition might be:

A trace-based alert can be defined using a query over trace data:

SELECT trace_id, root_span.duration_ms, root_span.error
FROM traces
WHERE root_span.duration_ms > 2000
  AND root_span.error = true
  AND root_span.service_name = 'checkout-service'
  AND timestamp BETWEEN now() - INTERVAL '5 minutes' AND now()
LIMIT 100

When such an alert fires, it provides:

An alert can be configured to:

A trace-based alert is more actionable than a metric alert: it shows *why* a service is slow, not just *that* it is slow.

This page was rewritten on 17 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.