Sub topic 5
Health endpoints with Actuator
This chapter assumes you can build a Spring Boot application with Maven or Gradle and run its JAR with java -jar. It also assumes you know basic HTTP status codes. Health endpoints let a process manager, load balancer, or Kubernetes ask the running application whether it is alive and whether it can take traffic. You use them to make restarts and rollouts safe.
Adding Actuator
Spring Boot Actuator is a module that exposes operational endpoints over HTTP. Add the starter to your build.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>In Gradle, the equivalent line is implementation 'org.springframework.boot:spring-boot-starter-actuator'.
Actuator exposes few endpoints over HTTP by default. In current Spring Boot versions only health is exposed, under the base path /actuator. Start the application and call it:
curl -i http://localhost:8080/actuator/healthHTTP/1.1 200
Content-Type: application/vnd.spring-boot.actuator.v3+json
{"status":"UP"}The response status code carries the result. UP returns HTTP 200. DOWN and OUT_OF_SERVICE return HTTP 503. UNKNOWN returns 200. Load balancers and Kubernetes probes look at the status code, not the body.
How the overall status is computed
The /actuator/health endpoint is an aggregate. Spring Boot auto-configures one health indicator for each supported dependency it finds on the classpath. A DataSource gets a db indicator, Redis gets a redis indicator, and so on. A diskSpace indicator and a ping indicator are always present. Each indicator reports a status, and the aggregate takes the most severe one. The default severity order is DOWN, OUT_OF_SERVICE, UP, UNKNOWN.
By default, the endpoint hides the per-component breakdown. This is intentional, because details can reveal your infrastructure. To see them during development, set:
management.endpoint.health.show-details=always
management.endpoint.health.show-components=alwaysThe safer production value is when-authorized, which shows details only to authenticated users with an allowed role. The response then looks like this:
{
"status": "UP",
"components": {
"db": { "status": "UP", "details": { "database": "PostgreSQL" } },
"diskSpace": { "status": "UP" },
"ping": { "status": "UP" }
}
}Liveness and readiness probes
A single "healthy or not" answer is not enough in an orchestrated environment. Two different questions need different answers:
- Liveness: is the process in a state it cannot recover from? If yes, restart it.
- Readiness: can the process serve requests right now? If no, stop sending it traffic, but do not restart it.
Spring Boot models these as two availability states. LivenessState is CORRECT or BROKEN. ReadinessState is ACCEPTING_TRAFFIC or REFUSING_TRAFFIC. Enable the probe endpoints with the setting from this tutorial's packaged configuration:
management.endpoint.health.probes.enabled=true
management.endpoints.web.exposure.include=health,infoThis adds two sub-paths of the health endpoint:
| Path | Backing state | Success | Failure |
|---|---|---|---|
| `/actuator/health/liveness` | `LivenessState` | 200 `UP` | 503 `DOWN` |
| `/actuator/health/readiness` | `ReadinessState` | 200 `UP` | 503 `DOWN` |
Spring Boot enables probes automatically when it detects it is running on Kubernetes. Setting the property explicitly makes the behavior the same on a VM, in Docker, or on your laptop, which is useful when you test the packaged JAR locally.
Readiness changes during the application lifecycle. It reports REFUSING_TRAFFIC while the application context starts. It switches to ACCEPTING_TRAFFIC once startup, including any ApplicationRunner and CommandLineRunner beans, has finished. When the application receives a shutdown signal, it switches back to REFUSING_TRAFFIC before the web server stops. That ordering gives a load balancer time to drain the instance. The next chapter builds on this behavior.
What belongs in each probe
By default, the liveness group contains only livenessState, and the readiness group contains only readinessState. Neither includes db or other external checks. This default is deliberate.
Readiness is the right place for dependencies the instance cannot work without. You can add them with a health group:
management.endpoint.health.group.readiness.include=readinessState,dbWith this setting, an instance whose database connection fails reports DOWN on /actuator/health/readiness. The load balancer takes that instance out of rotation, and the instance keeps running and recovers when the database returns.
Think about the cost of this choice. If a shared dependency such as the database is down for every instance, every instance leaves rotation, and the whole service answers 503. That may be what you want if the application cannot do useful work without the database. If the application can serve partial results, such as cached reads, leave the dependency out of readiness and handle the failure in application code.
Writing a custom health indicator
Implement HealthIndicator to report on something Spring Boot does not know about. Register the class as a bean.
import java.net.InetSocketAddress;
import java.net.Socket;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class PaymentGatewayHealthIndicator implements HealthIndicator {
private static final String HOST = "payments.example.com";
@Override
public Health health() {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(HOST, 443), 500);
return Health.up().withDetail("host", HOST).build();
} catch (Exception e) {
return Health.down(e).withDetail("host", HOST).build();
}
}
}Spring Boot derives the component name from the bean name by removing the HealthIndicator suffix and lowercasing the first letter. This bean appears as paymentGateway in the components section.
Keep these rules in mind for custom indicators:
- Keep them fast. The probe request waits for every indicator in the group. A 500 ms connect timeout, as above, keeps a slow dependency from stalling the probe.
- Set timeouts on every call. A hung check can cause the orchestrator's probe to time out, which counts as a failure.
- Add the indicator to a group only when it should affect that probe. A new indicator is part of the main
/actuator/healthaggregate automatically, but it is not part of the readiness group unless you include it.
Using the probes in Kubernetes
Kubernetes calls the probe paths and acts on the status code. A container fragment from a Deployment looks like this:
containers:
- name: myapp
image: myorg/myapp:1.0.0
ports:
- containerPort: 8080
startupProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
periodSeconds: 5
failureThreshold: 30
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
periodSeconds: 10
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
periodSeconds: 5The startup probe gives a slow JVM up to 150 seconds (30 failures at 5-second intervals) to start. The liveness and readiness probes do not begin until it succeeds. Without a startup probe, a liveness probe with a short delay can kill an application that is still starting. Chapter 12 covers the full Deployment.
Securing and isolating the endpoints
Health endpoints are open by default, and probes cannot authenticate. Follow these practices:
- Expose only what you need.
management.endpoints.web.exposure.include=health,infois enough for most services. Do not use*in production. - Keep
show-detailsatneverorwhen-authorizedfor any endpoint reachable from outside the cluster. - Optionally move management traffic to a separate port with
management.server.port=9090. The probes then use that port, and you can block it at the firewall or ingress. If you do this, updateportin the Kubernetes probes. - If Spring Security is on the classpath, allow the probe paths without authentication, for example by permitting
/actuator/health/**in your security filter chain. Otherwise the probes receive 401 responses and the pod never becomes ready.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `/actuator/health` returns 404 | Actuator is missing from the classpath, or `health` is not in the exposure list | Add the starter, and set `management.endpoints.web.exposure.include=health` |
| `/actuator/health/liveness` returns 404 | Probes are not enabled outside Kubernetes | Set `management.endpoint.health.probes.enabled=true` |
| Response is only `{"status":"UP"}` | `show-details` defaults to `never` | Set `show-details=when-authorized` and authenticate |
| Probe gets 401 or 403 | Spring Security blocks the path | Permit the health paths in the security configuration |
| All pods restart when the database fails | Database check is in the liveness group | Remove it from liveness and put it in readiness |
| Pod killed during startup | No startup probe, and liveness starts too early | Add a startup probe, or lengthen `initialDelaySeconds` |
Exercise
Your application depends on a PostgreSQL database. During a database outage, Kubernetes restarts all pods repeatedly, and the outage lasts longer than the database failure itself. What configuration mistake most likely caused this, and how do you fix it?
Show answer
The db health indicator was probably added to the liveness group, so the liveness probe returned 503 on every instance whenever the database was unreachable, and Kubernetes restarted them all. Restarting does not fix a database outage, and it adds startup load. Remove db from the liveness group, which should contain only livenessState. If the instances cannot serve requests without the database, add db to the readiness group with management.endpoint.health.group.readiness.include=readinessState,db. Instances then leave the load balancer rotation but keep running, and they return when the database recovers.
Exercise
You enable probes and call /actuator/health/readiness on a laptop, but it returns 404. The same JAR works in a Kubernetes cluster. Why, and what setting makes the behavior consistent?
Show answer
Spring Boot enables the probe endpoints automatically only when it detects a Kubernetes environment. On a laptop it does not, so the sub-paths do not exist. Set management.endpoint.health.probes.enabled=true in the packaged configuration. Also check that health is included in management.endpoints.web.exposure.include.