Sub topic 14
Observations and distributed tracing
This chapter assumes you have read the earlier chapters on exposing endpoints and on Micrometer metrics. You should be comfortable with MeterRegistry, the /actuator/metrics endpoint, and Spring Boot configuration in YAML. You do not need prior experience with tracing tools.
From metrics to observations
A metric answers "how many" and "how long" in aggregate. It cannot tell you why one request in a thousand took four seconds, or which downstream service caused it. Distributed tracing fills that gap by recording the path of a single request across services.
Spring Boot 3 unifies both through the Micrometer Observation API. You describe one unit of work as an observation. Registered handlers turn that observation into whatever signals are configured:
- A timer metric, which appears under
/actuator/metricsand in Prometheus output. - A span, which is one timed step in a trace, sent to a tracing backend.
- Optionally, log correlation, so log lines carry the trace ID.
You instrument once and get all of these. Spring MVC, RestClient, RestTemplate, WebClient, JDBC (with extra libraries), and Spring Data already create observations. For example, the http.server.requests metric you have seen is produced by an observation.
Key terms
- A trace is the complete journey of one request through all services. It has a trace ID.
- A span is one timed step inside a trace, such as an incoming HTTP request or a database call. Each span has a span ID and a parent span.
- Context propagation is the passing of the trace ID and parent span ID from one service to the next, normally in an HTTP header. The standard format is the W3C
traceparentheader. - A sampler decides which traces are recorded. Recording everything is costly, so you usually record a fraction.
Adding tracing
Observations work with only Actuator on the classpath. Tracing needs two more pieces: a bridge that connects Micrometer to a tracer, and an exporter that sends spans to a backend. This example uses OpenTelemetry and the OTLP protocol.
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>Spring Boot's dependency management supplies the versions. Then configure sampling and the export endpoint:
spring:
application:
name: order-service
management:
tracing:
sampling:
probability: 1.0
otlp:
tracing:
endpoint: http://localhost:4318/v1/traces
logging:
pattern:
correlation: "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] "The properties do the following:
management.tracing.sampling.probabilityis a number from 0.0 to 1.0. The default is0.1, so only about 10 percent of requests are traced. Setting1.0is convenient while learning but expensive under real load.management.otlp.tracing.endpointis where spans are sent. Use the OTLP HTTP endpoint of your collector or backend.logging.pattern.correlationadds the trace and span IDs to every log line written during a traced request. Recent Boot 3 versions configure a similar pattern automatically when tracing is on the classpath. Setting it explicitly makes the format predictable.
If you use Zipkin instead, swap the bridge for micrometer-tracing-bridge-brave, add io.zipkin.reporter2:zipkin-reporter-brave, and set management.zipkin.tracing.endpoint.
Creating your own observations
Framework observations cover the edges of your service. Use the API directly to time business logic that matters.
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import org.springframework.stereotype.Service;
@Service
public class InvoiceService {
private final ObservationRegistry registry;
public InvoiceService(ObservationRegistry registry) {
this.registry = registry;
}
public String generate(String customerId) {
return Observation.createNotStarted("invoice.generate", registry)
.lowCardinalityKeyValue("type", "monthly")
.highCardinalityKeyValue("customer.id", customerId)
.observe(() -> render(customerId));
}
private String render(String customerId) {
return "invoice-for-" + customerId;
}
}observe starts the observation, runs the supplier, records any exception as an error, and stops the observation in all cases. You do not manage start and stop yourself.
After a call, /actuator/metrics/invoice.generate shows a timer tagged with type. In Prometheus output the same timer appears as invoice_generate_seconds_count, _sum, and _max. The trace backend shows a span named invoice.generate.
Low and high cardinality key values
Cardinality is the number of distinct values a tag can take. Each distinct tag combination creates a separate time series in your metrics system.
| Kind | Used in metrics | Used in traces | Good for |
|---|---|---|---|
| Low cardinality | Yes, as a tag | Yes, as a span tag | Bounded sets: HTTP method, outcome, order type |
| High cardinality | No | Yes, as a span tag | Unbounded values: user ID, order ID, full URL |
Putting a customer ID in a low-cardinality key value creates one time series per customer. This can overload Prometheus and raise your monitoring bill. Unbounded values belong in the high-cardinality group, where only traces carry them.
Observing with an annotation
For simple cases, @Observed avoids the boilerplate. It needs AspectJ support and an ObservedAspect bean:
import io.micrometer.observation.ObservationRegistry;
import io.micrometer.observation.annotation.Observed;
import io.micrometer.observation.aop.ObservedAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
@Configuration
class ObservationConfig {
@Bean
ObservedAspect observedAspect(ObservationRegistry registry) {
return new ObservedAspect(registry);
}
}
@Service
class ShippingService {
@Observed(name = "shipping.quote",
contextualName = "quote-shipping",
lowCardinalityKeyValues = {"carrier", "default"})
public double quote(String destination) {
return 9.99;
}
}Add spring-boot-starter-aop to the project, or @Observed is silently ignored. The annotation works through a Spring proxy. A method called from another method in the same class bypasses the proxy and produces no observation. This is the most common reason an annotated method shows no metrics.
Making sure the trace continues across services
A trace only spans several services if each call passes the context along. Spring does this for you, but only for clients built from its auto-configured builders:
- Inject
RestClient.Builder,RestTemplateBuilder, orWebClient.Builderinstead of callingRestClient.create(),new RestTemplate(), orWebClient.create(). - A client created with
newhas no observation support. It sends notraceparentheader, so the downstream service starts a new, unrelated trace.
The following sequence shows a healthy trace:
Both services export spans with the same trace ID. The backend joins them into one tree.
Common problems
- No traces appear. Check the sampling probability first. With the default
0.1, nine of ten test requests are not recorded. Then check that the exporter dependency is present and the endpoint is reachable. - Trace breaks between services. The calling code probably uses a client that was not built from an injected builder. Message consumers and
@Asyncmethods also lose context unless the framework's instrumentation or context-propagating executors are used. - Metrics explode in size. A high-cardinality value was registered as a low-cardinality key value. Move it with
highCardinalityKeyValue. - Log lines lack IDs. The correlation pattern is not applied, or you set a custom
logging.pattern.consolethat omits it. - Health and Prometheus scrapes flood the trace backend. Actuator requests are observed like any others. Boot excludes some of them, but verify this for your version. A custom
ObservationPredicatebean can filter out observations by name or path.
Observations in production
Metrics tell you that something is wrong, and traces tell you where. A typical workflow is to see a latency alert on http.server.requests, find the slow endpoint in a dashboard, and then open a trace of a slow request. The trace ID in the log line links the log, the trace, and the metric period. Keep sampling low on high-traffic services, and rely on the aggregate metrics, which are never sampled, for alerting.
Exercise
A teammate adds .lowCardinalityKeyValue("order.id", orderId) to an observation, and Prometheus memory usage grows quickly. What is wrong, and how do you fix it?
Show answer
An order ID is unbounded, so each order creates a new time series in the metric. Use .highCardinalityKeyValue("order.id", orderId) instead. High-cardinality values go only into trace spans, not into metric tags.
Exercise
You annotate a method with @Observed, call it from another method in the same class, and see no shipping.quote metric. Name two things to check.
Show answer
Check that spring-boot-starter-aop is on the classpath and that an ObservedAspect bean is defined. Also check that the call goes through the Spring proxy. A call from within the same class bypasses the proxy, so move the method to another bean or call it from outside.
Exercise
Service A calls service B, but the trace backend shows two separate traces. A builds its client with new RestTemplate(). Why does this break the trace, and what is the fix?
Show answer
A client created with new is not instrumented, so it does not add the traceparent header. Service B therefore starts a new trace. Inject RestTemplateBuilder and build the client from it, or use an injected RestClient.Builder.