Spring Boot Actuator and Health Checks You Can Trust in Production
Spring Boot in Production · Part 2 of 17
- #Java
- #Spring Boot
- #production
- #actuator
- #kubernetes
A health check has one job: tell the platform whether this instance should
get traffic, and whether it should be restarted. The default Spring Boot
Actuator health endpoint answers a slightly different question. It tells
you whether the things Spring Boot knows about are reachable: the database,
the disk, maybe Redis. It knows nothing about the queue consumer thread that
died ten minutes ago. So the endpoint says UP, the load balancer keeps
sending requests, and orders pile up in a queue nobody is reading.
This is Part 2 of Spring Boot in Production. In Part 1 you made bad configuration stop the app at startup. This part is about what happens after startup: what Actuator should expose, who gets to see it, the difference between liveness and readiness, how to write a health check for the thing a database ping can't see, and how to shut down without dropping requests.
The example is the same orders service from Part 1, now with a background
consumer that polls a queue for order events. Everything below was run on
Spring Boot 4.1.2 with Java 25 (Amazon Corretto). The ideas work the
same on Spring Boot 3.5, but a few classes moved to new packages in 4.0.
Those spots are pointed out as they come up.
How do you add a health check endpoint in Spring Boot?
The short answer first, because it's smaller than the rest of this post
makes it look: add spring-boot-starter-actuator (the Maven snippet is in
the next section) and you already have one. With no configuration at all,
Spring Boot serves GET /actuator/health on the application port. On
Spring Boot 4.1.2 a fresh app answers like this:
$ curl -w ' [%{http_code}]\n' localhost:8080/actuator/health
{"groups":["liveness","readiness"],"status":"UP"} [200]
That status is the combined result of every health indicator Spring
Boot set up for what's on your classpath: a DataSource, disk space,
Redis, and so on. When any of them reports DOWN, the body says DOWN
and the HTTP status becomes 503. The status code is what load
balancers and Kubernetes actually read, not the JSON. The per-indicator
details stay hidden until you set management.endpoint.health.show-details.
That default is a working health check endpoint, but not yet one you can trust in production. Three things it doesn't do for you, each covered below:
- Keep the rest of Actuator private. See "Securing /actuator".
- Separate liveness from readiness (
/actuator/health/livenessand/actuator/health/readiness), so a slow database doesn't get every pod restarted. See "Liveness vs readiness". - Check your own code, like a queue consumer that silently stopped.
That's a custom Spring Boot
HealthIndicator. See "The health check that lies".
What Spring Boot Actuator gives you
Add the starter and you get a set of operational endpoints under
/actuator:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Out of the box, only health is exposed over HTTP. That default is
sensible, and the usual way teams break it is by copying
management.endpoints.web.exposure.include: "*" from a tutorial to "see
what's there". Here's what that wildcard opens:
envandconfigpropsshow your configuration. Since Spring Boot 3, the values are masked by default, but you still get every property name and where it came from, which is a decent map of your infrastructure. Oneshow-values: alwayslater, the values come back too.heapdumphands anyone a copy of your memory, and that copy has every secret the process holds, masked or not.threaddumpshows what every thread is doing right now.loggerslets anyone change log levels at runtime. That's a write operation, not a read.
Treat exposure as an allow list and name what you actually use:
management:
endpoints:
web:
exposure:
include: health,info,metrics
If you scrape metrics with Prometheus, add prometheus here (it needs the
micrometer-registry-prometheus dependency). The
Observability 101 post
covers what to do with those metrics once you have them.
Put Actuator on its own port
One more line keeps Actuator off the port your users hit:
management:
server:
port: 8081
Your load balancer or ingress routes only to 8080, and 8081 stays inside
the cluster network. That's a network boundary, not authentication, so
you still want the next section. But it means a mistake in your security
rules doesn't put /actuator/metrics on the public internet.
Securing /actuator
Health and info can be public. They have to be, because the kubelet and your load balancer don't log in. Everything else needs credentials. With Spring Security on the classpath, give Actuator its own filter chain:
package com.example.orders;
import static org.springframework.security.config.Customizer.withDefaults;
import org.springframework.boot.actuate.endpoint.web.WebServerNamespace;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.boot.health.actuate.endpoint.HealthEndpoint;
import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
class SecurityConfig {
@Bean
@Order(1)
SecurityFilterChain actuator(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
.requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)).permitAll()
.anyRequest().hasRole("ACTUATOR"))
.httpBasic(withDefaults());
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain app(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, HealthEndpoint.class)).permitAll()
.anyRequest().authenticated())
.httpBasic(withDefaults());
return http.build();
}
}
EndpointRequest matches Actuator paths wherever they live, so the rules
stay correct if someone changes the base path or the port. The second chain
is your application's own security. The only Actuator-related line in it
lets the probe paths on the main port through. They come up in the
Kubernetes section below.
On Spring Boot 3.5 the code is the same, but the imports differ:
EndpointRequest lives in
org.springframework.boot.actuate.autoconfigure.security.servlet, and
HealthEndpoint in org.springframework.boot.actuate.health.
For the ACTUATOR role, the quickest option is the user Spring Boot
configures from properties, with the password coming from the environment
like any other secret from Part 1:
spring:
security:
user:
name: ops
# password comes from SPRING_SECURITY_USER_PASSWORD
roles: ACTUATOR
In a real system that user probably comes from your identity provider, and the scraper uses a token. The filter chain doesn't change.
Then decide who sees health details. Without credentials, a caller should get the status and nothing else:
management:
endpoint:
health:
show-details: when-authorized
roles: ACTUATOR
Here's what that looks like against the running service:
$ curl localhost:8081/actuator/health
{"groups":["liveness","readiness"],"status":"UP"}
$ curl -u ops:change-me localhost:8081/actuator/health
{"components":{"db":{"details":{"database":"H2","validationQuery":"isValid()"},"status":"UP"},
"diskSpace":{...},"livenessState":{"status":"UP"},"orderConsumer":{...},
"ping":{"status":"UP"},"readinessState":{"status":"UP"},"ssl":{...}},
"groups":["liveness","readiness"],"status":"UP"}
$ curl -o /dev/null -w '%{http_code}\n' localhost:8081/actuator/metrics
401
$ curl -o /dev/null -w '%{http_code}\n' -u ops:change-me localhost:8081/actuator/env
404
The last one is a 404 even with valid credentials, because env isn't
exposed at all. Not exposing something beats securing it.
Liveness vs readiness
Kubernetes asks your pod two different questions, and mixing them up causes outages:
- Liveness: is this process stuck in a way only a restart can fix? Failing it kills the container.
- Readiness: should this instance receive traffic right now? Failing it takes the pod out of the Service's endpoints, and it gets traffic again once the check passes. Nothing restarts.
Spring Boot models both as application state and exposes them as health
groups at /actuator/health/liveness and /actuator/health/readiness.
These groups switch on by themselves when Spring Boot detects it's running
on Kubernetes. Turn them on explicitly anyway, so they also work on your
laptop and in tests:
management:
endpoint:
health:
probes:
enabled: true
add-additional-paths: true
add-additional-paths also publishes the two groups as /livez and
/readyz on the main port (8080). That matters once Actuator has its
own port. A probe on 8081 can pass while the server on 8080 is wedged,
because they're two different web servers. Pointing probes at the main
port checks the server your users actually hit. That's why the application
filter chain above lets those two paths through.
The most important rule here: the liveness probe must not depend on anything outside the process. If the database has a bad minute and your liveness check includes it, Kubernetes restarts every pod at once. The database recovers, and now you have a cold-start stampede on top of it. Restarting your app doesn't fix the database.
Spring Boot gets this right by default. The liveness group contains only
livenessState, and the readiness group only readinessState. Your job is
mostly not to break that, and the most common way to break it is pointing
the liveness probe at /actuator/health. That endpoint includes every
indicator, so one slow dependency turns it into a 503. You'll see that
happen in the next section.
The health check that lies
Back to the orders service. It has a database and a background consumer.
The consumer is a scheduled poll, but it stands in for any long-running
worker (a Kafka listener, an SQS poller, a batch thread). Here it is:
package com.example.orders;
import java.time.Clock;
import java.time.Instant;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class OrderEventsConsumer {
private final Clock clock;
private volatile Instant lastPoll;
OrderEventsConsumer(Clock clock) {
this.clock = clock;
this.lastPoll = clock.instant();
}
@Scheduled(fixedDelayString = "${app.consumer.poll-interval:1s}")
void poll() {
// Fetch a batch from the broker and process it (omitted).
lastPoll = clock.instant();
}
public Instant lastPoll() {
return lastPoll;
}
}
When that thread dies (an uncaught error in a listener container, a
deadlock, a broker connection that never recovers), here's what Actuator's
built-in indicators report: db is UP, diskSpace is UP, ping is
UP. All true. None of them check the part of the service that does the
work.
A custom HealthIndicator
The fix is to check what you actually care about: is the consumer still making progress? A timestamp of the last successful poll is enough:
package com.example.orders;
import java.time.Clock;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
class OrderConsumerHealthIndicator implements HealthIndicator {
private final OrderEventsConsumer consumer;
private final Clock clock;
private final Duration maxSilence;
OrderConsumerHealthIndicator(OrderEventsConsumer consumer, Clock clock,
@Value("${app.consumer.max-silence:30s}") Duration maxSilence) {
this.consumer = consumer;
this.clock = clock;
this.maxSilence = maxSilence;
}
@Override
public Health health() {
Duration silence = Duration.between(consumer.lastPoll(), clock.instant());
Health.Builder status = silence.compareTo(maxSilence) > 0 ? Health.down() : Health.up();
return status
.withDetail("lastPoll", consumer.lastPoll().toString())
.withDetail("silence", silence.toString())
.build();
}
}
Spring Boot drops the HealthIndicator suffix from the bean name, so this
shows up as orderConsumer. In Spring Boot 3.5, Health and
HealthIndicator are in org.springframework.boot.actuate.health. In 4.x
they moved to org.springframework.boot.health.contributor, and that's the
first compile error you'll hit when upgrading.
A few things make this check trustworthy:
- It measures progress, not existence. "The consumer bean exists" is always true. "The consumer polled in the last 30 seconds" is the thing that goes false.
- It's cheap. It reads a field. Health checks run every few seconds per pod, so an indicator that makes a network call or runs a query is load you add to your own dependencies.
- The threshold is configuration.
max-silenceshould be a few poll intervals, not one. A single slow batch shouldn't flip the pod out of service. - The
Clockis injected, so a test can move time forward instead of sleeping. More on that below.
Now stall the consumer (the demo raises the poll interval to an hour and
max-silence to two seconds) and look again:
$ curl -u ops:change-me localhost:8081/actuator/health
{"components":{"db":{...,"status":"UP"},"diskSpace":{...,"status":"UP"},
"livenessState":{"status":"UP"},
"orderConsumer":{"details":{"lastPoll":"2026-11-10T12:08:26.731683825Z",
"silence":"PT3.791988297S"},"status":"DOWN"},
"ping":{"status":"UP"},"readinessState":{"status":"UP"},"ssl":{...,"status":"UP"}},
"groups":["liveness","readiness"],"status":"DOWN"}
$ curl -w ' [%{http_code}]\n' localhost:8081/actuator/health/liveness
{"status":"UP"} [200]
$ curl -w ' [%{http_code}]\n' localhost:8081/actuator/health
{"groups":["liveness","readiness"],"status":"DOWN"} [503]
The database is still UP. Only the new indicator noticed.
That last line is the trap from the previous section. If your liveness
probe pointed at /actuator/health, Kubernetes would now restart a pod
that is perfectly alive, again and again, while the real problem sits
somewhere else.
Which check goes in which probe
The new indicator should affect readiness, not liveness. A pod whose consumer stopped shouldn't take traffic, and readiness is the signal that says so. Add it to the readiness group:
management:
endpoint:
health:
group:
readiness:
include: readinessState,orderConsumer
$ curl -w ' [%{http_code}]\n' localhost:8081/actuator/health/readiness
{"status":"DOWN"} [503]
Why not liveness, if a restart might fix a dead thread? Because you don't
know that it will. If the consumer is stuck because the broker is down, a
restart loop doesn't help and makes the noise worse. Take the pod out of
traffic, alert on it, and let a person decide. If you know a specific
failure is only fixable by a restart, say a thread that can't be restarted
in-process, that one condition can feed liveness through
AvailabilityChangeEvent.publish(context, LivenessState.BROKEN). Keep it
rare and deliberate.
What about the database in readiness? It's tempting, and the answer is "it depends". The database is shared. When it goes down, every pod fails readiness at the same moment, Kubernetes takes them all out of the Service, and your users get an error from the ingress instead of from your app. The user sees an error either way. But your app can usually return a better one, or still serve the endpoints that don't touch the database. Dependencies that only this instance uses (its own consumer, a local cache that has to warm up) are safe in readiness. Dependencies every instance shares usually belong in alerts and dashboards instead.
Kubernetes probe configuration
With the paths on the main port, the probe config is short. This is the standard shape. Tune the numbers to your startup time:
containers:
- name: orders
ports:
- containerPort: 8080
startupProbe:
httpGet: { path: /livez, port: 8080 }
periodSeconds: 5
failureThreshold: 24 # up to 2 minutes to start
livenessProbe:
httpGet: { path: /livez, port: 8080 }
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet: { path: /readyz, port: 8080 }
periodSeconds: 5
failureThreshold: 2
The startupProbe keeps the liveness probe from killing a JVM that is
still warming up, which is a classic source of restart loops on slow
nodes. Liveness gets a higher failureThreshold than readiness on
purpose: you want to stop traffic fast, but restart slowly. For more on
how these pieces fit into a cluster, see
Cloud Fundamentals Every Senior Engineer Needs.
Graceful shutdown
Deploys and scale-downs send your pod a SIGTERM. What happens to the
requests that are still running at that moment?
In Spring Boot 4.1, server.shutdown defaults to graceful (the
configuration metadata for 4.1.2 says so). Set it explicitly anyway, so
nobody has to look up the default for whatever version you're on:
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 20s
To check it, the orders service got a test endpoint that takes 5
seconds. The request was started, and the process got SIGTERM one
second later:
Commencing graceful shutdown. Waiting for active requests to complete
Graceful shutdown complete
HikariPool-1 - Shutdown initiated...
$ curl localhost:8081/actuator/health/readiness # during shutdown
{"status":"OUT_OF_SERVICE"} [503]
report done [200] 5.06s # the in-flight request
Three things happened. Readiness flipped to OUT_OF_SERVICE, so a load
balancer still probing would stop sending traffic. The web server stopped
accepting new requests. And the request that was already running finished
with a 200 instead of a reset connection.
Two Kubernetes details finish the job:
terminationGracePeriodSecondsmust cover the whole thing. It defaults to 30 seconds, and it includes thepreStophook below. A 5-secondpreStopplus a 20-second drain plus closing pools fits in 30, but not by much. If you raisetimeout-per-shutdown-phase, raise the grace period with it, or a slow drain ends inSIGKILL.- Endpoint removal isn't instant. Kubernetes sends
SIGTERMand removes the pod from the Service at about the same time, but load balancers and kube-proxy take a moment to notice. A shortpreStophook (sleep 5, if your image has a shell) delays theSIGTERMlong enough for traffic to drain first. Without it, a few requests can still arrive after the server has stopped accepting connections.
Test the health checks
Health checks are code that runs only when something is already going
wrong, which is exactly when you can't afford to find out they don't work.
Because the indicator takes a Clock, a test can stall the consumer
without sleeping:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"management.server.port=0",
"app.consumer.poll-interval=1h",
"spring.security.user.password=test-only"})
class HealthProbesTest {
@TestConfiguration
static class Clocks {
@Bean
@Primary
MutableClock mutableClock() {
return new MutableClock(); // a Clock whose time the test can move
}
}
@LocalManagementPort int port;
@Autowired MutableClock clock;
@Autowired OrderEventsConsumer consumer;
@BeforeEach
void consumerJustPolled() {
clock.set(consumer.lastPoll());
}
@Test
void stalledConsumerFailsReadinessButNotLiveness() throws Exception {
clock.advance(Duration.ofMinutes(5));
var readiness = get("/actuator/health/readiness", false);
assertThat(readiness.statusCode()).isEqualTo(503);
assertThat(readiness.body()).contains("\"status\":\"DOWN\"").doesNotContain("silence");
var liveness = get("/actuator/health/liveness", false);
assertThat(liveness.statusCode()).isEqualTo(200);
}
@Test
void metricsNeedCredentials() throws Exception {
assertThat(get("/actuator/metrics", false).statusCode()).isEqualTo(401);
assertThat(get("/actuator/metrics", true).statusCode()).isEqualTo(200);
}
// get(...) is a small java.net.http.HttpClient helper, with or without basic auth.
}
The full version also checks that anonymous callers never see details,
that env stays unexposed, and that /livez and /readyz answer on the
main port. Six tests, a few seconds to run. The one that earns its keep is
the first one. It pins down that readiness fails and liveness doesn't, so
a future change that mixes them up turns into a red build instead of a
restart storm. For more on structuring these, see
Testing Your Spring Boot Application.
A checklist for your next deploy
- Actuator exposure is an explicit allow list. No
*, and neverheapdumporenvon a public port. - Actuator runs on its own port, and everything except health and info requires a role.
- Anonymous health callers see the status only (
show-details: when-authorized). - Probes are on: liveness and readiness are separate paths, and the
liveness probe is not
/actuator/health. - Liveness checks nothing outside the process.
- Every background worker that does the real work (consumers, schedulers) has an indicator that measures progress, wired into readiness.
- Graceful shutdown is set explicitly, and
terminationGracePeriodSecondsis longer than the shutdown timeout. - A test proves that a stalled worker fails readiness and leaves liveness alone.
A health check you can trust is one that goes red for the failures you actually have, and only restarts the pod when a restart would help.
Next in the series, Part 3 covers database migrations with Flyway in Spring Boot: versioned scripts, what happens when two pods start at once, and how to change a schema without taking the service down.