Observability: logs, metrics and traces

Mid-level Frequently asked 6 min

On this page

The question

What is distributed tracing, and how does it work?

30-second answer

Distributed tracing follows one request across every service it touches. The first service creates a trace ID; each service records a span, a timed unit of work with its parent span's ID, and passes the trace context on, in an HTTP header such as W3C traceparent or a message header. Spans are exported to a backend, which joins them by trace ID into a waterfall showing where time went and what failed.

Understand it

One trace across four services

Step by step

A request with no trace context reaches the gateway. It starts a trace, ID 4bf92f35, and its own span, a1, the root.

Step 1 of 6
View as text

Four services in a row: gateway, Orders, Payments and Shipping. A line under them shows what carries the trace context, and below, a waterfall chart grows one bar per span: a1 for the gateway, b2 for Orders, c3 for Payments and d4 for Shipping.

A request with no trace context reaches the gateway. It starts a trace, ID 4bf92f35, and its own span, a1, the root.

The gateway calls Orders and adds a traceparent header: the trace ID and its own span ID. Orders starts span b2, with a1 as its parent.

Orders calls Payments with the same trace ID and its own span ID. Every service adds a span; the trace ID never changes.

Orders publishes OrderPlaced with the trace context in a Kafka message header. Shipping consumes it later, and its span d4 joins the same trace.

Each service also writes the trace and span IDs into every log line. Searching the logs for 4bf92f35 returns this request's lines from all four services.

Each service exports its spans. The backend joins them by trace ID into a waterfall, and the slow part is plain: Payments takes 600 of the 700 ms.

Four services in a row: gateway, Orders, Payments and Shipping. A line under them shows what carries the trace context, and below, a waterfall chart grows one bar per span: a1 for the gateway, b2 for Orders, c3 for Payments and d4 for Shipping.

A request with no trace context reaches the gateway. It starts a trace, ID 4bf92f35, and its own span, a1, the root.

The gateway calls Orders and adds a traceparent header: the trace ID and its own span ID. Orders starts span b2, with a1 as its parent.

Orders calls Payments with the same trace ID and its own span ID. Every service adds a span; the trace ID never changes.

Orders publishes OrderPlaced with the trace context in a Kafka message header. Shipping consumes it later, and its span d4 joins the same trace.

Each service also writes the trace and span IDs into every log line. Searching the logs for 4bf92f35 returns this request's lines from all four services.

Each service exports its spans. The backend joins them by trace ID into a waterfall, and the slow part is plain: Payments takes 600 of the 700 ms.

Takeaway: A trace ID is created once and passed with every call, in an HTTP or message header. Each service adds a span naming its parent, so a backend draws the request as a waterfall, and logs join by trace ID.

Logs, metrics and traces

Tap the parts

Select a part to see what it does.

Tap a part of observability. The stripe on each row names its pillar: logs, metrics, traces, or what they share.

View as text

A legend names the three pillars, logs, metrics and traces, and what they share. Seven rows follow, each a part with a colored stripe for its pillar and two short lines.

Logs, logs: what happened, one event, in detail. A log line records one event with its details: an error and its stack trace, a rejected order and why.

JSON logs, logs: fields, not prose, traceId on every line. Structured logs write fields, such as orderId, status and traceId, so a log platform can filter and join them.

Metrics, metrics: how much, how often, cheap for years. Metrics are numbers over time: request counts, latency histograms, queue lag, heap used.

RED, metrics: rate, errors, duration, per endpoint. For every service, watch the request rate, the error rate and the duration, as percentiles such as p99 rather than the average.

Traces, traces: where the time went, across services. A trace follows one request through every service as a tree of spans, each with a start, a duration and attributes.

Sampling, traces: keep 10% of traces, or every error. Recording every trace is expensive at scale.

OpenTelemetry, shared: one standard, for all three. OpenTelemetry is the vendor-neutral standard: APIs, SDKs, a Java agent and the OTLP (OpenTelemetry Protocol) wire format for traces, metrics and logs.

A legend names the three pillars, logs, metrics and traces, and what they share. Seven rows follow, each a part with a colored stripe for its pillar and two short lines.

Logs, logs: what happened, one event, in detail. A log line records one event with its details: an error and its stack trace, a rejected order and why.

JSON logs, logs: fields, not prose, traceId on every line. Structured logs write fields, such as orderId, status and traceId, so a log platform can filter and join them.

Metrics, metrics: how much, how often, cheap for years. Metrics are numbers over time: request counts, latency histograms, queue lag, heap used.

RED, metrics: rate, errors, duration, per endpoint. For every service, watch the request rate, the error rate and the duration, as percentiles such as p99 rather than the average.

Traces, traces: where the time went, across services. A trace follows one request through every service as a tree of spans, each with a start, a duration and attributes.

Sampling, traces: keep 10% of traces, or every error. Recording every trace is expensive at scale.

OpenTelemetry, shared: one standard, for all three. OpenTelemetry is the vendor-neutral standard: APIs, SDKs, a Java agent and the OTLP (OpenTelemetry Protocol) wire format for traces, metrics and logs.

Takeaway: Metrics tell you that something is wrong, traces tell you where, and logs tell you why. A shared trace ID ties the three together, and OpenTelemetry gives them one standard.

From an alert to the cause, through the three pillarsA metric alert says the checkout error rate is up. A trace of a failing request shows which service fails. The logs of that service, found by the trace ID, show why.Metric alert:errors upTrace: whichhop failsLogs by trace ID:why it fails
From an alert to the cause, through the three pillarsA metric alert says the checkout error rate is up. A trace of a failing request shows which service fails. The logs of that service, found by the trace ID, show why.Metric alert:errors upTrace: whichhop failsLogs by trace ID:why it fails
From an alert to the cause, through the three pillars

In code

# needs micrometer-tracing-bridge-otel and opentelemetry-exporter-otlp
spring.application.name=orders
management.tracing.sampling.probability=0.1
management.otlp.tracing.endpoint=http://otel-collector:4318/v1/traces
# With tracing on, Boot adds traceId and spanId to the default log pattern; JSON logs carry them as fields
logging.structured.format.console=ecs
management.metrics.distribution.percentiles-histogram.http.server.requests=true
Spring Boot 3: traces over OTLP, IDs in every log line
@Service
class PaymentClient {
    private final ObservationRegistry registry;
    private final RestClient payments;

    PaymentClient(ObservationRegistry registry, RestClient.Builder builder) {
        this.registry = registry;
        this.payments = builder.baseUrl("http://payments").build();
    }

    Receipt charge(Order order) {
        return Observation.createNotStarted("payment.charge", registry)
            .lowCardinalityKeyValue("provider", "card")         // a tag on the metric and the span
            .highCardinalityKeyValue("order.id", order.id().toString())   // span only: too many values for a metric
            .observe(() -> payments.post().uri("/charges").body(order).retrieve().body(Receipt.class));
    }
}
A custom span and timer around a call, with the Observation API
// Wrong: not instrumented, so no traceparent header and the trace breaks at this hop
 Wrong RestClient payments = RestClient.create("http://payments");

// Right: built from Spring Boot's builder, which adds tracing and metrics
 Right RestClient payments = restClientBuilder.baseUrl("http://payments").build();
A client built by hand drops the trace context
Where the telemetry goesEach service sends traces, metrics and logs to an OpenTelemetry collector, or exposes metrics for scraping. The collector forwards traces to a tracing backend such as Tempo or Jaeger, metrics to Prometheus and logs to Loki, and Grafana shows all three, linked by trace ID.ServicesOpenTelemetrycollectorTraces: Tempoor JaegerMetrics:PrometheusLogs: LokiGrafana
Where the telemetry goesEach service sends traces, metrics and logs to an OpenTelemetry collector, or exposes metrics for scraping. The collector forwards traces to a tracing backend such as Tempo or Jaeger, metrics to Prometheus and logs to Loki, and Grafana shows all three, linked by trace ID.ServicesOpenTelemetrycollectorTraces: Tempoor JaegerMetrics:PrometheusLogs: LokiGrafana
Where the telemetry goes

Solve it

Checkout is slow for some users, and no one knows which service

The checkout endpoint’s p99 latency rose from 400 ms to 3 seconds after a release, but its average barely moved. Checkout calls Orders, Pricing, Inventory and Payments. Each team says its service is fine. Find the cause.

  1. Confirm the symptom with metrics. The gateway’s latency histogram shows the p99 jump; the average hides it because most requests are still fast. Note which endpoint and since when.
  2. Look at slow traces, not random ones. Filter traces of checkout by duration above 2 seconds, or follow an exemplar from the histogram to a trace.
  3. Read the waterfall. The slow traces show 40 short sequential spans to Pricing, one per cart item, each fast. Big carts make the request slow; no single service is slow.
  4. Confirm in the logs. Search the Orders logs by one slow trace’s ID: one pricing request per item, added in the release.
  5. Fix and check. Price the whole cart in one batch call. The trace shows one Pricing span, and the p99 histogram drops back.
// Before: 40 items, 40 sequential calls, about 40 x 60 ms
List<Price> prices = cart.items().stream()
    .map(item -> pricing.get().uri("/prices/{sku}", item.sku()).retrieve().body(Price.class))
    .toList();

// After: one call for the whole cart
List<Price> prices = pricing.post().uri("/prices:batch")
    .body(cart.items().stream().map(Item::sku).toList())
    .retrieve()
    .body(new ParameterizedTypeReference<List<Price>>() {});
The trace showed one call per item; one batch call replaces them

How to answer

  • Instrumentation is mostly automatic, through framework integrations or the OpenTelemetry Java agent.
  • Context must cross thread pools and async boundaries, or the trace breaks.
  • Sampling keeps cost under control; tail sampling keeps the errors and slow traces.
  • Put the trace ID in every log line to jump from a trace to its logs.

Common mistakes

  • Saying centralized logs alone show where a request was slow. Without a shared ID and timings per hop, you cannot rebuild one request's path.
  • Building a client by hand instead of from the framework's builder, which silently drops the trace context at that hop.

Follow-up questions

What are trace IDs and span IDs?

A trace ID identifies one whole request across all services: 16 random bytes, the same in every span of that request. A span ID identifies one operation within it, such as one HTTP call or one database query: 8 bytes, new for every span. Each span also stores its parent's span ID, which turns the spans into a tree. Both travel in the W3C traceparent header: version, trace ID, parent span ID and flags.

  • The flags say whether the trace is sampled, so all services make the same choice.
  • Baggage carries extra key-value pairs along the trace, such as a tenant ID.
  • Logs record both IDs, through the logging MDC (Mapped Diagnostic Context).

See it in the infographic: One trace across four services

What is a correlation ID, and how does it differ from a trace ID?

A correlation ID is any identifier passed along a request or a business flow so that related logs can be found together, often an X-Correlation-ID header set at the edge and logged everywhere. A trace ID is a standardized correlation ID that tracing systems manage, with spans and timings. Today the trace ID usually serves as the correlation ID; a business ID, such as an order ID, still helps to follow a flow across several requests.

  • A saga spanning hours covers many traces; an order ID ties them together.
  • Return the ID in error responses, so users can quote it to support.
  • Never trust an incoming ID blindly from outside; validate or replace it at the gateway.

See it in the infographic: Logs, metrics and traces

What is OpenTelemetry, and how does a Spring Boot service use it?

OpenTelemetry is the vendor-neutral standard for telemetry: APIs and SDKs (software development kits) to create traces, metrics and logs, automatic instrumentation for common libraries, the OTLP (OpenTelemetry Protocol) wire format, and a collector that receives, processes and forwards data to any backend. A Spring Boot 3 service uses Micrometer Observation with the OpenTelemetry bridge and an OTLP exporter, or runs the OpenTelemetry Java agent with no code changes.

  • It replaced OpenTracing and OpenCensus.
  • Backends such as Jaeger, Tempo, Datadog or New Relic all accept OTLP, so no lock-in.
  • The collector can sample, filter and enrich data before it is stored.

See it in the infographic: Logs, metrics and traces See it in the infographic: One trace across four services

How does the trace context get from one service to the next over Kafka?

The producer's instrumentation writes the trace context into the record's headers, as traceparent. The consumer's instrumentation reads it and starts its span as a child, or as a link, of the producer's span. Spring Kafka does this when observation is enabled on the template and the listener container.

Check yourself

1. A request passes through four services. Which identifier is the same in every service's span?
Show answers
  • The trace ID: Correct. One trace ID covers the whole request; every span carries it.
  • The span ID: Incorrect. Each operation gets a new span ID.
  • The parent span ID: Incorrect. It points to the caller's span, so it changes at every hop.
2. An alert says checkout errors doubled. Which signal shows which downstream service the failing requests stopped at?
Show answers
  • Traces of the failing requests: Correct. A trace shows the path and the failing span across services.
  • The error rate metric: Incorrect. Metrics show that errors rose, not where along the path they happen.
  • The gateway's logs alone: Incorrect. The gateway sees only its own part of the request.