Search code examples
javaspringspring-bootspring-boot-actuatorhealth-monitoring

Add and remove Spring Boot health checks dynamically


I am working on a Spring Boot-based application where domain-specific tasks are added and removed dynamically via an API. As those jobs can fail individually, I would like to add HealthIndicators for each job while they are running and remove them afterwards. The Spring Actuator's health endpoint is already integrated into several monitors and this would just push this information downstream.

I could of course aggregate the health checks of all jobs into one HealthIndicator bean but I would prefer if the health of all checks was listed somehow. The HealthIndicator does however only allow to return a single Health instance. Is there a way to return a collection of such objects?


Solution

  • Spring Boot 2.1 introduced a HealthIndicatorRegistry for this purpose. Whenever the health endpoint is queried, the registry is asked for a snapshot of all registered health indicators and each of those indicators is then called to determine the application's health.

    The registry is available as a bean so can be injected into your class that manages the domain-specific tasks. It could then call register(String, HealthIndicator) and unregister(String) as those tasks are added and removed.