Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 66 ยท Production Features

Actuator: Health, Metrics and Info

Monitor a Spring Boot app with Actuator: endpoints, exposure and security, health groups and Kubernetes probes, custom HealthIndicators and info.

Once an application is running somewhere you cannot attach a debugger, you need it to tell you how it is doing. Is it up? Can it reach the database? How much memory is it using? Which version is deployed? Which beans and properties did it start with? Load balancers, Kubernetes, monitoring systems and the engineer on call all ask these questions, and they should not have to read log files to get answers.

Spring Boot Actuator adds production-ready endpoints that answer them: /actuator/health, /actuator/metrics, /actuator/info and many more. You add one starter and Boot publishes them. The part that needs thought is not turning them on but deciding which ones to expose and to whom, because some endpoints reveal a lot. This lesson covers the endpoints, exposure and security, health groups and probes, writing a custom health indicator and filling the info endpoint. Metrics and tracing go deeper in Observability; for a library-level view see Actuator and Observability.

Spring Boot cannot run on this site, so the real configuration and classes are read-only. The TryIts re-create the decisions Actuator makes (combining health statuses, choosing exposed endpoints, merging info) in plain Java.

What Actuator gives you

Health Is the app and its dependencies OK?
Metrics Memory, threads, requests, your own numbers.
Info Version, build, git commit.
Operations Log levels, thread dumps, beans, config.
1 / 2

Adding Actuator

Add the starter:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Start the application and open /actuator. It lists the endpoints that are exposed over HTTP. The commonly used ones:

Endpoint What it shows
health overall status and, if allowed, the status of each component
info application information you contribute (build, git, custom keys)
metrics names and values of metrics (jvm.memory.used, http.server.requests, ...)
prometheus the same metrics in Prometheus text format (needs the Micrometer Prometheus registry)
env the Environment: properties and where they came from
configprops all @ConfigurationProperties beans with their bound values
beans, mappings, conditions the bean graph, request mappings, and the auto-configuration report
loggers log levels, and a way to change a level at runtime with a POST
threaddump, heapdump diagnostic dumps (a heap dump contains everything in memory)
scheduledtasks, caches, flyway state of scheduled jobs, caches, migrations
shutdown stops the application; disabled unless you enable it

A health response looks like this (with details enabled):

JSON
{
  "status": "UP",
  "components": {
    "db": { "status": "UP", "details": { "database": "PostgreSQL" } },
    "diskSpace": { "status": "UP", "details": { "free": 91234234368, "threshold": 10485760 } },
    "ping": { "status": "UP" }
  }
}

Exposure and security

Actuator distinguishes two things: an endpoint can be enabled (the bean exists) and exposed (reachable over a technology, HTTP or JMX). Over HTTP only health is exposed by default, and you widen that deliberately:

YAML
management:
  endpoints:
    web:
      exposure:
        include: health, info, metrics, prometheus
        exclude: heapdump
  endpoint:
    health:
      show-details: when-authorized

Use specific names rather than *. A wildcard also exposes whatever endpoint a future dependency adds. Several settings control how much leaks:

  • show-details for health: never (default, only the overall status), when-authorized (details for users with the right roles) or always. Details name your databases and brokers; keep them away from anonymous users.
  • show-values for env and configprops: by default values are hidden (shown as ******) until you opt in with when-authorized or always. Even then, treat these endpoints as sensitive because secrets can sit in unexpected property names.
  • A separate management port: management.server.port=9090 moves all actuator endpoints off the public port, so a firewall or Kubernetes network policy can keep them internal. You can also change the base path with management.endpoints.web.base-path.
  • Spring Security protects actuator like any other path. A typical rule allows health to everyone (or to the load balancer) and requires a role for the rest:
Java
@Bean
SecurityFilterChain actuator(HttpSecurity http) throws Exception {
    http
        .securityMatcher(EndpointRequest.toAnyEndpoint())
        .authorizeHttpRequests(a -> a
            .requestMatchers(EndpointRequest.to("health", "info")).permitAll()
            .anyRequest().hasRole("OPS"))
        .httpBasic(Customizer.withDefaults());
    return http.build();
}

Imports for actuator types moved in Boot 4, where Actuator was split into smaller modules; let your IDE suggest them. The concepts stay the same. See CSRF, CORS and Secure Defaults for why "expose everything" is among the most common Boot misconfigurations.

The first TryIt applies include and exclude patterns to a list of endpoints, the way management.endpoints.web.exposure does, and masks sensitive values in an env listing.

Java Which endpoints are exposed, and what leaks

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.

What is real: exposure is an explicit allow-list and sensitive property values are masked by default. What is the stand-in: Boot decides "sensitive" with configurable key patterns (and, since Boot 3, hides all values until you set show-values), and exposure applies separately to HTTP and JMX.

Health: status, components and groups

The health endpoint combines many health indicators into one answer. Boot auto-configures indicators for what it finds on the classpath: db for a DataSource, diskSpace, redis, mongo, rabbit, kafka, mail and others. Each returns a status, and the aggregator picks the most severe one, in this order: DOWN, OUT_OF_SERVICE, UP, UNKNOWN. So one failing database makes the whole application DOWN. By default DOWN and OUT_OF_SERVICE are served as HTTP 503, and UP as 200, which is the signal a load balancer reads.

Health groups let you publish different subsets under their own paths:

YAML
management:
  endpoint:
    health:
      probes:
        enabled: true
      group:
        readiness:
          include: readinessState, db
        critical:
          include: db, redis
          show-details: always

You then call /actuator/health/critical. Groups are how you give different consumers different answers.

Liveness and readiness probes

Kubernetes asks two different questions, and Boot supports both with built-in groups (enabled automatically when it detects it runs on Kubernetes, or with management.endpoint.health.probes.enabled=true):

  • Liveness (/actuator/health/liveness): "is the process broken beyond repair?" If it fails, Kubernetes restarts the container. It should reflect only the application's internal state, and never external systems. If the database is down and liveness fails, Kubernetes restarts every pod, which fixes nothing and adds load to a recovering database.
  • Readiness (/actuator/health/readiness): "can I send traffic here right now?" If it fails, the pod is taken out of the load balancer but not restarted. During startup and graceful shutdown the application reports REFUSING_TRAFFIC; you can add dependencies that the app genuinely needs to be able to serve requests.

Mixing these up is a classic production mistake: pointing liveness at /actuator/health (which includes the database) can turn a short database outage into a crash loop. Deployment: Cloud, Kubernetes and Config shows the full pod configuration.

Writing a custom HealthIndicator

Implement HealthIndicator and register it as a bean. The bean name minus the HealthIndicator suffix becomes the component name:

Java
@Component
class PaymentGatewayHealthIndicator implements HealthIndicator {

    private final PaymentGatewayClient gateway;

    PaymentGatewayHealthIndicator(PaymentGatewayClient gateway) {
        this.gateway = gateway;
    }

    @Override
    public Health health() {
        try {
            long millis = gateway.ping();            // a cheap call with its own short timeout
            return Health.up().withDetail("latencyMs", millis).build();
        } catch (Exception e) {
            return Health.down(e).withDetail("endpoint", gateway.baseUrl()).build();
        }
    }
}

This shows as paymentGateway in the response. Health checks run on every probe, often every few seconds, from several pods. Keep them fast and cheap: set a short timeout, avoid expensive queries, and cache the result if the check is heavy. A health check that hangs makes the probe itself fail. Also decide whether an optional dependency should count at all: if the app can limp along without the payment gateway, a degraded status in a non-critical group (or an info entry) is better than marking the whole app DOWN.

The second TryIt implements the aggregation rules: indicators, the severity order, groups, HTTP status mapping and hiding details from anonymous callers.

Java A health aggregator with groups

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.

Notice that the cache being down turns the full health DOWN (and 503), while liveness stays UP. That is the behaviour you want: Kubernetes keeps the pod running, and the load balancer stops sending it traffic if the readiness group includes Redis. What is the stand-in: real indicators return Health objects with maps of details, and the aggregation is done by a StatusAggregator that you can replace.

The info endpoint

/actuator/info is a bag of facts about the build and the running application, assembled from info contributors. Several are built in:

  • build: the Maven or Gradle plugin writes META-INF/build-info.properties when you add the build-info goal (or springBoot { buildInfo() }), giving name, version and build time.
  • git: add a git properties plugin and the commit id, branch and time appear (management.info.git.mode=full adds more).
  • env: any property under info.* is published, enabled with management.info.env.enabled=true, for example info.app.owner=payments-team.
  • java, os, process: opt in with management.info.java.enabled=true and similar.

Your own contributor implements InfoContributor:

Java
@Component
class FeatureFlagsInfo implements InfoContributor {

    private final FeatureFlags flags;

    FeatureFlagsInfo(FeatureFlags flags) { this.flags = flags; }

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("features", flags.enabledNames());
    }
}

The most valuable info entry is the version and commit that is actually running. During an incident, "which build is this?" is the first question, and the answer should be one curl away. The TryIt merges contributors in order, the way Boot builds the response.

Java Merging info contributors

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.

What is real: the response is the merge of independent contributors, each adding a section. What is the stand-in: the real Info builder works with Info.Builder details and the endpoint turns it into JSON.

Metrics endpoint in brief

/actuator/metrics lists metric names, and /actuator/metrics/jvm.memory.used?tag=area:heap returns one metric with its tags. Boot records JVM memory, garbage collection, threads, the HTTP server (http.server.requests), the connection pool, the cache and more through Micrometer. For dashboards you normally expose a prometheus endpoint or ship metrics to another backend instead of reading JSON by hand; counters, timers and tracing are the subject of Observability: Metrics, Tracing and Logs.

Never publish heapdump, env, configprops or loggers to the internet without authentication. A heap dump contains passwords and tokens held in memory, and a writable loggers endpoint lets anyone turn on TRACE logging that fills your disk.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which actuator endpoints are exposed over HTTP by default?

    By default only health is exposed over the web. Widen it with management.endpoints.web.exposure.include, preferably as a specific list.
  2. 2. A readiness probe depends on the database and the database goes down. What should Kubernetes do?

    Readiness controls whether the pod receives traffic. Restarting is the job of liveness, and liveness should not include external dependencies.
  3. 3. One health indicator reports DOWN while three others report UP. What is the overall status and HTTP code?

    The aggregator chooses the most severe status, and DOWN is served as 503 by default.
  4. 4. What makes a custom HealthIndicator safe to run on every probe?

    Probes run often and from many pods. A slow or hanging check makes the probe itself fail and can cause outages.
  5. 5. Why is management.endpoints.web.exposure.include=* risky on a public port?

    A wildcard publishes everything. Use an explicit list, authentication and ideally a separate management port.

Summary

  • Add spring-boot-starter-actuator to get health, info, metrics, loggers and other operational endpoints.
  • Only health is on the web by default; expose a specific list, secure it with Spring Security and consider a separate management port.
  • Health combines indicators by severity (DOWN, OUT_OF_SERVICE, UP, UNKNOWN); DOWN becomes HTTP 503.
  • Use health groups, and keep liveness internal while readiness may include real dependencies.
  • Custom HealthIndicator beans must be fast and cheap; custom InfoContributor beans add build, git and feature information.
  • Treat env, configprops, heapdump and loggers like an admin console.

Next: Observability: Metrics, Tracing and Logs.