Production-grade guide to distributed tracing design covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Distributed tracing is the practice of capturing the full lifecycle of a request as it flows across multiple services, databases, queues, and infrastructure layers. It matters when latency is a concern, when errors propagate across service boundaries, and when diagnosing issues in a microservices architecture—especially when a single user action triggers hundreds of operations across dozens of services.
To capture meaningful traces, services must instrument their code with spans that reflect real work. Each span represents a unit of work—typically a function call, HTTP request, or database query. The key is to define spans at the level of logical units, not just technical calls.
A typical HTTP request entry point should create a root span with metadata: trace_id, span_id, parent_span_id, service_name, operation_name, start_time, and duration. The span should be populated with attributes such as http.method, http.url, http.status_code, and http.user_agent.
In Go, a common pattern uses context.Context to propagate trace context. The opentracing.StartSpan function takes a context.Context and a span name, and returns a new span and a modified context:
func HandleRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) {
span, ctx := opentracing.StartSpanFromContext(ctx, "HandleRequest")
defer span.Finish()
span.SetTag("http.method", r.Method)
span.SetTag("http.url", r.URL.String())
// Process request body
body, _ := io.ReadAll(r.Body)
span.LogFields(
log.String("request.body.size", fmt.Sprintf("%d", len(body))),
log.Int("request.body.bytes", len(body)),
)
// Call downstream service
downstreamSpan, ctx := opentracing.StartSpanFromContext(ctx, "CallUserService")
defer downstreamSpan.Finish()
client := &http.Client{}
req, _ := http.NewRequestWithContext(ctx, "GET", "http://user-service/users/123", nil)
resp, err := client.Do(req)
if err != nil {
downstreamSpan.SetTag("error", true)
downstreamSpan.LogFields(log.String("error", err.Error()))
}
downstreamSpan.SetTag("http.status_code", resp.StatusCode)
}
Spans should be named using a consistent schema: ServiceName.OperationName. For example, PaymentService.ProcessPayment, OrderService.CreateOrder, or CacheLayer.GetFromRedis. The operation_name should reflect the business logic, not just the code.
When a service makes an HTTP request to another service, the trace context must be propagated so that spans can be stitched into a single trace. The standard is to use HTTP headers, typically traceparent and tracestate.
The traceparent header follows the W3C Trace Context specification:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e571f-1815432161128868-01
00 is the version.4bf92f3577b34da6a3ce929d0e0e571f is the trace_id.1815432161128868 is the span_id.01 is the trace_flags.The tracestate header carries additional vendor-specific metadata:
tracestate: ot=00-4bf92f3577b34da6a3ce929d0e0e571f-1815432161128868-01,jaeger=1234
When a service receives an HTTP request, it must extract the trace context from the headers and use it to create a new span that becomes part of the incoming trace.
In Node.js, using the opentracing and express libraries:
const express = require('express');
const opentracing = require('opentracing');
const { TraceContext } = require('w3c-trace-context');
const app = express();
const tracer = opentracing.globalTracer();
app.use((req, res, next) => {
const carrier = { get: (key) => req.headers[key.toLowerCase()] };
const spanContext = tracer.extract(opentracing.FORMAT_HTTP_HEADERS, carrier);
const span = tracer.startSpan('HTTP Request', {
childOf: spanContext,
tags: {
'http.method': req.method,
'http.url': req.originalUrl,
},
});
req.span = span;
res.on('finish', () => {
span.setTag('http.status_code', res.statusCode);
span.finish();
});
next();
});
Failure often occurs when the traceparent header is missing or malformed. A common mistake is using TraceContext without validating the traceparent string. The traceparent must be exactly 44 characters long (including the 00- prefix), and the trace_id and span_id must be 32-character hex strings.
With thousands of requests per second, collecting a trace for every request is expensive. Sampling is essential.
The most effective strategy is adaptive sampling based on request latency, error rates, and user importance. A trace should be sampled if:
The sampling decision is made at the edge service—typically a gateway or load balancer—before the request enters the application.
A simple sampling configuration in a YAML file:
sampling:
strategy: adaptive
adaptive:
min_latency: 100
error_rate_threshold: 0.05
trace_ratio: 0.1
sample_on_error: true
sample_on_latency: true
sample_on_user_segment:
premium: 0.5
default: 0.2
free: 0.1
When a request matches any of the conditions, it is marked for full tracing by setting a sampled flag on the root span and including a sampled field in the tracestate.
A well-designed trace should reflect the actual flow of work. Spans should be nested, not flat. The parent_span_id in each span links to the span that created it.
A typical trace might look like:
Trace ID: 4bf92f3577b34da6a3ce929d0e0e571f
└── Root Span: HandleRequest (HTTP)
├── CallUserService (HTTP)
│ ├── GetUserById (DB: PostgreSQL)
│ └── GetUserPreferences (Cache: Redis)
├── CallOrderService (HTTP)
│ ├── CreateOrder (DB: MySQL)
│ └── SendOrderConfirmation (Queue: Kafka)
└── CallPaymentService (HTTP)
├── ProcessPayment (DB: MongoDB)
└── ConfirmPayment (External API)
Each span includes a start_time (in nanoseconds since Unix epoch) and duration (also in nanoseconds). These two fields allow precise time alignment across services.
To improve readability, spans should include a duration field and use start_time to calculate duration during the span’s lifetime. The duration should be calculated as end_time - start_time, and end_time is set when the span finishes.
Spans should not only capture timing but also rich metadata. Common attributes include:
db.name, db.operation, db.statementmessage_bus.topic, message_bus.message_idrpc.service, rpc.methodcomponent, service.name, span.kindFor example, a database span might include:
{
"name": "Query Users",
"kind": "client",
"start_time": 1672531200000000000,
"duration": 145000000,
"attributes": {
"db.name": "user_db",
"db.operation": "SELECT",
"db.statement": "SELECT * FROM users WHERE id = $1",
"db.system": "postgresql",
"component": "database"
}
}
Spans should also log events using LogFields or Log calls. These are timestamped events within a span, useful for capturing internal steps.
In Python using OpenTelemetry:
from opentelemetry import trace
from opentelemetry.propagate import inject
tracer = trace.get_tracer(__name__)
def create_user(name: str):
with tracer.start_as_current_span("CreateUser") as span:
span.set_attribute("user.name", name)
span.add_event("Validating input")
if not name:
span.add_event("Input validation failed", {
"error": "name is required"
})
span.set_status(StatusCode.ERROR, "Name missing")
span.add_event("Saving to database")
db_result = db.execute("INSERT INTO users (name) VALUES (%s)", [name])
span.add_event("Database saved", {
"rows_affected": db_result.rowcount
})
span.add_event("Sending welcome email")
mailer.send_welcome_email(name)
Errors in distributed systems are not just exceptions—they are spans with error tags and structured logs.
An error should be marked on a span with error: true, and the error details should be added as attributes:
{
"error": true,
"error.type": "ValidationException",
"error.message": "User name cannot be empty",
"error.stack": "at create_user (user_service.py:45)\n at handle_request (gateway.py:12)",
"error.cause": "ValidationError"
}
When a span is marked as an error, the entire trace should be flagged as containing an error. The root span should have a error field and a error_message if the error propagated from a downstream service.
A common failure is setting error: true but not including error.message. Without the message, it’s hard to triage errors from a dashboard.
Spans should also include a timestamp field for each log entry. The timestamp is the Unix timestamp in nanoseconds.
Traces are stored in a backend system, such as a database or a time-series store. The trace data should be indexed on:
trace_idservice_nameoperation_namestart_timedurationattributes (for filtering)A typical query to find slow traces:
SELECT trace_id, service_name, operation_name, start_time, duration
FROM traces
WHERE duration > 100000000 -- 100ms
AND service_name = 'PaymentService'
AND operation_name = 'ProcessPayment'
ORDER BY start_time DESC
LIMIT 50;
The trace data is often stored in a columnar format—Parquet, ORC, or Avro—optimized for columnar access and filtering.
traceparent header: The root span is created, but downstream services don’t join the trace. The trace appears as a flat list of spans with no hierarchy.parent_span_id: The parent_span_id is copied from the parent span but not updated when the service creates a new span. This causes spans to be misaligned.duration is set manually, but the start_time and end_time are not properly synchronized. A span may appear to take 50 ms, but its start_time is off by 20 ms.http.method vs http_method, db.name vs database_name, user.id vs userId. This makes filtering and aggregating traces difficult.error: true, but no error.message. Another service sets error.message, but not error.type. The error diagnosis becomes ad hoc.To ensure trace quality, engineers should write tests that validate the trace structure.
A test can validate that:
service_name and operation_name.trace_id, span_id, and parent_span_id.start_time of each span is less than or equal to the start_time of its parent.start_time of a span is less than or equal to the start_time of its children.duration of a span is positive and the end_time is start_time + duration.Such tests can be run in CI, ensuring that new instrumentation does not break the trace structure.
Service.Operation naming.traceparent and tracestate.These principles, when applied consistently, turn distributed tracing from a diagnostic luxury into a core observability practice.
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