Sub topic 4
Writing a custom health indicator
This chapter assumes you have a Spring Boot application with spring-boot-starter-actuator on the classpath. It also assumes you know how to expose endpoints in application.yml and how to read the /actuator/health response. Spring Security is not needed here.
Why write your own indicator
Spring Boot registers health indicators for the things it can detect, such as the database DataSource, disk space, and Redis. It cannot know about your payment provider, an internal REST service, or a licence server. A custom HealthIndicator lets the health endpoint report on those dependencies.
The endpoint combines every HealthIndicator bean into one result. Each bean becomes a named component in the response. If you add a bean, it appears automatically. You do not register it anywhere else.
The HealthIndicator contract
HealthIndicator is an interface with one method, health(), which returns a Health object. A Health has two parts:
- A status, such as
UP,DOWN,OUT_OF_SERVICE, orUNKNOWN. - An optional map of details, which are key-value pairs that explain the status.
You create a Health with a builder. Health.up(), Health.down(), and Health.status("NAME") start the builder. withDetail(key, value) adds a detail, and build() finishes it. Health.down(exception) records the exception class and message under the error key.
A first indicator
The example below checks a payment gateway. PaymentClient is a hypothetical client for an external service, so replace it with your own.
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 final PaymentClient client; // hypothetical client for an external service
public PaymentGatewayHealthIndicator(PaymentClient client) {
this.client = client;
}
@Override
public Health health() {
try {
client.ping();
return Health.up().withDetail("gateway", "reachable").build();
} catch (Exception ex) {
return Health.down(ex).build();
}
}
}How the name is derived
Spring Boot takes the bean name and removes the HealthIndicator or HealthContributor suffix. The class PaymentGatewayHealthIndicator is registered as the bean paymentGatewayHealthIndicator, so the component name is paymentGateway. Renaming the class changes the key in the JSON, and that can break dashboards or alerts that read it. You can set the name yourself with @Component("paymentGatewayHealthIndicator") if you need it to stay stable.
What the response looks like
With management.endpoint.health.show-details set to always (or when-authorized and a logged-in authorized user), a failing gateway produces this:
{
"status": "DOWN",
"components": {
"paymentGateway": {
"status": "DOWN",
"details": {
"error": "java.net.ConnectException: Connection refused"
}
}
}
}Without details permission, callers see only {"status":"DOWN"}. The default for show-details is never, so you will see the short form until you change it.
How statuses are aggregated
The top-level status is not an average. A StatusAggregator picks one status from all components by using a severity order. The default order, from most severe to least, is:
DOWNOUT_OF_SERVICEUPUNKNOWN
One DOWN component makes the whole result DOWN. By default, a DOWN result returns HTTP 503, and UP returns 200. Load balancers and orchestrators usually read that status code, not the JSON body.
You can change the order or the HTTP mapping with properties. For example, this makes a custom status count as a failure for HTTP purposes:
management:
endpoint:
health:
status:
order: DOWN,OUT_OF_SERVICE,DEGRADED,UP,UNKNOWN
http-mapping:
DEGRADED: 200Here DEGRADED is a custom status. It ranks above UP, so it wins during aggregation, but the endpoint still returns 200.
Returning a custom status
When the dependency is partly available, UP and DOWN are too coarse. Use Health.status(...) with your own name:
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class QueueHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int backlog = currentBacklog();
if (backlog > 10_000) {
return Health.status("DEGRADED")
.withDetail("backlog", backlog)
.build();
}
return Health.up().withDetail("backlog", backlog).build();
}
private int currentBacklog() {
return 42; // replace with a real measurement
}
}If you use a custom status, add it to status.order, as shown above. A status that is missing from the order is ranked lowest, so it is overridden by any other status, and it may not behave the way you expect.
AbstractHealthIndicator
AbstractHealthIndicator handles the try/catch for you. You override doHealthCheck(Health.Builder builder). If it throws, the base class returns DOWN with the exception details and logs a warning.
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;
@Component
public class LicenseServerHealthIndicator extends AbstractHealthIndicator {
public LicenseServerHealthIndicator() {
super("License server check failed");
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
boolean valid = checkLicense();
if (valid) {
builder.up().withDetail("license", "valid");
} else {
builder.down().withDetail("license", "expired");
}
}
private boolean checkLicense() {
return true; // replace with a real call
}
}The string passed to super(...) is the message used in the warning log when the check throws.
Edge cases and failure modes
Health checks run on a real request thread, often every few seconds, and from several callers at once. These points matter in production.
Timeouts
A check that hangs makes the health endpoint hang. A probe that waits for a response will then time out and may restart your pod. Always set a connect and read timeout on the client you use in the indicator. A health check should fail fast.
Cost and frequency
Do not run expensive work in health(). A Kubernetes probe, a load balancer, and a monitoring system might each call the endpoint every 5 to 10 seconds. If each call runs a heavy query, you create load yourself. Options include:
- Run the check on a schedule and have
health()return the cached result. - Use a lightweight call, such as a ping or
SELECT 1, instead of a real business query. - Set
management.endpoint.health.cache.time-to-live, which caches the result of the individual endpoint for that duration. Check your Boot version, because the cache setting applies to the endpoint's read operation.
Should a dependency make you DOWN?
Decide what a failure means. If an optional dependency such as a recommendation service fails, and the application can work without it, marking the whole application DOWN may cause a load balancer to remove healthy instances. In the worst case, every instance fails the same external check, and all of them are removed together. For optional dependencies, report a custom status such as DEGRADED mapped to HTTP 200, or exclude the indicator from the groups used by probes. The next chapter covers groups.
Reactive applications
In a WebFlux application, use ReactiveHealthIndicator, which returns Mono<Health>. A blocking HealthIndicator still works in many cases, because Boot adapts it, but blocking calls on an event-loop thread are a bug. Prefer the reactive form for reactive clients.
Details and sensitive data
Details are shown to anyone who is allowed to see them. Do not put connection strings, credentials, or internal host names in withDetail. Exception messages can also leak these, since Health.down(ex) copies the message into the response. If that is a concern, use Health.down().withDetail("error", "unreachable") instead.
Disabling an indicator and testing one
You can turn off a built-in indicator by property. This is useful when a default check does not fit your setup:
management:
health:
redis:
enabled: falseCustom indicators are plain classes, so you can test them without starting Spring. This test uses JUnit 5 and Mockito:
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.health.Status;
class PaymentGatewayHealthIndicatorTest {
@Test
void reportsDownWhenPingFails() {
PaymentClient client = mock(PaymentClient.class);
doThrow(new IllegalStateException("timeout")).when(client).ping();
var health = new PaymentGatewayHealthIndicator(client).health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails()).containsKey("error");
}
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The component is missing from the response | The class is not a Spring bean, or details are hidden | Add `@Component` and set `show-details` |
| The key has an unexpected name | The name comes from the bean name minus the suffix | Rename the bean explicitly |
| The endpoint returns 200 while a component is DOWN | A custom `http-mapping` or a non-default status order | Review `status.order` and `http-mapping` |
| The endpoint is slow or times out | The check has no client timeout | Set timeouts and cache results |
| A custom status never wins | It is not listed in `status.order` | Add it to the order |
Exercise
Your class is named InventoryServiceHealthIndicator. What name will its component have in the health response, and what would you do if the optional inventory service goes down but you do not want load balancers to remove the instance?
Show answer
The component name is inventoryService, because Boot removes the HealthIndicator suffix from the bean name. For an optional dependency, return a custom status such as DEGRADED instead of DOWN. Add it to management.endpoint.health.status.order and map it to HTTP 200 with management.endpoint.health.status.http-mapping.DEGRADED: 200. Alternatively, keep the indicator out of the health group used by the load balancer.
Exercise
Why should health() set timeouts on its client, and why should it avoid heavy queries?
Show answer
The health endpoint waits for every indicator. A hanging check makes the whole endpoint hang, which can make a probe time out and trigger a restart. Heavy queries run on every call, and probes and monitors call the endpoint often, so the checks add their own load to the dependency.