Implementing Distributed Tracing

1. Understanding Distributed Tracing Concepts

ConceptDetail
TraceEnd-to-end request path across services
SpanSingle unit of work with start/end
Trace IDUnique per request (16 bytes / 32 hex)
Span IDUnique per span (8 bytes / 16 hex)
Parent Span IDBuilds tree
Context propagationW3C traceparent header

2. Generating Trace IDs

FormatDetail
W3Ctraceparent: 00-{trace-id}-{span-id}-{flags}
GenerationSDK assigns at edge if missing
EncodingLowercase hex
Length32 hex (trace), 16 hex (span)

3. Propagating Trace Context

HeaderUse
traceparentW3C ID + parent
tracestateVendor extensions
baggageCross-cutting key/values
B3 (Zipkin)X-B3-TraceId, X-B3-SpanId

4. Creating Spans

Example: OpenTelemetry (Java)

Tracer tracer = GlobalOpenTelemetry.getTracer("orders");
Span span = tracer.spanBuilder("processOrder")
    .setAttribute("order.id", id)
    .startSpan();
try (var scope = span.makeCurrent()) {
    chargePayment(id);
} catch (Exception e) {
    span.recordException(e);
    span.setStatus(StatusCode.ERROR);
    throw e;
} finally {
    span.end();
}
ElementDetail
NameOperation: HTTP GET /orders/{id}
KindSERVER, CLIENT, PRODUCER, CONSUMER, INTERNAL
StatusOK, ERROR, UNSET

5. Using Parent-Child Relationships

RelationDetail
Parent → ChildSynchronous nested call
Follows-fromAsync causation (queues)
Span linksConnect spans across traces (batches)

6. Adding Span Tags

ConventionExamples
HTTPhttp.method, http.status_code, url.full
DBdb.system, db.statement
Messagingmessaging.system, messaging.destination
Customorder.id, tenant.id
SpecOpenTelemetry Semantic Conventions

7. Adding Span Logs

ElementDetail
Span eventTime-stamped record on a span
recordExceptionCaptures stack as event
UseMark stages within a span without new span

8. Implementing Sampling Strategies

StrategyDetail
Head-based (probabilistic)Decide at root; e.g. 1%
Rate-limitingN traces/sec per service
Tail-basedDecide after seeing whole trace (errors, slow)
AdaptiveAdjust based on volume
TipAlways sample errors + slow traces

9. Correlating Traces Across Services

MechanismDetail
Auto-instrumentationSDK injects/extracts headers
AsyncInject context into message headers
Cron / batchNew trace per run; link to parent

10. Analyzing Trace Data

InsightHow
Latency hotspotsCritical path analysis
Error originFailing span at deepest level
Service mapAuto-derived from traces
High-cardinality queryFilter by tag (user, tenant)

11. Implementing Error Tracing

PracticeDetail
Status ERRORMark on exception
recordExceptionStack trace as event
Force-sampleAlways keep error traces
Link to logstraceId in log lines

12. Using Tracing Tools

ToolNotes
OpenTelemetryVendor-neutral SDK + collector (standard)
JaegerOSS backend
TempoGrafana, object-storage backed
ZipkinOSS, B3 origin
Datadog / Honeycomb / New Relic / LightstepManaged APM