Actuator

Key idea
Spring Boot Actuator adds operational endpoints to your application (health, info, metrics, configuration, beans, logs…). They're turned on with `spring-boot-starter-actuator`, published over HTTP or JMX according to the exposure settings and extended with your own `HealthIndicator`s, `InfoContributor`s, Micrometer metrics and `@Endpoint`s.
In the box
The box status page said "OK" even when the rowers were broken. Add Actuator, decide which endpoints to expose, write a health indicator that really checks the equipment, publish info and metrics with Micrometer and create your own endpoint.
Ops / load balancerStatusController

The load balancer sends GET /legacy/status to StatusController, highlighted in red, which answers OK no matter what.

The load balancer sends GET /actuator to the Actuator entry point, highlighted, from which the health, info and metrics endpoints hang.

Actuator and the health, info and metrics endpoints are highlighted: they're the only ones exposed over HTTP.

The health endpoint calls health() on EquipmentHealthIndicator, highlighted, which checks how many rowers work.

With the rowers broken, the health endpoint, highlighted, returns 503 DOWN to the load balancer.

The info endpoint, highlighted, asks BoxInfoContributor to contribute().

BookingService adds one to box.bookings in the MeterRegistry, both highlighted, and the metrics endpoint queries it filtering by the wod tag.

Actuator sends GET and POST to the custom boxstatus endpoint, highlighted.

Final view: Actuator with its endpoints, the custom endpoint, the health indicator, the info contributor, the MeterRegistry and, below, the rowers and BookingService.

Step 1 of 9

An "OK" that lies

The load balancer asks /legacy/status whether the instance is fine, and StatusController always answers {"status": "OK"} with a 200.

Even if the rowers break, even if the database doesn't respond, even if memory is about to run out. And there's no way to see metrics, configuration or logs without logging into the machine.

Step 2 of 9

Spring Boot Actuator

Adding spring-boot-starter-actuator brings a collection of operational endpoints under /actuator:

  • health: the state of the application and its dependencies.
  • info: arbitrary information (version, build, git…).
  • metrics: Micrometer metrics (JVM, HTTP, your own metrics).
  • env, configprops, beans, conditions, mappings, loggers (even to change levels on the fly), threaddump, heapdump, prometheus, shutdown…

GET /actuator returns a discovery page with links (_links) to the exposed endpoints.

Step 3 of 9

Enabling and exposing

Two different concepts:

  • Enabled: the endpoint exists. Almost all are; shutdown isn't.
  • Exposed: it can be reached through a technology (HTTP or JMX). Over HTTP, only health is exposed by default.
management.endpoints.web.exposure.include=health,info,metrics,boxstatus
management.endpoint.health.show-details=always

That's why, in the test, /actuator/beans answers 404: it exists, but it isn't exposed.

Step 4 of 9

A custom health indicator

/actuator/health aggregates every HealthIndicator bean: Boot brings indicators for the database, disk space, Redis… and you add your own.

EquipmentHealthIndicator looks at the rowers: with 2 or more working it returns Health.up(), otherwise Health.down(), always with the workingRowers detail.

The component is named after the bean without the suffix: equipmentHealthIndicator → equipment.

Step 5 of 9

DOWN means 503

With 6 rowers, /actuator/health answers 200 with "status": "UP" and, since show-details=always, the details of each component.

If only 1 rower is left, the indicator turns DOWN, the aggregated status turns DOWN and the HTTP response is 503 Service Unavailable. The load balancer stops sending traffic to this instance without reading the JSON.

Step 6 of 9

/actuator/info

/actuator/info gathers what the **InfoContributor**s provide:

  • BoxInfoContributor adds a box block with the name and opening time.
  • The info.* properties (info.app.name, info.app.version) appear if you enable management.info.env.enabled=true.
  • With spring-boot-maven-plugin (goal build-info) or the git plugin, also the build version and the commit.

Step 7 of 9

Metrics with Micrometer

Actuator uses Micrometer, a metrics facade (like SLF4J for logging). Boot already registers JVM, CPU, HTTP, connection pool metrics…, and you add your own through the MeterRegistry:

  • Counter: counts things (box.bookings, with the wod tag).
  • Timer: how long something takes and how often (box.booking.time).
  • Gauge: a value that goes up and down (free spots, for instance).

/actuator/metrics/box.bookings?tag=wod:Fran returns Fran's counter: 2 after two bookings.

Step 8 of 9

Your own endpoint

With @Endpoint(id = "boxstatus") you create an Actuator endpoint:

  • @ReadOperation → GET /actuator/boxstatus.
  • @WriteOperation → POST, with the parameters in a JSON body ({"rowers": 4}).
  • @DeleteOperation → DELETE.

It's technology-agnostic: the same endpoint is published over HTTP and JMX, with the same exposure and security settings as the others.

Step 9 of 9

Recap

  • spring-boot-starter-actuator → endpoints under /actuator.
  • Enabled ≠ exposed; over HTTP only health by default (management.endpoints.web.exposure.include).
  • Health: custom HealthIndicators, aggregated status, DOWN → 503, show-details.
  • Info: InfoContributor and info.* (with management.info.env.enabled).
  • Metrics: Micrometer (Counter, Timer, Gauge, tags).
  • @Endpoint + @ReadOperation/@WriteOperation/@DeleteOperation.

Cheatsheet →

Code

StatusController.java

/** Before: a hand-made status page. Always "OK", always 200, and nothing about the database or the metrics. */
@RestController
public class StatusController {
    @GetMapping("/legacy/status")
    public Map<String, String> status() {
        return Map.of("status", "OK");     // even when the rowers are broken
    }
}

ActuatorTest.java

@Test
void onlyExposedEndpointsAreReachable() throws Exception {
    mvc.perform(get("/actuator")).andExpect(jsonPath("$._links.health").exists()); // discovery page
    mvc.perform(get("/actuator/beans")).andExpect(status().isNotFound());          // exists, not exposed
    mvc.perform(get("/actuator/info"))
        .andExpect(jsonPath("$.app.name").value("spring2learn box"))              // info.* properties
        .andExpect(jsonPath("$.box.openFrom").value("06:00"));                    // InfoContributor
}

ActuatorTest.java

@Test
void onlyExposedEndpointsAreReachable() throws Exception {
    mvc.perform(get("/actuator")).andExpect(jsonPath("$._links.health").exists()); // discovery page
    mvc.perform(get("/actuator/beans")).andExpect(status().isNotFound());          // exists, not exposed
    mvc.perform(get("/actuator/info"))
        .andExpect(jsonPath("$.app.name").value("spring2learn box"))              // info.* properties
        .andExpect(jsonPath("$.box.openFrom").value("06:00"));                    // InfoContributor
}

EquipmentHealthIndicator.java

@Component                      // bean name "equipmentHealthIndicator" → component "equipment"
public class EquipmentHealthIndicator implements HealthIndicator {
    private final Equipment equipment;

    public EquipmentHealthIndicator(Equipment equipment) {
        this.equipment = equipment;
    }

    @Override
    public Health health() {
        int rowers = equipment.workingRowers();
        Health.Builder status = rowers >= 2 ? Health.up() : Health.down(); // DOWN → HTTP 503
        return status.withDetail("workingRowers", rowers).build();
    }
}

ActuatorTest.java

@Test
void healthAggregatesEveryIndicator() throws Exception {
    mvc.perform(get("/actuator/health"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.status").value("UP"))
        .andExpect(jsonPath("$.components.equipment.details.workingRowers").value(6));

    equipment.setWorkingRowers(1);
    mvc.perform(get("/actuator/health"))
        .andExpect(status().isServiceUnavailable())                // DOWN → 503 for load balancers
        .andExpect(jsonPath("$.status").value("DOWN"));
}

BoxInfoContributor.java

@Component
public class BoxInfoContributor implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("box", Map.of("name", "CrossFit Norte", "openFrom", "06:00"));
    }
}

BookingService.java

@Service
public class BookingService {
    private final MeterRegistry registry;   // Micrometer: the metrics facade
    private final Timer bookingTime;

    public BookingService(MeterRegistry registry) {
        this.registry = registry;
        this.bookingTime = Timer.builder("box.booking.time").register(registry);
    }

    public String book(String athlete, String wod) {
        return bookingTime.record(() -> {
            Counter.builder("box.bookings").tag("wod", wod)  // one counter per tag value
                .register(registry).increment();
            return athlete + " → " + wod;
        });
    }
}

BoxStatusEndpoint.java

@Component
@Endpoint(id = "boxstatus")                  // /actuator/boxstatus (once exposed) and JMX
public class BoxStatusEndpoint {
    private final Equipment equipment;

    public BoxStatusEndpoint(Equipment equipment) {
        this.equipment = equipment;
    }

    @ReadOperation                           // HTTP GET
    public Map<String, Integer> status() {
        return Map.of("workingRowers", equipment.workingRowers());
    }

    @WriteOperation                          // HTTP POST, JSON body {"rowers": 4}
    public void rowers(int rowers) {
        equipment.setWorkingRowers(rowers);
    }
}

EquipmentHealthIndicator.java

@Component                      // bean name "equipmentHealthIndicator" → component "equipment"
public class EquipmentHealthIndicator implements HealthIndicator {
    private final Equipment equipment;

    public EquipmentHealthIndicator(Equipment equipment) {
        this.equipment = equipment;
    }

    @Override
    public Health health() {
        int rowers = equipment.workingRowers();
        Health.Builder status = rowers >= 2 ? Health.up() : Health.down(); // DOWN → HTTP 503
        return status.withDetail("workingRowers", rowers).build();
    }
}

Quiz

1. You add spring-boot-starter-actuator with no other configuration. Which endpoint answers over HTTP?

2. A custom HealthIndicator returns Health.down(). What does /actuator/health answer?

3. You set info.app.name=box in application.properties, but /actuator/info is empty. What's missing?

4. What does Counter.builder("box.bookings").tag("wod", wod).register(registry).increment() do?

5. Which annotations create your own Actuator endpoint with read and write operations?

6. /actuator/beans answers 404 even though the endpoint exists. Why?

Cheatsheet → · Mock exam →

Run it