Chapter 12

Actuator and observability

The difference between "the service is down" and "the p99 on /api/books tripled after the 14:02 deploy" is about twenty lines of configuration.

⏱ 20 min readLevel: intermediate
Actuator endpoints feeding Micrometer, which exports to Prometheus, an OpenTelemetry collector and log aggregation, all visualised in Grafana
Two dependencies give you metrics, traces and health probes.

Setup

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-prometheus</artifactId>
  <scope>runtime</scope>
</dependency>
application.yml — a production-shaped baseline
management:
  server:
    port: 9090                      # separate port — do not expose this publicly
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,loggers
      base-path: /actuator
  endpoint:
    health:
      show-details: when-authorized
      probes:
        enabled: true               # adds /health/liveness and /health/readiness
    loggers:
      access: unrestricted          # change log levels without a restart
  metrics:
    tags:
      application: ${spring.application.name}
      env: ${ENVIRONMENT:local}
  observations:
    key-values:
      application: ${spring.application.name}

info:
  app:
    name: ${spring.application.name}
    version: '@project.version@'
The endpoints you must never expose publicly

/env and /configprops print your configuration. /heapdump downloads the entire heap — including every string in memory, so passwords and tokens. /threaddump and /loggers are useful to an attacker mapping your system. Use management.server.port to bind actuator to an internal port, and additionally require a role (chapter 10). include: "*" in production is a genuine incident waiting to happen.

The endpoints worth knowing

EndpointGives youExpose?
/healthAggregated up/down plus component detailYes (liveness/readiness publicly, details restricted)
/infoBuild version, git commitYes
/metricsBrowse individual metricsInternal
/prometheusScrape format for PrometheusInternal
/loggersRead and change log levels at runtimeInternal, admin only
/beansEvery bean, its type and dependenciesInternal
/conditionsThe auto-configuration reportInternal
/mappingsEvery URL and its handler methodInternal
/configpropsBound @ConfigurationPropertiesInternal only
/envEvery property and its sourceInternal only
/threaddumpFull thread dumpInternal only
/heapdumpDownloads a heap dump fileDisable in production
/scheduledtasksAll @Scheduled methodsInternal
/startupPer-bean startup timingsInternal, needs a buffering recorder

Health checks that mean something

Boot auto-registers indicators for the data source, Redis, Kafka, disk space and more, and aggregates them. The key insight is the liveness vs readiness distinction.

ProbeQuestionIf it fails
/health/livenessIs the process broken beyond recovery?Kubernetes restarts the pod
/health/readinessCan it serve traffic right now?Kubernetes removes it from the load balancer
Never put your database in the liveness probe

If the database has a brief hiccup, a database-backed liveness probe makes Kubernetes restart every single pod simultaneously — turning a 30-second blip into a full outage with a thundering-herd reconnect. Databases belong in readiness. Liveness should answer only "is this JVM wedged?".

application.yml
management:
  endpoint:
    health:
      probes:
        enabled: true
      group:
        liveness:
          include: livenessState        # nothing external
        readiness:
          include: readinessState,db,inventoryService
          show-details: always
common/health/InventoryHealthIndicator.java
@Component("inventoryService")
public class InventoryHealthIndicator implements HealthIndicator {

    private final InventoryClient client;

    public InventoryHealthIndicator(InventoryClient client) {
        this.client = client;
    }

    @Override
    public Health health() {
        try {
            long start = System.nanoTime();
            client.ping();
            long millis = (System.nanoTime() - start) / 1_000_000;

            return millis < 500
                    ? Health.up().withDetail("latencyMs", millis).build()
                    : Health.status("DEGRADED").withDetail("latencyMs", millis).build();

        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}
GET /actuator/health
{
  "status": "UP",
  "components": {
    "db":               { "status": "UP", "details": { "database": "PostgreSQL", "validationQuery": "isValid()" } },
    "diskSpace":        { "status": "UP", "details": { "total": 494384795648, "free": 216287453184 } },
    "inventoryService": { "status": "UP", "details": { "latencyMs": 34 } },
    "livenessState":    { "status": "UP" },
    "readinessState":   { "status": "UP" }
  }
}

Metrics with Micrometer

Micrometer is a facade over metric backends — you instrument once and export to Prometheus, Datadog, CloudWatch or anything else by swapping a dependency.

catalog/BookService.java — custom instruments
@Service
public class BookService {

    private final Counter booksCreated;
    private final Timer searchTimer;
    private final DistributionSummary orderValue;

    public BookService(MeterRegistry registry, BookRepository repository) {
        this.booksCreated = Counter.builder("bookstore.books.created")
                .description("Books created since startup")
                .tag("source", "api")
                .register(registry);

        this.searchTimer = Timer.builder("bookstore.search.duration")
                .publishPercentiles(0.5, 0.95, 0.99)
                .publishPercentileHistogram()
                .register(registry);

        this.orderValue = DistributionSummary.builder("bookstore.order.value")
                .baseUnit("EUR")
                .register(registry);

        // a gauge observes something continuously — no manual updates
        Gauge.builder("bookstore.books.total", repository, JpaRepository::count)
             .description("Books currently in the catalogue")
             .register(registry);
    }

    public Book create(CreateBookCommand command) {
        Book book = repository.save(Book.from(command));
        booksCreated.increment();
        return book;
    }

    public Page<Book> search(BookSearchFilter filter, Pageable pageable) {
        return searchTimer.record(() -> repository.findAll(toSpec(filter), pageable));
    }
}
InstrumentUse forExample
CounterThings that only increaseorders placed, errors
TimerDuration + count togetherrequest latency
GaugeA value that goes up and downqueue depth, cache size
DistributionSummaryNon-time distributionspayload size, order value
LongTaskTimerWork still in progressa running import job
Never tag with an unbounded value

.tag("userId", userId) or .tag("bookId", id) creates one time series per distinct value. A million users means a million series, and you will take down your metrics backend before you notice. Tags must have low, bounded cardinality: status, method, outcome, region.

@Observed — one annotation for metrics and traces

the Observation API
@Configuration
public class ObservationConfig {

    @Bean
    ObservedAspect observedAspect(ObservationRegistry registry) {
        return new ObservedAspect(registry);
    }
}

@Service
public class PricingService {

    @Observed(name = "pricing.calculate",
              contextualName = "calculate-order-total",
              lowCardinalityKeyValues = {"tier", "standard"})
    public Money calculate(Order order) {
        // produces a timer AND a trace span from one annotation
    }
}

Distributed tracing

pom.xml
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<dependency>
  <groupId>io.opentelemetry</groupId>
  <artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>
application.yml
management:
  tracing:
    sampling:
      probability: 0.1        # 10% in production; 1.0 in dev
  otlp:
    tracing:
      endpoint: http://otel-collector:4318/v1/traces

logging:
  pattern:
    level: "%5p [${spring.application.name},%X{traceId:-},%X{spanId:-}]"

Trace and span ids are placed in the logging MDC automatically, so every log line can be correlated with a trace — and with the traceId you returned in the ProblemDetail back in chapter 7.

Structured logging

Boot 3.4 can emit JSON logs natively — no Logback encoder dependency required.

application.yml
logging:
  structured:
    format:
      console: ecs               # or: logstash, gelf
  level:
    root: INFO
    com.bitsnippets.bookstore: INFO
what a log line becomes
{
  "@timestamp": "2026-08-17T10:24:31.882Z",
  "log.level": "INFO",
  "service.name": "bookstore",
  "trace.id": "3f2a1c9e5b7d4a10",
  "span.id": "a1b2c3d4",
  "message": "Book created id=1042",
  "log.logger": "com.bitsnippets.bookstore.catalog.BookService"
}
What not to log

Passwords, tokens, full card numbers, national identifiers, session cookies, and complete request bodies on user endpoints. Logs are copied into aggregation systems that many more people can read than your database. When in doubt, log an identifier and look the record up.

What to actually alert on

MetricAlert whenMeans
http.server.requests 5xx rate> 1% for 5 minSomething is broken
http.server.requests p99> 2× baselineDegradation before it becomes an outage
hikaricp.connections.pending> 0 for 1 minPool exhausted — slow queries or a leak
jvm.memory.used / max (old gen)> 85% sustainedHeading for OOM
jvm.gc.pausep99 > 1sGC pressure
application.ready.time> 2× previous releaseA startup regression
Custom business counterdrops to zeroOften the earliest real signal

That last row matters more than people expect: "orders placed per minute went to zero" is usually detected before any infrastructure metric moves.

A custom actuator endpoint

common/CacheStatsEndpoint.java
@Component
@Endpoint(id = "cachestats")
public class CacheStatsEndpoint {

    private final CacheManager cacheManager;

    @ReadOperation
    public Map<String, Object> stats() {
        return cacheManager.getCacheNames().stream()
                .collect(Collectors.toMap(name -> name, this::statsFor));
    }

    @WriteOperation
    public void evict(@Selector String cacheName) {
        Optional.ofNullable(cacheManager.getCache(cacheName)).ifPresent(Cache::clear);
    }
}

Available at GET /actuator/cachestats and POST /actuator/cachestats/{cacheName}, once added to the exposure list.

Checklist

  • Actuator on a separate port, and role-protected.
  • include lists explicit endpoints — never "*" in production.
  • Liveness has no external dependencies; readiness has the ones you cannot serve without.
  • Prometheus scraping, with application and env tags.
  • No high-cardinality metric tags.
  • Trace ids in logs and in error responses.
  • Alerts on error rate, latency, pool saturation and at least one business metric.
  • Heap dump endpoint disabled outside development.

Why should the database not be part of the liveness probe?

Liveness failure means "restart me". Restarting will not fix a database that is down — it just adds a mass reconnect storm on top of the original problem. Dependencies belong in readiness, which removes the instance from the load balancer until it can serve again.