Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Cloud and Serverless

Metrics, Health Checks and Tracing

Observe a Micronaut service in production: management endpoints, health indicators, Micrometer and Prometheus metrics, OpenTelemetry tracing and logging. Runnable stand-ins.

Once a service runs in the cloud you cannot attach a debugger. You need it to tell you how it is doing. That is observability, and it rests on three signals: health ("can this instance serve traffic?"), metrics (numbers over time, such as requests per second) and traces (the path of one request through many services), plus logs.

Micronaut provides all three through modules you add as needed. The real modules need a running server and a monitoring system, so their code is read-only here. The TryIt examples are plain Java stand-ins for a health aggregator, a metrics registry and a trace.

Management endpoints

Add micronaut-management and enable the endpoints you want. They are HTTP routes under / by default:

GROOVY
implementation("io.micronaut:micronaut-management")
YAML
endpoints:
  all:
    port: 8081            # serve management on a separate, internal port
    sensitive: true       # require authentication
  health:
    enabled: true
    sensitive: false      # health must be reachable by the load balancer
    details-visible: AUTHENTICATED
  info:
    enabled: true
  loggers:
    enabled: true
    write-sensitive: true

Useful endpoints include /health, /info, /beans, /routes, /env, /loggers (change log levels at runtime), /metrics and /refresh. Many of them reveal internals, so protect them with security rules or expose them only on a private port.

Health

GET /health returns {"status":"UP"} when everything is fine, and DOWN with HTTP 503 otherwise. Micronaut aggregates health indicators: built-in ones for disk space, JDBC, Redis and others, plus any you write:

Java
import io.micronaut.health.HealthStatus;
import io.micronaut.management.health.indicator.HealthIndicator;
import io.micronaut.management.health.indicator.HealthResult;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import jakarta.inject.Singleton;

@Singleton
class PaymentGatewayHealth implements HealthIndicator {
    private final PaymentGateway gateway;
    PaymentGatewayHealth(PaymentGateway gateway) { this.gateway = gateway; }

    @Override
    public Publisher<HealthResult> getResult() {
        HealthStatus status = gateway.ping() ? HealthStatus.UP : HealthStatus.DOWN;
        return Mono.just(HealthResult.builder("paymentGateway", status).build());
    }
}

The overall status is the worst status of all indicators. Kubernetes can use two probes: liveness ("restart me if this fails") and readiness ("send me traffic only if this succeeds"). Micronaut exposes /health/liveness and /health/readiness for them. Keep liveness trivial; if it depends on a database, a database outage restarts every pod and makes things worse.

Three signals

Health Is this instance fit to serve?
Metrics Counters, gauges and timers over time.
1 / 2

Metrics with Micrometer

Micronaut uses Micrometer, a vendor-neutral facade, and exports to Prometheus, Datadog, CloudWatch, Graphite and many others.

GROOVY
implementation("io.micronaut.micrometer:micronaut-micrometer-core")
implementation("io.micronaut.micrometer:micronaut-micrometer-registry-prometheus")
YAML
micronaut:
  metrics:
    enabled: true
    export:
      prometheus:
        enabled: true
        step: PT1M
        descriptions: true

Out of the box you get JVM memory, garbage collection, threads, HTTP server and client timings, and datasource pool metrics. Prometheus scrapes them from /prometheus. You add your own with an injected MeterRegistry:

Java
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;

@Singleton
class OrderService {
    private final Counter placed;
    private final Timer pricing;

    OrderService(MeterRegistry registry) {
        this.placed = registry.counter("orders.placed", "channel", "web");
        this.pricing = registry.timer("orders.pricing");
    }

    Order place(Cart cart) {
        placed.increment();
        return pricing.record(() -> priceAndSave(cart));
    }
}

Kinds of meter: a counter only goes up (requests served), a gauge goes up and down (queue length), a timer records durations and counts, a distribution summary records sizes. Tags such as channel let you slice data, but each distinct tag value creates a new time series, so never tag with user ids or other unbounded values.

Try it: counters, timers and Prometheus text

Java A tiny metrics registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: aggregating health indicators

Java Health aggregation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Distributed tracing

With ten services, one user request may touch five of them. A trace is the whole journey; each hop is a span with a start, a duration and a parent. A trace id travels in an HTTP header (the W3C traceparent header) so that every service adds its spans to the same trace.

Micronaut supports OpenTelemetry:

GROOVY
implementation("io.micronaut.tracing:micronaut-tracing-opentelemetry-http")
YAML
otel:
  traces:
    exporter: otlp
  exporter:
    otlp:
      endpoint: http://localhost:4318

Incoming requests and @Client calls are traced automatically. Add your own spans with @NewSpan("price-calculation") on a method, and attach details with @SpanTag("orderId") on a parameter. Add the trace id to your logs (through the MDC) so you can jump from a log line to the trace.

Try it: spans of one request

Java A trace tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Logging

Micronaut uses SLF4J with Logback by default. In containers log to standard output in a structured format (JSON), keep levels configurable through the /loggers endpoint and never log secrets or full request bodies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the overall health status when one indicator is DOWN?

    The aggregate is the worst individual status, and the endpoint returns HTTP 503.
  2. 2. Which meter type only ever increases?

    A counter counts events, such as requests served. A gauge can go up and down.
  3. 3. Why should you avoid tagging a metric with a user id?

    High-cardinality tags create too many series. Use a small, bounded set of values.
  4. 4. What does a trace id allow you to do?

    Every service adds its spans to the same trace, so the journey can be reconstructed.

Summary

  • Observability means health, metrics, traces and logs.
  • micronaut-management exposes /health, /loggers and more; protect or isolate them.
  • Micrometer gives counters, gauges and timers and exports to Prometheus and others; keep tags low-cardinality.
  • OpenTelemetry tracing follows a request across services; propagate the trace id into logs.
  • Keep Kubernetes liveness simple and let readiness check dependencies.

Next: Testing with Micronaut Test