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.
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:
X-Trace-ID).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.
X-Trace-ID and X-Parent-Span-ID, leading to orphaned spans.X-Parent-Span-ID to the current span’s ID instead of the incoming span’s ID.X-Trace-ID is used, but the consumer fails to extract it, spans are created without context.X-Trace-ID for every incoming request, but not propagate it through all internal calls. This creates multiple independent traces for a single logical request.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:
service.latency.p95: 95th percentile of request duration across all spans.service.errors.count: number of spans with error=true or error.message.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.
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:
trace_id and a parent_span_id pointing to the root request span.start_time is the beginning of the entire request.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.
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:
X-Trace-ID across all HTTP calls and message queues.CacheMiss, NotFound, InvalidInput, RateLimitExceeded.When a service fails, it may:
error.message and error.typeerror.retried when a retry loop is attemptederror.code for machine-readable failure codesA request fails with a NotFound error at the User Service, but the Order Service reports a Timeout error. The trace shows:
User Service span has error.type: NotFoundOrder Service span has error.type: Timeout, error.duration_ms: 1200The 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.
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:
X-Trace-ID, X-Span-ID, and X-Parent-Span-ID as message headers.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.
Combine distributed traces with logs to enrich observability.
Each log entry includes:
trace_idspan_idservice.namelevelA 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:
trace_id as a common key across logs, traces, and metrics.trace_id in the log database (e.g., Elasticsearch, Loki).span_id to every log entry in the service.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.
A service logs User saved to database, but the db.save span is missing from the trace. This often happens when:
db.save, but the span is started after the call.db.save span is created but not finished before the log entry is written.db.save span is created in a different service than the one logging.The result: a log entry appears in the trace but does not align with any span, making it difficult to correlate.
To fix:
log instrumentation).trace_id and span_id.Ensure consistent trace context across service boundaries.
Every service must:
The extraction process:
X-Trace-ID from headers or message fields.X-Span-ID and X-Parent-Span-ID.The injection process:
trace_id, span_id, and parent_span_id.X-Trace-ID, X-Span-ID, and X-Parent-Span-ID to outgoing request headers.A service may also inject additional context:
X-Trace-Sampled: true to signal that the trace is being sampled.X-Trace-Service: user-service to help identify the originating service.A typical service may:
X-Trace-Sampled flag, leading to un-sampled spans.X-Trace-ID but does not set X-Parent-Span-ID when calling another service.span_context headers, but not all services extract and inject them correctly. The result: traces are split across HTTP and gRPC boundaries, with no link between them.X-Trace-ID for every incoming request but fails to propagate it through all internal calls. This creates multiple independent traces for a single logical request.Trigger alerts based on distributed traces.
An alert condition might be:
error=true and duration_ms > 2000p95 latency > 1000ms for the past 5 minutesTimeout error in more than 10% of traces in the last hourA 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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy