How-To Guide

How to Implement Distributed Tracing

Trace a request across services: create spans, propagate the trace context, record useful attributes, and read the trace to find the slow hop.

On this page

  1. Introduction
  2. Create a span per significant operation
  3. Propagate the trace context on every call
  4. Record the attributes you will query
  5. Sample without losing the important traces
  6. Read the trace to find the slow hop
  7. Test the propagation and the attributes
  8. Common pitfalls
  9. Conclusion

Introduction

A request that crosses several services has a story the logs of each service tell only in fragments. A trace joins the fragments: it is a tree of spans, one per operation, with a start, an end, a parent, and attributes, so the whole request is one structure. When a request is slow, the trace shows which span dominated, which is the hop to fix. Tracing is the instrument that answers where the time went across service boundaries.

This tutorial covers creating spans, propagating the trace context, recording useful attributes, and reading a trace to find the slow hop. The examples follow OpenTelemetry, the standard that any tracing backend can consume.

Create a span per significant operation

A span is an operation with a start time, an end time, a parent, and attributes. Wrap each significant operation in a span: the incoming request, a database query, an outbound call, a cache lookup, and any internal step worth measuring. The span records the duration and the outcome, and its parent links it into the trace tree, so the whole request is one structure.

Start the span when the operation starts and end it when it ends, including on the error path, so a failed operation still has a span with the error recorded. Use an automatic instrumentation where the framework offers it, so the spans for HTTP, database, and client calls are created without hand-wrapping each, and add manual spans for the operations the instrumentation does not cover.

import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('orders');

async function loadOrder(id) {
  return tracer.startActiveSpan('loadOrder', async (span) => {
    try {
      span.setAttribute('order.id', id);
      const order = await db.query('SELECT ... WHERE id = $1', [id]);   // child span auto
      span.setAttribute('order.found', Boolean(order));
      return order;
    } catch (err) {
      span.recordException(err as Error);
      span.setStatus({ code: 2 });   // error
      throw err;
    } finally {
      span.end();   // end the span on success and on error
    }
  });
}

Propagate the trace context on every call

For the spans across services to join into one trace, the trace context must travel with the request. The caller injects the trace id and the current span id into the outgoing call, typically in a header, and the callee extracts them and makes its span a child. OpenTelemetry and the W3C Trace Context standard define the header format, so the propagation is interoperable.

Automatic instrumentation usually injects and extracts the context for HTTP and gRPC calls, so the propagation is handled. For a transport it does not cover, a message queue or a custom protocol, inject the context into the message and extract it on the consumer, so the trace continues across the queue. Without the propagation, each service’s spans form a separate trace and the whole request is not visible.

import { propagation, context } from '@opentelemetry/api';

// caller: inject the context into the outgoing headers
const headers = {};
propagation.inject(context.active(), headers);
await fetch('https://downstream/report', { headers });   // downstream joins the trace

// callee: extract on the incoming request, making its spans children of the caller's

Record the attributes you will query

A span is useful for the attributes it carries. Record the ones you query on: the route or the operation name, the status code, the downstream target and host, the entity id, and the outcome. These turn a span from a duration into an answer, so a trace shows not only where the time went but what the operation did and whether it succeeded.

Keep the attributes bounded in cardinality, because an attribute with unbounded values, such as a raw user id or a full URL with query, creates enormous cardinality in the backend. Prefer a bounded value, such as the route template rather than the concrete path, and the entity id only where you will query on it. High cardinality attributes make the trace backend slow and expensive.

span.setAttribute('http.route', '/orders/:id');    // template, bounded
span.setAttribute('http.status_code', res.status);
span.setAttribute('downstream.service', 'reporting');
// avoid: span.setAttribute('http.url', req.url);   // unbounded cardinality

Sample without losing the important traces

Tracing every request at full fidelity is expensive, so most systems sample. Head-based sampling decides at the start, so it is cheap and consistent across the trace but may miss a slow request. Tail-based sampling decides after the trace completes, so it can keep the slow ones and the errors, at the cost of buffering. Choose by what you need: keep all errors and slow requests, sample the rest.

Whatever the strategy, keep the sampling decision in the context so all services sample the same trace, or a partial trace forms. Record the sampling rate so a count derived from the traces can be scaled. The point is that a sampled trace is still complete for the requests it covers, and the slow and failing ones are not the ones dropped.

Read the trace to find the slow hop

To use a trace, follow the tree to the span whose duration dominates the parent. A request that took two seconds with a single query span of 1.9 seconds points at that query. The trace turns a slow request from a mystery into a named span, and the span’s attributes say what it was doing. This is the payoff: the time is attributed, not guessed.

Look for the span that both is long and has no long child, because a long span whose children are short is time spent in its own code, while a long span with a long child is waiting on the child. The deepest long span is where the time is actually spent. Read the spans across services to see the hop that dominated, which is where to optimize.

# a trace tree: the span whose duration dominates its parent is the slow hop
# HTTP GET /orders  2100ms
#   └─ loadOrder      2050ms
#       └─ db.query   2000ms   <- the hop to fix
# configure the backend to show the waterfall, and read the widest child

Test the propagation and the attributes

Test that a downstream call carries the trace context, by a stub that records the incoming header and asserting it holds a trace id and a span id. Test that a span records the attributes the trace is queried on, by a test exporter that captures the finished spans. Test that an error path still ends the span and records the error, so a failed operation is visible in the trace.

# with an in-memory exporter, assert the spans and their parent links
node -e '
// run a request that calls a downstream stub, then read the captured spans
// assert: one root span, the downstream span is its child, error spans have status 2
'

Common pitfalls

Not propagating the context so each service is a separate trace, spans not ended on the error path so a failed operation has no span, unbounded attribute cardinality that makes the backend expensive, head-based sampling that drops the slow traces, and reading only the root span so the slow child is missed are the recurring mistakes. Context propagation, ending spans on every path, bounded attributes, tail-based sampling for slow and error traces, and reading the tree address them.

Conclusion

Distributed tracing joins the operations of one request across services into a trace. Create a span per significant operation, propagate the trace context on every call, record the attributes you query, sample so the slow and error traces are kept, and read the tree to find the span that dominates. Self-check by asserting a downstream call carries the trace context and that the error spans end with the error recorded. Then a slow request names the hop to fix.

Sources: OpenTelemetry: Traces, W3C Trace Context, OpenTelemetry: Context propagation.

FAQ

How is tracing different from logging?
A log line is a point event with a message; a span is an interval with a start, an end, a parent, and attributes. A trace is the tree of spans for one request across services, which shows where the time went. Logs tell you what happened, traces tell you where it happened and for how long.
What is context propagation?
It is passing the trace and span id from the current span to a downstream call, so the downstream's span becomes a child of the caller's. Without it, each service's spans are separate traces and you cannot see the whole request.

Related Examples