Spring › Observability

Distributed tracing and context propagation in Spring Boot 4

Compare the Spring Boot 4 native OpenTelemetry starter with the Java Agent, covering W3C traceparent propagation, sampling, and async context loss.

Distributed tracing and context propagation in Spring Boot 4

Linking requests across two services into one trace means choosing between Spring Boot 4’s native OpenTelemetry starter and the Java Agent—and knowing where traceparent propagation silently breaks.

Environment: Spring Boot 4.0.1 (spring-boot-starter-opentelemetry), Kotlin 2.2, Java 21, OpenTelemetry Java Agent 2.24.0, homelab OTel Collector (https://otel.namju.kim, OTLP/HTTP), and Tempo.

Background

At work, we bake the OpenTelemetry Java Agent directly into our container images. Getting traces without touching application code is convenient, but that convenience hides how spans are created. Whenever a trace unexpectedly split into two disconnected traces after crossing an async boundary, tracking down where the context dropped took far longer than it should have.

Spring Boot 4.0 introduced an official spring-boot-starter-opentelemetry module maintained by the Spring team. To compare both approaches under identical conditions, I spun up two services—order-api and payment-api—in my homelab, running the native starter on one and the Java Agent on the other. In my previous note on structured logging and traceId correlation in Spring Boot, I covered attaching traceId to logs inside a single service. Here, I trace how that traceId crosses service and thread boundaries.

How context propagation works

Distributed tracing comes down to context propagation. The caller writes its active span context into outbound HTTP headers (inject), and the callee reads those headers to create a child span under the same trace (extract). The standard wire format is the W3C Trace Context traceparent header:

1
2
3
4
5
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             │  │                                │                └ trace-flags (01 = sampled)
             │  │                                └ parent span id (16 hex)
             │  └ trace id (32 hex)
             └ version
sequenceDiagram
    participant O as order-api
    participant P as payment-api
    participant C as "OTel Collector"
    O->>O: Start server span (new traceId)
    O->>P: POST /payments + traceparent
    P->>P: Extract header & start child span
    P-->>C: Export span batch (OTLP/HTTP)
    O-->>C: Export span batch (OTLP/HTTP)

In Spring Boot’s native setup, header injection happens through ObservationRestClientCustomizer, which Spring automatically attaches to the auto-configured RestClient.Builder bean. When a client built from that builder sends an HTTP request, Micrometer starts a client Observation, and PropagatingSenderTracingObservationHandler uses OpenTelemetry’s TextMapPropagator to write traceparent. That means if you bypass the builder and call RestClient.create() directly, no traceparent header is sent and the downstream service starts a brand-new trace. The Java Agent avoids this trap because it instruments the underlying HTTP client libraries via bytecode.

Sampling decisions travel in the last bit of trace-flags. With the native starter, the root service makes a single head-sampling decision using management.tracing.sampling.probability (default 0.1), and downstream services follow a parent-based sampler. Even if you set payment-api to sample 100% of traces, it won’t resurrect a trace that order-api already marked as unsampled (00).

Native starter vs. Java Agent

CriterionSpring Boot native (spring-boot-starter-opentelemetry)OTel Java Agent 2.x
Setup methodGradle dependency + application.yml-javaagent flag + environment variables
Instrumentation scopeComponents with Spring Observation support (MVC, RestClient, parts of JDBC)Broad bytecode instrumentation (JDBC, Redis, Kafka, HTTP clients)
Cross-thread propagationExplicit wiring required (TaskDecorator, etc.)Automatic via ExecutorService instrumentation
Custom spans & metricsUnified Micrometer Observation API (span + timer together)OpenTelemetry API and annotations
GraalVM native / AOTSupportedImpractical due to runtime bytecode manipulation
Version couplingManaged cleanly by the Spring Boot BOMLibrary versions must fall within the Agent’s supported matrix

My rule of thumb is straightforward. If I own the codebase and want to model domain operations with the Observation API—getting both spans and metrics from one instrumentation point—I pick the native starter. If I’m onboarding legacy services or need broad library coverage without code changes, I use the Java Agent. OpenTelemetry also publishes a third-party Spring Boot starter, but its own documentation recommends it only as a fallback when the Agent isn’t an option, and it pulls in alpha artifacts, so I left it out of this homelab test.

When not to use it. Never enable both the Java Agent and the native starter in the same JVM. The Agent instruments Spring MVC while the starter creates its own Observation spans, producing duplicate server spans for every request. Also, for standalone batch jobs that make no outbound service calls, structured logs and metrics usually give you better operational visibility at lower overhead than distributed tracing. Finally, on high-throughput services, settle on a sampling budget before pointing traffic at a Collector whose memory limits you haven’t sized yet.

Configuration and verification

Native starter setup

In Spring Boot 4.0, OTLP trace export properties moved under management.opentelemetry.tracing.export.otlp.*. Note that endpoint expects the full signal path including /v1/traces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# order-api/src/main/resources/application.yml
spring:
  application:
    name: order-api
  threads:
    virtual:
      enabled: true

management:
  tracing:
    sampling:
      probability: 1.0
    propagation:
      produce: [W3C]
  opentelemetry:
    resource-attributes:
      deployment.environment: homelab
    tracing:
      export:
        otlp:
          endpoint: https://otel.namju.kim/v1/traces
          transport: http
          compression: gzip
          headers:
            Authorization: "Bearer ${OTEL_AUTH_TOKEN}"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// order-api/src/main/kotlin/kim/namju/order/config/TracingConfig.kt
package kim.namju.order.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.task.support.ContextPropagatingTaskDecorator
import org.springframework.web.client.RestClient

@Configuration
class TracingConfig {

    // Inject the auto-configured builder so traceparent headers are attached automatically
    @Bean
    fun paymentClient(builder: RestClient.Builder): RestClient =
        builder.baseUrl("http://payment-api:8080").build()

    // Applies to the auto-configured applicationTaskExecutor (@Async) to copy context across threads
    @Bean
    fun contextPropagatingTaskDecorator() = ContextPropagatingTaskDecorator()
}

Java Agent setup

For payment-api, I mounted the agent JAR into the container and configured it entirely through environment variables. Since Agent 2.x, the default protocol is http/protobuf, and the Agent automatically appends per-signal paths such as /v1/traces to OTEL_EXPORTER_OTLP_ENDPOINT. Keep the auth token in .env so no credentials sit in docker-compose.yml.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# payment-api/docker-compose.yml
services:
  payment-api:
    image: payment-api:local
    environment:
      JAVA_TOOL_OPTIONS: "-javaagent:/otel/opentelemetry-javaagent.jar"
      OTEL_SERVICE_NAME: payment-api
      OTEL_RESOURCE_ATTRIBUTES: deployment.environment=homelab
      OTEL_EXPORTER_OTLP_ENDPOINT: https://otel.namju.kim
      OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
      OTEL_EXPORTER_OTLP_HEADERS: ${OTEL_EXPORTER_OTLP_HEADERS} # .env: Authorization=Bearer%20<token>
      OTEL_TRACES_SAMPLER: parentbased_traceidratio
      OTEL_TRACES_SAMPLER_ARG: "1.0"
    volumes:
      - ./otel/opentelemetry-javaagent-2.24.0.jar:/otel/opentelemetry-javaagent.jar:ro

The fastest way to confirm end-to-end propagation is to grep the downstream service’s logs for the traceId generated by order-api, then query Tempo directly on the internal homelab network.

1
2
3
4
# Confirm payment-api logged the same traceId sent by order-api
docker logs payment-api 2>&1 | grep -m1 "4bf92f3577b34da6a3ce929d0e0e4736"
# Verify the complete trace exists in Tempo (internal homelab network)
curl -s http://tempo:3200/api/traces/4bf92f3577b34da6a3ce929d0e0e4736 | jq '.batches | length'

When .batches | length returns 2 (one batch per service), both order-api and payment-api spans are linked under the same trace.

Production pitfalls and checklist

The most frequent breakage I ran into was trace context dropping across asynchronous boundaries. Enabling spring.threads.virtual.enabled=true switches Spring’s auto-configured executor to a virtual-thread-backed SimpleAsyncTaskExecutor. Even though virtual threads are lightweight, each task still runs on a separate thread, so ThreadLocal tracing context doesn’t follow automatically. Registering ContextPropagatingTaskDecorator fixes Spring’s managed executor, including @Async methods. However, if your code spins up Executors.newVirtualThreadPerTaskExecutor() manually, Spring never wraps it and the trace breaks again. In those cases, either inject Spring’s managed executor or wrap the runnable with Micrometer’s ContextSnapshotFactory. For Kotlin coroutines, pass observationRegistry.asContextElement() into the coroutine context so suspension and resumption across threads keep the active span intact.

Spring Boot’s endpoint property uses the URL verbatim, whereas the Java Agent’s OTEL_EXPORTER_OTLP_ENDPOINT automatically appends /v1/traces. Copying the same URL between both setups either omits the path or sends requests to /v1/traces/v1/traces, resulting in 404 responses from the Collector.

My homelab Collector only exposes OTLP/HTTP (port 4318) behind Nginx Proxy Manager; gRPC (port 4317) stays restricted to the internal Docker network. If you configure the Agent with grpc against the public HTTPS domain, the connection fails immediately.

Before enabling distributed tracing in production, verify these five checks:

  • Only one instrumentation mode (native starter or Java Agent) is active per service
  • All outbound HTTP clients are created from auto-configured builders (RestClient.Builder, WebClient.Builder)
  • @Async and virtual-thread executors use ContextPropagatingTaskDecorator (and coroutines include asContextElement())
  • Root services set the intended sampling rate while downstream services use parent-based sampling
  • Endpoint URLs follow each tool’s path convention (full path for Spring Boot properties, base URL for the Java Agent)
This post is licensed under CC BY 4.0 by the author.