Video in progress

What is the Observation API in Spring Boot 3, and how does it differ from a plain `Timer` and from tracing?

Observation is an abstraction that lets you wrap code once and get a metric, a span and a log all at once. The code only starts and stops the Observation, and the handlers in the registry decide which signals are produced.

📖 Answer

In Spring Boot 2, you had Timer for metrics and Sleuth for tracing as separate things, and you had to wrap one operation twice. In Boot 3, Micrometer Tracing replaced Sleuth, and everything came together around ObservationRegistry.

@Service
class PaymentService {
    private final ObservationRegistry registry;

    PaymentResult pay(PaymentRequest req) {
        return Observation.createNotStarted("payment.pay", registry)
                .lowCardinalityKeyValue("provider", req.provider())   // metric tag + span attribute
                .highCardinalityKeyValue("orderId", req.orderId())    // span only, not the metric
                .observe(() -> gateway.charge(req));
    }
}

From one call you get:

  • DefaultMeterObservationHandler: the payment.pay timer and an active-task gauge;
  • the tracing handler: the payment.pay span;
  • traceId/spanId in MDC.

The most useful part is the split between lowCardinality and highCardinality: the cardinality problem is closed off at the API level.

There is also an annotation variant, @Observed(name = "payment.pay"), but it works through AOP: you need an ObservedAspect bean (from Boot 3.2, management.observations.annotations.enabled=true registers it for you; before that, you do it by hand), and it doesn't work on self-invocation. Spring itself (MVC, WebFlux, RestClient, WebClient, Spring Kafka, @Scheduled) is also instrumented through this API.