Video in progress

How do you write your own health indicator, and what should you watch out for?

You write a bean that implements the HealthIndicator interface and return Health.up() or Health.down(). The check must be fast and have a timeout, otherwise the health endpoint itself slows down and the probes fail.

📖 Answer

Say the service depends on an external payment gateway:

@Component
public class PaymentGatewayHealthIndicator implements HealthIndicator {

    private final PaymentGatewayClient client;

    public PaymentGatewayHealthIndicator(PaymentGatewayClient client) {
        this.client = client;
    }

    @Override
    public Health health() {
        try {
            long ms = client.ping(Duration.ofSeconds(1)); // short timeout
            return Health.up().withDetail("latencyMs", ms).build();
        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}

The HealthIndicator suffix is dropped from the bean name, and the component shows up in /actuator/health as paymentGateway.

Things to watch out for:

  • Without a timeout, when the gateway hangs the health request hangs too, and the Kubernetes probe times out.
  • Every probe hits the external service. 30 pods every 5 seconds is load too. You can cache the result for a short time.
  • If an optional dependency (say the recommendations service) goes down, is it right to mark the whole application DOWN? Often not. Take it out of the health groups or show it for information only.

In reactive applications the same thing is done with ReactiveHealthIndicator.