Custom Health Checks with Spring Boot Actuator
How to implement custom health indicators with Spring Boot Actuator, including database, Redis, external API checks, and Kubernetes readiness probes.
Overview
A payment pod once got restarted twelve times in an hour because its health check depended on a third-party API that was slow — not down, just slow. Kubernetes timed out, declared the pod dead, and killed it. The pod was fine. This is the kind of bug HealthIndicator exists to prevent, and the kind you create when you wire one up carelessly.
Spring Boot Actuator ships a /actuator/health endpoint that reports the application’s health as a JSON document. Out of the box it checks built-in indicators (database, disk space, ping). You register additional HealthIndicator beans to check whatever matters to your service (an external API, a cache connection, queue depth) and Kubernetes reads the same endpoint to decide whether to restart your pod or route traffic to it.
A typical response looks like this:
{
"status": "UP",
"components": {
"db": { "status": "UP" },
"redis": { "status": "UP", "details": { "ping": "PONG" } },
"paymentGateway": {
"status": "UP",
"details": { "provider": "stripe", "latency_ms": 42 }
},
"diskSpace": { "status": "UP" },
"livenessState": { "status": "UP" },
"readinessState": { "status": "UP" }
}
}
When to Use
- Kubernetes liveness and readiness probes — tell the orchestrator when to restart the pod or pull it out of the service rotation
- Monitoring external dependencies your service can’t work without (payment gateway, SMS provider, third-party API)
- Checking resource availability (cache, message queue, file storage)
- Building a status page that aggregates several service health checks
- Detecting degraded states early enough to alert before they become full outages
When NOT to Use
- Simple scripts or CLI tools — health checks exist for long-running services that something else supervises
- Applications with no orchestrator or load balancer — if nothing reads the endpoint, each probe burns CPU for nobody
- As a metrics replacement — health is binary (UP/DOWN). For gradual degradation signals, use Micrometer instead
Solution
Setup
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Enable the health endpoint
# application.yml
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: always
show-components: always
Open http://localhost:8080/actuator/health and you’ll see the aggregated JSON above. Keep show-details: always off in production — more on that in Best Practices.
Basic custom health indicator
Every indicator is a plain @Component: it exposes a health() method through the HealthIndicator interface. Actuator collects all of them, calls health(), and merges the results under the bean’s name (paymentGateway for PaymentGatewayHealthIndicator).
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 PaymentGatewayClient client;
public PaymentGatewayHealthIndicator(PaymentGatewayClient client) {
this.client = client;
}
@Override
public Health health() {
try {
PaymentGatewayStatus status = client.ping();
if (status.isAvailable()) {
return Health.up()
.withDetail("provider", "stripe")
.withDetail("latency_ms", status.getLatencyMs())
.withDetail("version", status.getVersion())
.build();
}
return Health.down()
.withDetail("reason", "Gateway returned unavailable")
.withDetail("status_code", status.getStatusCode())
.build();
} catch (Exception e) {
return Health.down(e)
.withDetail("error", e.getMessage())
.build();
}
}
}
Database health indicator with a custom query
The built-in DataSourceHealthIndicator already runs SELECT 1, so a custom version only pays off when you want richer details — like the connection count from pg_stat_activity here:
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
private final JdbcTemplate jdbcTemplate;
public DatabaseHealthIndicator(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Health health() {
try {
Integer result = jdbcTemplate.queryForObject("SELECT 1", Integer.class);
int activeConnections = jdbcTemplate.queryForObject(
"SELECT count(*) FROM pg_stat_activity WHERE state = 'active'",
Integer.class
);
return Health.up()
.withDetail("database", "postgresql")
.withDetail("active_connections", activeConnections)
.withDetail("max_connections", 100)
.build();
} catch (Exception e) {
return Health.down(e)
.withDetail("database", "postgresql")
.withDetail("error", "Connection failed")
.build();
}
}
}
Redis health indicator
The point most people miss: getConnection() borrows a connection you must return. Wrap it in try-with-resources or every probe leaks one.
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisHealthIndicator implements HealthIndicator {
private final RedisConnectionFactory connectionFactory;
private final RedisTemplate<String, String> redisTemplate;
public RedisHealthIndicator(RedisConnectionFactory connectionFactory,
RedisTemplate<String, String> redisTemplate) {
this.connectionFactory = connectionFactory;
this.redisTemplate = redisTemplate;
}
@Override
public Health health() {
try (RedisConnection connection = connectionFactory.getConnection()) {
String pong = connection.ping();
long latency = measureLatency();
return Health.up()
.withDetail("redis", "connected")
.withDetail("ping", pong)
.withDetail("latency_ms", latency)
.build();
} catch (Exception e) {
return Health.down(e)
.withDetail("redis", "disconnected")
.build();
}
}
private long measureLatency() {
long start = System.currentTimeMillis();
redisTemplate.opsForValue().get("health-check-key");
return System.currentTimeMillis() - start;
}
}
External API health indicator with timeout
A health check without a timeout is a denial-of-service against yourself: Kubernetes calls the probe on an interval, and if the external API hangs, the endpoint hangs and the pod gets killed. Two timeouts here — connect and total request.
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
@Component
public class ExternalApiHealthIndicator implements HealthIndicator {
private static final String HEALTH_URL = "https://api.example.com/health";
private final HttpClient httpClient;
public ExternalApiHealthIndicator() {
this.httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
}
@Override
public Health health() {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(HEALTH_URL))
.timeout(Duration.ofSeconds(3))
.GET()
.build();
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() == 200) {
return Health.up()
.withDetail("url", HEALTH_URL)
.withDetail("status_code", response.statusCode())
.build();
}
return Health.down()
.withDetail("url", HEALTH_URL)
.withDetail("status_code", response.statusCode())
.withDetail("reason", "Non-200 response")
.build();
} catch (Exception e) {
return Health.down(e)
.withDetail("url", HEALTH_URL)
.withDetail("error", "Connection timeout or failure")
.build();
}
}
}
Queue depth health indicator
Useful pattern for “degraded but alive”: report UP with a warning detail when depth approaches the threshold, and DOWN only once it’s exceeded.
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class QueueDepthHealthIndicator implements HealthIndicator {
private static final int THRESHOLD = 1000;
private final MessageQueueService queueService;
public QueueDepthHealthIndicator(MessageQueueService queueService) {
this.queueService = queueService;
}
@Override
public Health health() {
int depth = queueService.getQueueDepth("order-processing");
Map<String, Object> details = new HashMap<>();
details.put("queue", "order-processing");
details.put("depth", depth);
details.put("threshold", THRESHOLD);
if (depth < THRESHOLD * 0.8) {
return Health.up().withDetails(details).build();
}
if (depth < THRESHOLD) {
return Health.up().withDetails(details)
.withDetail("warning", "Queue depth approaching threshold").build();
}
return Health.down().withDetails(details)
.withDetail("error", "Queue depth exceeded threshold").build();
}
}
Custom health groups
Health groups are declared in configuration — there’s no annotation for this. Each group becomes its own endpoint (/actuator/health/{group}) and only aggregates the indicators you list:
management:
endpoint:
health:
group:
infrastructure:
include: db,redis
external:
include: paymentGateway,externalApi
The include list takes indicator names: the bean name minus the HealthIndicator suffix. db is the built-in datasource indicator; paymentGateway and externalApi are the custom beans above. Now /actuator/health/infrastructure answers “are my internal dependencies alive” while /actuator/health/external answers “can I reach third parties” — different questions that deserve different answers.
Kubernetes liveness and readiness probes
Spring Boot 2.3+ exposes two built-in groups with a single property:
management:
endpoint:
health:
probes:
enabled: true
This gives you /actuator/health/liveness and /actuator/health/readiness. Point the Kubernetes probes at them:
# kubernetes deployment
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 3
Reacting to availability changes with ApplicationAvailability
When your code needs to know its own state (for example, to stop accepting jobs), inject ApplicationAvailability to read it, and ApplicationEventPublisher to change it:
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.LivenessState;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
@Service
public class AvailabilityService {
private final ApplicationAvailability availability;
private final ApplicationEventPublisher publisher;
public AvailabilityService(ApplicationAvailability availability,
ApplicationEventPublisher publisher) {
this.availability = availability;
this.publisher = publisher;
}
@EventListener
public void onLivenessChange(AvailabilityChangeEvent<LivenessState> event) {
// e.g. stop background work while Kubernetes restarts us
}
@EventListener
public void onReadinessChange(AvailabilityChangeEvent<ReadinessState> event) {
// e.g. pause consuming from the queue while unready
}
public void markUnready() {
AvailabilityChangeEvent.publish(
publisher, this, ReadinessState.REFUSING_TRAFFIC
);
}
}
markUnready() is how you gracefully drain the pod: Kubernetes still sees it as alive, but the readiness endpoint flips to OUT_OF_SERVICE and traffic stops flowing while you finish in-flight work.
Explanation
How the aggregate status is computed
Actuator asks every registered indicator for a Health object and combines them with a status aggregator. The default rule is simple: the worst status wins. DOWN beats OUT_OF_SERVICE, which beats UP, which beats UNKNOWN. One failing indicator flips the whole endpoint to DOWN — which is exactly why a flaky non-critical dependency should never return DOWN in the first place.
The overall status maps to HTTP: UP returns 200; DOWN and OUT_OF_SERVICE return 503. Kubernetes interprets a non-2xx response or a timeout the same way (probe failure), so a slow check and a failing check are indistinguishable to it.
Why liveness and readiness are separate groups
probes.enabled: true creates two groups: liveness contains only LivenessStateIndicator, readiness contains only ReadinessStateIndicator. Both read ApplicationAvailability — an in-memory state object — so they answer instantly without touching your database, your cache, or anything on the network.
That’s the entire trick. If your custom indicators ran inside the liveness group, a dead Redis would mean “restart the pod,” and a pod restarted because Redis is down comes back to find Redis still down — a restart loop. Keep expensive checks out of liveness; if you want one in readiness, add it to the group explicitly:
management:
endpoint:
health:
group:
readiness:
include: readinessState,db,redis
The cost model nobody thinks about
Kubernetes calls each probe on its own interval — typically every 5-10 seconds, from every kubelet that runs your pods. An external API check inside a health indicator is therefore an outbound request every few seconds, forever. Multiply by replicas. Either cache the result for a few seconds, or accept that your “health check” is a recurring paid API call.
Variants
Reactive indicator for Spring WebFlux
On a reactive stack, implement ReactiveHealthIndicator and return a Mono<Health> instead of blocking:
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.ReactiveHealthIndicator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Component
public class ReactiveApiHealthIndicator implements ReactiveHealthIndicator {
private final WebClient webClient = WebClient.create("https://api.example.com");
@Override
public Mono<Health> health() {
return checkExternalApi()
.map(status -> Health.up().withDetail("status", status).build())
.onErrorResume(e -> Mono.just(
Health.down(e).withDetail("error", e.getMessage()).build()
));
}
private Mono<String> checkExternalApi() {
return webClient.get()
.uri("/health")
.retrieve()
.bodyToMono(String.class);
}
}
Disabling specific built-in indicators
If a built-in check doesn’t apply (no disk-space concerns, Redis managed elsewhere):
management:
health:
db:
enabled: false
redis:
enabled: false
diskspace:
enabled: false
Best Practices
- For the metrics side of observability, see Expose Metrics with Micrometer and Prometheus — health checks answer “is it broken”, metrics answer “how broken and since when”. For the architectural view of what to expose, the Health Check Pattern covers which signals belong in each probe.
- Set timeouts on every external check — a hanging health check blocks the endpoint, and Kubernetes treats a timeout exactly like a DOWN.
- Use health groups to separate infrastructure checks from external API checks, so a dead third party doesn’t hide a dead database.
- Return
DOWNonly when the service genuinely can’t function — degraded performance deserves a warning detail, not a restart. - Include useful details (latency, connection count, queue depth) — operators need that context to diagnose what the status page can’t tell them.
- Keep liveness cheap. It should read
ApplicationAvailabilityand nothing else; a liveness probe that does I/O turns dependency blips into restart loops. - Cache external check results for a few seconds — calling a paid API on every probe request is wasteful and slow.
- Use
show-details: when-authorizedin production —alwaysleaks database URLs, connection counts, and internal architecture to anyone who can reach the endpoint.
Common Mistakes
- No timeout on external checks: a slow external API makes the health endpoint hang; Kubernetes times out and kills a healthy pod.
- Returning DOWN for non-critical dependencies: if the analytics service is down but the core app works, report UP with a warning detail — otherwise one vendor outage takes your whole fleet down with it.
- Checking too many things in one indicator: each indicator should check exactly one dependency. Split them, then organize with health groups.
- Not caching expensive results: the probe fires every 5-10 seconds per kubelet. External API checks should be cached for at least that long.
- Exposing full details publicly:
show-details: alwaysleaks database URLs, connection counts, and internal architecture. Usewhen-authorizedin production. - Putting dependency checks in the liveness group: liveness answers “is the JVM alive”, not “are my dependencies up”. A database check there turns a DB outage into a restart storm.
See Also
- Health Check Pattern — the architectural side: which signals to expose, graceful degradation, and probe design.
- Health Check Endpoint — building a health endpoint from scratch when you aren’t on Spring Boot.
- Companion code: runnable Spring Boot project with all the indicators from this recipe at the companion repo.
Further Reading
- Spring Boot Actuator: Health endpoints — groups, probes, status mapping, and the full property reference.
- Kubernetes: Configure Liveness, Readiness and Startup Probes — probe fields, timing, and failure semantics.
Frequently Asked Questions
What is the difference between liveness and readiness probes?
Liveness tells Kubernetes whether to restart the pod. Readiness tells Kubernetes whether to route traffic to the pod. A pod can be live (running) but not ready (still warming its cache or waiting for a dependency), and it should sit out of rotation instead of being killed.
How do I disable all health checks except ping?
management:
health:
defaults:
enabled: false
ping:
enabled: true
Can I return a custom HTTP status code?
Yes. Configure status mapping:
management:
endpoint:
health:
status:
http-mapping:
down: 503
out-of-service: 503
warning: 200
How do I add a custom status level?
Register a Status and return it from a regular component — @HealthIndicator isn't a real annotation, @Component is what registers the bean:
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;
@Component
public class CustomStatusIndicator implements HealthIndicator {
private static final Status DEGRADED = new Status("DEGRADED", "Performance is degraded");
@Override
public Health health() {
if (isDegraded()) {
return Health.status(DEGRADED).build();
}
return Health.up().build();
}
}
Note that custom statuses map to HTTP 200 by default — configure http-mapping if you need 503 for yours.
Should I check the database in liveness or readiness?
Readiness. If the database is temporarily unavailable, the pod shouldn't restart — it should just stop receiving traffic. Liveness should only fail when the application itself is stuck: deadlock, hung thread, broken internal state.
Related Resources
Expose Metrics with Micrometer and Prometheus
How to expose custom application metrics using Micrometer and Prometheus in Spring Boot, including counters, gauges, timers, and histograms.
PatternHealth Check Pattern: Expose Liveness and Readiness Probes
Implement liveness and readiness probes for container orchestrators. Covers Kubernetes probe config, dependency checks, and graceful degradation.
RecipeExpose Business Metrics with Prometheus
How to expose custom business metrics in Python using prometheus_client, including counters, gauges, histograms, summaries, and Flask integration.
RecipeStructured JSON Logging with structlog
How to emit structured JSON logs in Python using structlog, including context binding, log levels, processors, and integration with standard logging.