Spring Boot & Spring Cloud
Spring Boot Actuator and Observability: Health, Metrics, Tracing and Logs
Intermediate7 min readUpdated
You will be able to expose exactly the management endpoints a service needs, wire liveness and readiness probes, publish application and business metrics to Prometheus, propagate trace context across services and into logs, and lock the whole surface down so that observability does not become an information leak.
What you will learn
- Enable and expose Actuator endpoints selectively and secure them
- Configure health groups and Kubernetes liveness and readiness probes, and write a custom HealthIndicator
- Publish JVM, HTTP and custom business metrics through Micrometer to Prometheus
- Add distributed tracing with Micrometer Tracing and correlate traces with log lines
- Explain the Observation API and instrument a critical code path with it
A service you cannot observe is a service you cannot operate. Spring Boot Actuator turns a jar into something an operator can interrogate: is it healthy, what is it doing, how fast, and what was the request that failed at 03:14. This page covers the four pillars as Boot 3 implements them: management endpoints, health and probes, metrics through Micrometer, and traces through Micrometer Tracing with log correlation. Along the way it deals with the part most tutorials skip, which is not exposing all of that to the public internet.
Endpoints: enabling, exposing and securing
Add spring-boot-starter-actuator. Every endpoint has two independent switches: enabled (does the bean exist) and exposed (is it reachable over HTTP or JMX). All endpoints except shutdown are enabled by default; over HTTP only health is exposed. Exposure is a list:
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus,loggers
base-path: /actuator # default; change it if / is already taken by an API prefix
endpoint:
health:
show-details: when-authorized
env:
show-values: when-authorized # Boot 3 masks all env and configprops values by default
server:
port: 9090 # optional: management traffic on a separate port
The endpoints worth knowing:
| Endpoint | What it gives you | Exposure advice |
|---|---|---|
health | Aggregated status of the application and its dependencies | Public without details; details for authenticated users |
info | Build version, git commit, custom facts | Fine to expose internally |
metrics / prometheus | Micrometer meters, in JSON or Prometheus text format | Expose to the scraper only |
loggers | Read and change log levels at runtime | Authenticated |
env, configprops | Effective configuration and bound properties | Authenticated, values masked |
beans, conditions, mappings | Context introspection for debugging | Authenticated, or local only |
threaddump, heapdump | Diagnostics under load | Authenticated; heap dumps contain secrets |
shutdown | Graceful stop via POST | Disabled unless you really need it |
Running management endpoints on a separate port (management.server.port) is the simplest hardening: bind the main port to the load balancer and the management port only to the cluster network. When the application uses Spring Security, endpoints on the main port are protected by the same filter chain, and EndpointRequest matchers let you write the rule precisely:
@Bean
SecurityFilterChain actuatorSecurity(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
.requestMatchers(EndpointRequest.to(HealthEndpoint.class)).permitAll()
.anyRequest().hasRole("OPS"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
The info endpoint is empty until you feed it. The Maven and Gradle plugins can generate build information (spring-boot-maven-plugin's build-info goal, springBoot { buildInfo() } in Gradle), the git-commit-id plugin adds commit data, and any InfoContributor bean adds custom entries. info.env.enabled=true turns info.* properties into entries too.
Health and probes
health aggregates HealthIndicator beans. Boot auto-configures one for every dependency it knows about: the DataSource, Redis, RabbitMQ, Kafka, Elasticsearch, disk space, and more. Each returns UP, DOWN, OUT_OF_SERVICE or UNKNOWN; the aggregate is DOWN if any contributor is, and the HTTP status is 503 for DOWN and OUT_OF_SERVICE, 200 otherwise.
A custom indicator is a small bean:
@Component
class PaymentGatewayHealthIndicator implements HealthIndicator {
private final PaymentGatewayClient gateway;
PaymentGatewayHealthIndicator(PaymentGatewayClient gateway) {
this.gateway = gateway;
}
@Override
public Health health() {
try {
Duration latency = gateway.ping();
return Health.up().withDetail("latency", latency.toMillis() + "ms").build();
} catch (Exception ex) {
return Health.down(ex).build(); // the exception message shows only with show-details
}
}
}
The bean name minus the HealthIndicator suffix becomes the contributor's key (paymentGateway). Keep indicators cheap: they run on every probe and orchestrators probe often. Cache the result for a few seconds if the check is a network call.
Liveness and readiness
Kubernetes distinguishes two questions, and so should your health configuration. Boot exposes two health groups, liveness and readiness, at /actuator/health/liveness and /actuator/health/readiness. They are enabled automatically when the application detects it is running on Kubernetes (through the KUBERNETES_SERVICE_HOST environment variable), and can be forced with management.endpoint.health.probes.enabled=true.
By default the liveness group contains only the LivenessStateHealthIndicator, which reflects the application's own LivenessState and does not touch external systems. The readiness group contains only the ReadinessStateHealthIndicator, which goes REFUSING_TRAFFIC during startup and shutdown. You add the dependencies that matter to readiness explicitly:
management:
endpoint:
health:
group:
readiness:
include: readinessState,db,paymentGateway
liveness:
include: livenessState
Do not put the database in liveness. If the database goes away, restarting every pod does not bring it back; it only adds reconnect storms. Readiness is the right lever: the pod stops receiving traffic and rejoins when the dependency recovers.
The matching deployment fragment:
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 9090 }
initialDelaySeconds: 10
periodSeconds: 10
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 9090 }
periodSeconds: 5
Application code can flip the states through AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC), for example while a cache warms up. With server.shutdown=graceful, Boot marks readiness as refusing traffic first, waits for in-flight requests, then stops, which pairs naturally with rolling updates.
Metrics with Micrometer
Actuator's metrics are built on Micrometer, a vendor-neutral facade in the way SLF4J is for logging. Boot registers meters for the JVM (memory, garbage collection, threads, class loading), the system (CPU, file descriptors), HTTP server requests, RestClient/WebClient calls, DataSource pools, caches, executors, and more. GET /actuator/metrics/http.server.requests shows the meter with its tags; drill in with ?tag=uri:/api/orders&tag=status:500.
To ship them somewhere, add a registry. For Prometheus:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>
and expose prometheus; the scraper reads /actuator/prometheus in text exposition format. Registries for OpenTelemetry (OTLP), Datadog, New Relic, Graphite, InfluxDB and others follow the same pattern and can coexist.
Business metrics are where observability pays for itself. Inject the MeterRegistry:
@Service
class CheckoutService {
private final Counter ordersPlaced;
private final Timer paymentTimer;
CheckoutService(MeterRegistry registry) {
this.ordersPlaced = Counter.builder("shop.orders.placed")
.description("Orders successfully placed")
.register(registry);
this.paymentTimer = Timer.builder("shop.payment.duration")
.publishPercentileHistogram() // lets Prometheus compute quantiles
.register(registry);
}
Order checkout(Cart cart) {
Payment payment = paymentTimer.record(() -> gateway.charge(cart.total()));
Order order = orders.create(cart, payment);
ordersPlaced.increment();
return order;
}
}
Tags add dimensions (.tag("channel", "web")), and every distinct tag value creates a new time series; never tag with unbounded values such as customer ids or free text. @Timed on a method works when TimedAspect is registered as a bean and AOP is on the classpath. Common tags for all meters (management.metrics.tags.application=shop, region=eu-west-1) make dashboards filterable across services.
Percentiles deserve one note: publishPercentiles computes them in the application and cannot be aggregated across instances; publishPercentileHistogram publishes buckets so the monitoring system can compute quantiles over the fleet. Prefer the histogram for anything you will aggregate.
Tracing and the Observation API
Metrics tell you that the 99th percentile jumped; traces tell you which downstream call did it. Spring Boot 3 replaced Spring Cloud Sleuth with Micrometer Tracing, which is a facade over a tracer implementation. Pick a bridge and an exporter:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>
management:
tracing:
sampling:
probability: 0.1 # default 0.1; 1.0 in development
otlp:
tracing:
endpoint: http://otel-collector:4318/v1/traces
With that in place, incoming HTTP requests, RestClient/WebClient calls, JDBC (via the datasource-micrometer library), Kafka and RabbitMQ interactions carry spans, and the W3C traceparent header propagates context between services (B3 is available through management.tracing.propagation.type). micrometer-tracing-bridge-brave with Zipkin is the alternative combination.
The unifying concept underneath is the Observation API from Micrometer 1.10. An Observation is a unit of work that, when started and stopped, produces a timer and a span and whatever else the registered handlers do. Instrumenting your own critical path once gives you both signals:
Observation.createNotStarted("shop.checkout", observationRegistry)
.lowCardinalityKeyValue("channel", cart.channel()) // becomes a metric tag and a span attribute
.highCardinalityKeyValue("cart.id", cart.id()) // span-only, never a metric tag
.observe(() -> checkoutService.checkout(cart));
@Observed on a method does the same declaratively when ObservedAspect is registered. The low/high cardinality split encodes the tagging rule from the metrics section directly in the API.
Correlating logs with traces
When tracing is active, Boot 3 puts traceId and spanId into the logging MDC and includes them in the default console pattern as [app,traceId,spanId]. Copying a trace id from a log line into your tracing UI, or from a trace into your log search, closes the loop between the two systems. If you customise logging.pattern.console, keep %X{traceId} and %X{spanId} in it, or use logging.pattern.correlation (Boot 3.1+) to change only that fragment.
Structured logging finishes the job: Boot 3.4 can write JSON lines in Elastic Common Schema or Logstash format with logging.structured.format.console=ecs, so a log platform indexes trace ids and custom fields without regex parsing. Returning the trace id to clients in error responses, as suggested in the error handling guide, turns a support ticket into a direct lookup.
Common mistakes
Exposing * and forgetting about it. management.endpoints.web.exposure.include=* in a tutorial becomes env, heapdump and threaddump reachable by anyone who finds /actuator. Enumerate the endpoints you need and put the rest behind authentication or a separate port.
Putting external dependencies in the liveness probe. A database outage becomes a fleet-wide restart loop. Liveness stays internal; readiness carries the dependencies.
Expensive health checks. An indicator that runs a query over a large table, or calls a third-party API without a timeout, turns the probe itself into a load problem. Give each check a timeout and cache results.
High-cardinality tags. A userId tag on http.server.requests creates one time series per user and can exhaust the registry and the monitoring backend. Use high-cardinality values only on spans.
Sampling at 100 % in production without capacity planning. Traces are large. Start with the default probability and raise it for specific services or during incidents, or use tail-based sampling in the collector.
Assuming metrics appear with no registry. The metrics endpoint shows meters, but nothing is exported until a registry dependency is added; the prometheus endpoint does not exist without micrometer-registry-prometheus.
Key takeaways
- Actuator endpoints are enabled by default but only
healthis exposed over HTTP; expose an explicit list, secure the rest, and consider a separate management port. - Liveness must reflect only the process's own state; readiness includes the dependencies a request needs, so failures shed traffic instead of restarting pods.
- Micrometer provides JVM, HTTP and pool metrics out of the box; add a registry (Prometheus, OTLP, others) to export them and a few well-tagged business meters to make them meaningful.
- Micrometer Tracing replaces Sleuth in Boot 3; pick a bridge (OpenTelemetry or Brave) and an exporter, set the sampling probability, and context propagates automatically.
- The Observation API instruments a code path once and yields both a timer and a span; keep high-cardinality values out of metric tags.
- Trace ids in the MDC and structured JSON logs link logs, metrics and traces into one investigation path.
Sources and further reading
Frequently asked questions
- Which Actuator endpoints are exposed over HTTP by default?
- Only health. Every other endpoint (info, metrics, env, beans, loggers, threaddump and so on) is enabled but not exposed over the web until you list it in management.endpoints.web.exposure.include. Over JMX the default exposure is also limited to health since Boot 2.2. This conservative default exists because endpoints such as env and heapdump reveal configuration and memory contents.
- What is the difference between liveness and readiness?
- Liveness answers 'is this process broken beyond recovery?' and a failing probe makes Kubernetes restart the container, so it must not depend on external systems. Readiness answers 'can this instance take traffic right now?' and a failing probe only removes the pod from the Service's endpoints, so it is the right place to reflect a lost database connection or a warm-up phase.
- Do I still need Spring Cloud Sleuth for tracing?
- No. Spring Cloud Sleuth reached end of life with Spring Boot 2.x. In Boot 3 tracing is provided by Micrometer Tracing, with bridges to OpenTelemetry or Brave, and auto-configured by Actuator. The API changed (Observation and Tracer instead of Sleuth's Span types), but the property prefix management.tracing.* covers sampling and propagation.
- How do I change a log level in production without restarting?
- Expose the loggers endpoint and send a POST to /actuator/loggers/com.example.shop with a JSON body such as {"configuredLevel": "DEBUG"}. The change is immediate and lost on restart. Protect the endpoint with authentication, since it can generate enough log volume to affect the service.