Distributed tracing in Spring Boot

When one user request passes through five services, a log line in one of them tells you little. Distributed tracing gives the whole request one ID, carries it across every call and records how long each step took. This page explains how that works in Spring Boot 4, which replaced Spring Cloud Sleuth with Micrometer Tracing and OpenTelemetry, and runs two services that trace a request between them.

Contents

How distributed tracing works

A trace is the record of one request as it moves through a system. It is made of spans: one span per unit of work, such as handling an HTTP request, calling another service or running a database query. Every span has a start time, a duration, a name, attributes such as the URL or the status code, and the ID of its parent span. Together the spans form a tree that shows where the time went and where an error started.

Four mechanisms make it work across services:

  • Context propagation: when a service calls another, it adds the trace ID and its current span ID to the request, usually in the W3C traceparent header. The receiving service continues the same trace instead of starting a new one.
  • Instrumentation: Spring MVC, WebFlux, RestClient, WebClient, JDBC and messaging create spans automatically, through Micrometer's Observation API. Application code adds its own spans where the built-in ones are not enough.
  • Sampling: recording every span of every request is expensive, so the service that starts a trace decides whether to record it. The decision travels in the header, so a trace is recorded completely or not at all.
  • Export: finished spans are sent in batches, usually over the OTLP protocol to an OpenTelemetry Collector, which forwards them to a tracing backend such as Jaeger, Zipkin or Grafana Tempo.

The tracing support in Spring has changed twice, which explains the many outdated guides:

Tracing in Spring over the years
Spring BootLibraryNotes
2.xSpring Cloud SleuthIts own instrumentation; not supported on Spring Boot 3
3.xMicrometer Tracing, with a Brave or OpenTelemetry bridgeSleuth's core moved into Micrometer; configured through Actuator
4.xMicrometer Tracing with OpenTelemetry, via spring-boot-starter-opentelemetryOne starter for traces, metrics and logs over OTLP

So a "Spring Cloud tracing" setup today needs no Spring Cloud dependency at all. All programs on this page run with Spring Boot 4.1, Micrometer Tracing 1.7 and the OpenTelemetry SDK 1.62; the exemplar example adds Micrometer's Prometheus registry 1.17. Instead of sending spans to a backend, each program registers a small SpanExporter bean that keeps them in memory and prints them, so the output shows exactly what a backend would receive. Trace IDs are random, so the programs print facts about them, such as their length or whether two match, rather than the IDs themselves.

Setting up tracing in Spring Boot 4

One starter brings Micrometer Tracing, the OpenTelemetry bridge and SDK, and the OTLP exporters:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-opentelemetry</artifactId>
</dependency>
YAML
spring:
  application:
    name: checkout                       # becomes the service.name of every span
management:
  tracing:
    sampling:
      probability: 0.1                   # the default: record 10% of traces
  opentelemetry:
    tracing:
      export:
        otlp:
          endpoint: http://otel-collector:4318/v1/traces

Spans are exported over OTLP only when an endpoint is configured; without one, tracing still runs and trace IDs still appear in logs. The same starter also exports metrics over OTLP, to http://localhost:4318/v1/metrics by default. The programs set management.otlp.metrics.export.enabled=false, because without a collector every shutdown logs a connection error. Spring Boot 4.0 moved the trace export settings under management.opentelemetry.tracing.export, and the Spring Boot 3 names under management.otlp.tracing are no longer supported, so check them when upgrading.

Following a request across two services

A checkout service calls a stock service, the smallest system in which tracing pays off. Both run as separate Spring Boot applications in one program, each with its own embedded Tomcat:

Java
package demo.tracing.propagation;

import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

public class TracePropagation {

    // collects finished spans in memory instead of sending them to a tracing backend
    static final List<SpanData> SPANS = new CopyOnWriteArrayList<>();

    static class MemoryExporter implements SpanExporter {
        @Override
        public CompletableResultCode export(Collection<SpanData> spans) {
            SPANS.addAll(spans);
            return CompletableResultCode.ofSuccess();
        }

        @Override
        public CompletableResultCode flush() {
            return CompletableResultCode.ofSuccess();
        }

        @Override
        public CompletableResultCode shutdown() {
            return CompletableResultCode.ofSuccess();
        }
    }

    static final Map<String, String> SEEN = new ConcurrentHashMap<>();

    // ---- backend: the stock service ----

    @RestController
    static class StockController {
        @GetMapping("/stock")
        String stock(@RequestHeader("traceparent") String traceparent) {
            SEEN.put("backend traceparent", traceparent);
            SEEN.put("backend traceId", MDC.get("traceId"));
            return "7 in stock";
        }
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(StockController.class)
    static class StockService {
        @Bean
        SpanExporter memoryExporter() {
            return new MemoryExporter();
        }
    }

    // ---- frontend: the checkout service, which calls the stock service ----

    @RestController
    static class CheckoutController {
        private final RestClient stock;

        CheckoutController(RestClient.Builder builder,
                Environment env) {
            this.stock = builder.baseUrl(env.getProperty("stock.url")).build();
        }

        @GetMapping("/checkout")
        String checkout() {
            SEEN.put("frontend traceId", MDC.get("traceId"));
            return "checkout ok, " + stock.get().uri("/stock").retrieve().body(String.class);
        }
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(CheckoutController.class)
    static class CheckoutService {
        @Bean
        SpanExporter memoryExporter() {
            return new MemoryExporter();
        }
    }

    static int port(Object context) {
        return ((WebServerApplicationContext) context).getWebServer().getPort();
    }

    public static void main(String[] args) {
        String[] common = {"--spring.main.banner-mode=off", "--logging.level.root=WARN",
                "--server.port=0", "--management.tracing.sampling.probability=1.0",
                "--management.otlp.metrics.export.enabled=false"};
        try (var backend = SpringApplication.run(StockService.class,
                    concat(common, "--spring.application.name=stock"));
             var frontend = SpringApplication.run(CheckoutService.class,
                    concat(common, "--spring.application.name=checkout",
                            "--stock.url=http://localhost:" + port(backend)))) {
            String answer = RestClient.create().get()
                    .uri("http://localhost:" + port(frontend) + "/checkout")
                    .retrieve().body(String.class);
            System.out.println("Response: " + answer);
        }   // closing the contexts flushes the span processors

        String traceparent = SEEN.get("backend traceparent");
        String[] parts = traceparent.split("-");
        System.out.println("traceparent header seen by the stock service:");
        System.out.println("  version " + parts[0] + ", trace id of " + parts[1].length()
                + " hex digits, parent span id of " + parts[2].length()
                + " hex digits, flags " + parts[3]);
        System.out.println("Same trace id in both services' MDC: "
                + SEEN.get("frontend traceId").equals(SEEN.get("backend traceId"))
                + ", and in the header: " + parts[1].equals(SEEN.get("backend traceId")));

        Map<String, SpanData> byId = SPANS.stream()
                .collect(Collectors.toMap(SpanData::getSpanId, s -> s));
        List<SpanData> ordered = new ArrayList<>(SPANS);
        ordered.sort(Comparator.comparingLong(SpanData::getStartEpochNanos));
        System.out.println("Spans exported (" + ordered.size() + "), in start order:");
        for (SpanData span : ordered) {
            SpanData parent = byId.get(span.getParentSpanId());
            System.out.printf("  %-8s %-24s service=%-8s parent=%s%n", span.getKind(),
                    span.getName(), span.getResource().getAttributes().asMap().entrySet()
                            .stream().filter(e -> e.getKey().getKey().equals("service.name"))
                            .map(e -> e.getValue().toString()).findFirst().orElse("?"),
                    parent == null ? "(none: root span)" : parent.getName());
        }
        System.out.println("All spans share one trace id: "
                + (SPANS.stream().map(SpanData::getTraceId).distinct().count() == 1));
    }

    static String[] concat(String[] base, String... more) {
        String[] all = Arrays.copyOf(base, base.length + more.length);
        System.arraycopy(more, 0, all, base.length, more.length);
        return all;
    }
}
Output
Response: checkout ok, 7 in stock
traceparent header seen by the stock service:
  version 00, trace id of 32 hex digits, parent span id of 16 hex digits, flags 03
Same trace id in both services' MDC: true, and in the header: true
Spans exported (3), in start order:
  SERVER   http get /checkout       service=checkout parent=(none: root span)
  CLIENT   http get                 service=checkout parent=http get /checkout
  SERVER   http get /stock          service=stock    parent=http get
All spans share one trace id: true
  • The traceparent header that arrived at the stock service had the W3C format: version 00, a 32-digit trace ID, the 16-digit ID of the calling span, and flags. The flags 03 are two bits: 01, sampled, and 02, which W3C Trace Context Level 2 defines as "the trace ID is random".
  • Both services had the same trace ID in their logging MDC, and it equalled the one in the header. Every log line written while handling the request, in either service, can therefore be found by that one ID.
  • Three spans were exported. The checkout service's SERVER span for GET /checkout is the root. Its child is the CLIENT span of the RestClient call, and that span's child is the stock service's SERVER span, in another application. The tree crosses the service boundary because of the header.
  • Each span carries the service.name taken from spring.application.name, which is how a tracing backend shows which service did what.

The client span exists only because the checkout service built its RestClient from the auto-configured RestClient.Builder, which Spring Boot instruments. The program's own first request, made with RestClient.create(), has no client span and sends no traceparent, which is why the trace starts at the checkout service. A client created with new or create() inside a service silently breaks the trace at that point.

Sampling and baggage

Sampling decides what is recorded, and baggage carries extra values along with the trace. This program sets the tenant as baggage in one endpoint, calls a second endpoint, and runs once with every trace sampled and once with none:

Java
package demo.tracing.sampling;

import io.micrometer.tracing.BaggageInScope;
import io.micrometer.tracing.Tracer;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

public class SamplingAndBaggage {

    static final List<SpanData> SPANS = new CopyOnWriteArrayList<>();
    static final Map<String, String> SEEN = new ConcurrentHashMap<>();

    @SpringBootApplication
    static class ShopApplication {
        @Bean
        SpanExporter memoryExporter() {
            return new SpanExporter() {
                @Override
                public CompletableResultCode export(Collection<SpanData> spans) {
                    SPANS.addAll(spans);
                    return CompletableResultCode.ofSuccess();
                }

                @Override
                public CompletableResultCode flush() {
                    return CompletableResultCode.ofSuccess();
                }

                @Override
                public CompletableResultCode shutdown() {
                    return CompletableResultCode.ofSuccess();
                }
            };
        }
    }

    @RestController
    static class ShopController {
        private final RestClient self;
        private final Tracer tracer;
        private final Environment env;

        ShopController(RestClient.Builder builder, Tracer tracer, Environment env) {
            this.self = builder.build();
            this.tracer = tracer;
            this.env = env;
        }

        @GetMapping("/front")
        String front() {
            // set baggage here; it travels with every downstream call of this trace
            try (BaggageInScope tenant = tracer.createBaggageInScope("tenant", "eu-1")) {
                SEEN.put("tenant set at /front", tenant.get());
                return self.get().uri("http://localhost:{port}/back",
                        env.getProperty("local.server.port")).retrieve().body(String.class);
            }
        }

        @GetMapping("/back")
        String back(@RequestHeader("traceparent") String traceparent,
                @RequestHeader(name = "tenant", required = false) String tenantHeader) {
            SEEN.put("flags", traceparent.substring(traceparent.lastIndexOf('-') + 1));
            SEEN.put("tenant header", String.valueOf(tenantHeader));
            SEEN.put("tenant in MDC", String.valueOf(MDC.get("tenant")));
            SEEN.put("traceId in MDC", MDC.get("traceId") == null ? "no" : "yes");
            return "ok";
        }
    }

    static void run(String probability) {
        SPANS.clear();
        SEEN.clear();
        try (var context = SpringApplication.run(ShopApplication.class,
                "--spring.main.banner-mode=off", "--logging.level.root=WARN", "--server.port=0",
                "--management.otlp.metrics.export.enabled=false",
                "--management.tracing.sampling.probability=" + probability,
                "--management.tracing.baggage.remote-fields=tenant",
                "--management.tracing.baggage.correlation.fields=tenant")) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            RestClient.create().get().uri("http://localhost:" + port + "/front")
                    .retrieve().body(String.class);
        }
        System.out.println("sampling probability " + probability + ":");
        System.out.println("  traceparent flags at /back: " + SEEN.get("flags")
                + ", trace id in MDC: " + SEEN.get("traceId in MDC"));
        System.out.println("  tenant header: " + SEEN.get("tenant header")
                + ", tenant in MDC: " + SEEN.get("tenant in MDC"));
        System.out.println("  spans exported: " + SPANS.size());
    }

    public static void main(String[] args) {
        run("1.0");
        run("0.0");
    }
}
Output
sampling probability 1.0:
  traceparent flags at /back: 03, trace id in MDC: yes
  tenant header: eu-1, tenant in MDC: eu-1
  spans exported: 3
sampling probability 0.0:
  traceparent flags at /back: 02, trace id in MDC: yes
  tenant header: eu-1, tenant in MDC: eu-1
  spans exported: 0
  • With probability 1.0, the flags were 03, sampled, and three spans were exported: the two server spans and the client span between them.
  • With probability 0.0, the flags were 02: the sampled bit was off, and no span at all was exported. The trace ID was still created, propagated and put into the MDC, so log correlation works for every request, sampled or not.
  • In both runs, the baggage value eu-1 arrived at the second endpoint in a tenant header, because management.tracing.baggage.remote-fields lists it, and was in the MDC there, because correlation.fields lists it too.

Spring Boot's default probability is 0.1, so in a fresh application nine requests out of ten are not recorded. That surprises everyone the first time they look for a trace in a test environment; set 1.0 outside production. In production, a collector with tail-based sampling can keep every trace that contains an error while dropping most successful ones, a decision a service cannot make at the start of a request.

Baggage is sent with every downstream call, so keep it small and never put secrets in it: every service, and any third party you call, receives it.

Custom spans with the Observation API

Automatic instrumentation covers the edges of a service: HTTP in and out, database calls, messages. Important internal steps, such as pricing an order, need their own span. Micrometer's Observation API creates one, and a timer metric from the same code:

Java
package demo.tracing.observation;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

public class CustomObservation {

    static final List<SpanData> SPANS = new CopyOnWriteArrayList<>();

    @SpringBootApplication
    static class ShopApplication {
        @Bean
        SpanExporter memoryExporter() {
            return new SpanExporter() {
                @Override
                public CompletableResultCode export(Collection<SpanData> spans) {
                    SPANS.addAll(spans);
                    return CompletableResultCode.ofSuccess();
                }

                @Override
                public CompletableResultCode flush() {
                    return CompletableResultCode.ofSuccess();
                }

                @Override
                public CompletableResultCode shutdown() {
                    return CompletableResultCode.ofSuccess();
                }
            };
        }
    }

    @Service
    static class PricingService {
        private final ObservationRegistry registry;

        PricingService(ObservationRegistry registry) {
            this.registry = registry;
        }

        String price(String sku, String tier) {
            // one observation gives a span AND a timer metric
            return Observation.createNotStarted("shop.price", registry)
                    .contextualName("price " + sku)
                    .lowCardinalityKeyValue("tier", tier)        // span attribute + metric tag
                    .highCardinalityKeyValue("sku", sku)         // span attribute only
                    .observe(() -> {
                        if (sku.isBlank()) {
                            throw new IllegalArgumentException("no sku");
                        }
                        return sku + " costs 12.50";
                    });
        }
    }

    public static void main(String[] args) {
        try (var context = SpringApplication.run(ShopApplication.class,
                "--spring.main.banner-mode=off", "--logging.level.root=WARN",
                "--spring.main.web-application-type=none",
                "--management.otlp.metrics.export.enabled=false",
                "--management.tracing.sampling.probability=1.0")) {
            PricingService pricing = context.getBean(PricingService.class);
            pricing.price("book", "gold");
            pricing.price("pen", "gold");
            try {
                pricing.price(" ", "basic");
            } catch (IllegalArgumentException e) {
                System.out.println("third call failed: " + e.getMessage());
            }

            MeterRegistry meters = context.getBean(MeterRegistry.class);
            for (Timer timer : meters.find("shop.price").timers()) {
                System.out.println("timer shop.price " + timer.getId().getTags()
                        + " count=" + timer.count());
            }
        }
        System.out.println("spans:");
        for (SpanData span : SPANS) {
            System.out.println("  " + span.getName() + " " + span.getAttributes().asMap()
                    .entrySet().stream()
                    .filter(e -> !e.getKey().getKey().startsWith("thread"))
                    .map(e -> e.getKey().getKey() + "=" + e.getValue())
                    .sorted().toList()
                    + " status=" + span.getStatus().getStatusCode());
        }
    }
}
Output
third call failed: no sku
timer shop.price [tag(error=IllegalArgumentException), tag(tier=basic)] count=1
timer shop.price [tag(error=none), tag(tier=gold)] count=2
spans:
  price book [sku=book, tier=gold] status=OK
  price pen [sku=pen, tier=gold] status=OK
  price   [sku= , tier=basic] status=ERROR
  • Each call produced a span named after its contextual name, price book, price pen and, for the blank SKU, price followed by a space. The third span has status ERROR, because observe recorded the exception before rethrowing it.
  • The same observations also produced timers named shop.price: two calls for tier=gold with error=none, and one for tier=basic with error=IllegalArgumentException.
  • tier, a low-cardinality key value, appears on both the spans and the timers. sku, a high-cardinality one, appears only on the spans. A metric tag with thousands of values creates thousands of time series, while a span attribute costs nothing extra.

With spring-boot-starter-aspectj on the classpath, annotating a method with @Observed(name = "shop.price") does the same without code, through a proxy, with the usual proxy limits for calls on this. When only a span is wanted, Micrometer's Tracer creates one directly, but an observation is usually better, since the metric comes for free.

Correlating logs with traces

As the programs show, the current traceId and spanId are in the SLF4J MDC while a request is handled. Spring Boot's default console log pattern already prints them: with tracing on the classpath, each line has a block with the application name and the trace and span IDs, which is empty for lines logged outside a request. To use your own pattern, include %X{traceId} and %X{spanId}:

YAML
logging:
  pattern:
    correlation: "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] "

With structured JSON logging, enabled with logging.structured.format.console=ecs or logstash, the IDs become fields of their own. Log platforms can then link from a log line to its trace and back. The same starter can also export the logs themselves over OTLP, so traces, metrics and logs arrive at one collector.

Linking metrics to traces with exemplars

Metrics show that something is slow; a trace shows why. An exemplar connects the two: next to a metric value, the registry stores the trace and span ID of one request that contributed to it, so a dashboard can jump from a slow latency point to a trace that caused it. With micrometer-registry-prometheus and tracing on the classpath, Spring Boot adds exemplars to the Prometheus endpoint by itself. This program serves three requests, each returning its own trace ID, and then reads /actuator/prometheus in both formats Prometheus understands:

Java
package demo.tracing.exemplars;

import io.micrometer.tracing.Tracer;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

public class MetricExemplars {

    @RestController
    static class PriceController {
        private final Tracer tracer;

        PriceController(Tracer tracer) {
            this.tracer = tracer;
        }

        @GetMapping("/price")
        String price() {
            return tracer.currentSpan().context().traceId();     // returned for the demo
        }
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(PriceController.class)
    static class ShopApplication {
    }

    public static void main(String[] args) {
        try (var context = SpringApplication.run(ShopApplication.class,
                "--server.port=0", "--spring.main.banner-mode=off",
                "--logging.level.root=WARN",
                "--management.otlp.metrics.export.enabled=false",
                "--management.tracing.sampling.probability=1.0",
                "--management.endpoints.web.exposure.include=prometheus")) {
            RestClient client = RestClient.create("http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port"));
            List<String> traceIds = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                traceIds.add(client.get().uri("/price").retrieve().body(String.class));
            }

            for (String format : new String[] {"text/plain",
                    "application/openmetrics-text; version=1.0.0"}) {
                System.out.println("Accept: " + format);
                String scrape = client.get().uri("/actuator/prometheus")
                        .header("Accept", format).retrieve().body(String.class);
                scrape.lines()
                        .filter(line -> line.startsWith("http_server_requests_seconds_count"))
                        .filter(line -> line.contains("uri=\"/price\""))
                        .forEach(line -> System.out.println("  " + label(line, traceIds)));
            }
        }
    }

    // trace IDs change on every run: check which request the exemplar belongs to
    static String label(String line, List<String> traceIds) {
        int hash = line.indexOf(" # {");
        if (hash < 0) {
            return line;
        }
        String exemplar = line.substring(hash);
        boolean known = traceIds.stream()
                .anyMatch(id -> exemplar.contains("trace_id=\"" + id + "\""));
        return line.substring(0, hash) + "\n      # exemplar: span_id and trace_id"
                + (known ? " of one of the 3 requests" : " of an unknown request");
    }
}
Output
Accept: text/plain
  http_server_requests_seconds_count{error="none",exception="none",method="GET",outcome="SUCCESS",status="200",uri="/price"} 3
Accept: application/openmetrics-text; version=1.0.0
  http_server_requests_seconds_count{error="none",exception="none",method="GET",outcome="SUCCESS",status="200",uri="/price"} 3
      # exemplar: span_id and trace_id of one of the 3 requests
  • The timer http_server_requests_seconds counted the 3 requests to /price, with the low-cardinality tags method, status, outcome and uri. The trace ID is not a tag: as a tag, every request would create a new time series.
  • In the classic text format, requested with Accept: text/plain, the line ended after the value. That format has no place for exemplars.
  • In the OpenMetrics format, the same line carried an exemplar after #, with a span_id and a trace_id, and the trace ID was one of those the three requests returned. The program prints a description instead of the IDs, which change on every run.
  • One exemplar stood for all three requests. The registry keeps a sample of requests, not every one, which is enough to find a representative trace for a point on a graph.

Two trial runs of the same program with one setting changed showed the limits. With management.tracing.sampling.probability=0.0, the scrape had no exemplars at all: they come only from sampled spans, so with a low probability most metric points have none. With management.metrics.distribution.percentiles-histogram.http.server.requests=true, the exemplar appeared on a histogram bucket line, so a slow bucket can point to a slow trace. Prometheus asks for the OpenMetrics format by itself, but it stores exemplars only when started with --enable-feature=exemplar-storage.

Traps that break traces

  • Other threads: the trace context lives in thread-local state. Work handed to a plain ExecutorService or new Thread starts without it. Use executors from Spring Boot, which wraps its task executors with context propagation, or wrap your own with ContextExecutorService.wrap from the context-propagation library.
  • Uninstrumented clients: as the first program shows, only clients built from Spring Boot's builders propagate the context. The same applies to WebClient.Builder and to Kafka and RabbitMQ templates created by hand.
  • Messaging: Kafka and RabbitMQ propagate the trace in message headers only when observation is enabled on the template and the listener container, for example with spring.kafka.template.observation-enabled=true.
  • Proxies and gateways that drop headers: a load balancer or gateway that does not forward traceparent starts a new trace at every hop. Check the first span of each service in the backend.
  • Mixed formats: Spring Boot produces W3C headers and accepts W3C and B3. A service that only understands B3 needs management.tracing.propagation.produce to include B3 during a migration.

Choosing a tracing setup

Tracing choices in Spring Boot 4
NeedChoice
Tracing in a new Spring Boot 4 servicespring-boot-starter-opentelemetry and an OTLP endpoint
An application still on Spring Cloud SleuthUpgrade to Micrometer Tracing as part of the Spring Boot 3 or 4 upgrade
A step inside a service shown as a span, with a metricObservation, or @Observed with the AspectJ starter
Find all logs of one requestThe trace ID in the MDC, printed by the default log pattern
A value every service must see, such as a tenantBaggage with remote-fields and correlation.fields
Control the cost of recordingmanagement.tracing.sampling.probability, plus tail sampling in a collector
Send traces to Jaeger, Zipkin, Tempo or a vendorAn OpenTelemetry Collector between the services and the backend

Start by setting the application name and a sampling probability, make sure every outgoing client comes from a Spring Boot builder, and check one trace end to end before relying on them. Metrics and health from the same Micrometer foundation are covered on the Actuator and observability pages, and the HTTP clients that carry the trace on the declarative clients page.