Video in progress

Middle 🌱 Spring

How do you write your own HealthIndicator, and when is it useful?

You create a bean that implements the HealthIndicator interface and return Health.up() or Health.down() from the health() method; its name is added to /actuator/health automatically. It's useful for showing a dependency on an external system, but you have to wire it into readiness carefully.

📖 Answer

Say the service depends on a payment provider and you want to see problems with it in monitoring.

@Component("paymentGateway")
class PaymentGatewayHealth implements HealthIndicator {

    private final PaymentClient client;

    PaymentGatewayHealth(PaymentClient client) { this.client = client; }

    @Override
    public Health health() {
        try {
            Duration javob = client.ping(); // with a 1-2 second timeout
            return Health.up().withDetail("latencyMs", javob.toMillis()).build();
        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}

/actuator/health now shows the paymentGateway component too, and if it's DOWN, the overall status is DOWN as well.

You have to be careful here:

  • Cascade. If this indicator is wired into the Kubernetes liveness or readiness probe, when the provider goes down all your pods are declared "sick" and pulled out of traffic. You usually don't add external systems to the probe groups.
  • Slow check. health() is called on every request; keep the timeout short or cache the result for a few seconds.
  • For a non-critical system, you can use your own status (Status("DEGRADED")) instead of DOWN.

Groups are configured like management.endpoint.health.group.readiness.include=db,redis.