Skip to lesson

Health and readiness endpoints with Actuator

ShopLite now runs in production, but the platform only sees a process: it cannot tell a stuck app from one that is still starting. The app has to answer two different questions.

Liveness vs readiness: restart me, or do not send me traffic

A liveness probe is a URL the platform calls on a schedule to ask: is this process still working at all? If it keeps failing, the platform restarts the container. Use it only for problems a restart fixes, such as a deadlock.

ShopLite needs about 40 seconds to start, and a restart does not fix every problem. The program below shows what a platform does with each pair of probe answers.

Two probes. If the liveness probe keeps failing, the platform restarts the container. If the readiness probe fails, the platform sends no traffic but keeps the instance running. A database outage fails only readiness, so nothing is restarted.

Example 1 · What a platform does with each probe result

ProbeDecisionDemo.javaJava
public class ProbeDecisionDemo {    static String action(boolean live, boolean ready) {        if (!live) {            return "restart the container";        }        if (!ready) {            return "keep it running, send no traffic";        }        return "send traffic";    }
    public static void main(String[] args) {        String[][] moments = {            {"starting up (Flyway running)", "true", "false"},            {"serving normally", "true", "true"},            {"MySQL down for 30 s", "true", "false"},            {"shutting down after SIGTERM", "true", "false"},            {"deadlocked, no thread answers", "false", "false"}        };        for (String[] m : moments) {            boolean live = Boolean.parseBoolean(m[1]);            boolean ready = Boolean.parseBoolean(m[2]);            System.out.printf("%-31s live=%-5s ready=%-5s -> %s%n", m[0], live, ready, action(live, ready));        }    }}
Output
starting up (Flyway running)    live=true  ready=false -> keep it running, send no traffic
serving normally                live=true  ready=true  -> send traffic
MySQL down for 30 s             live=true  ready=false -> keep it running, send no traffic
shutting down after SIGTERM     live=true  ready=false -> keep it running, send no traffic
deadlocked, no thread answers   live=false ready=false -> restart the container

What this code does

  • Only a failed liveness probe leads to a restart. Start-up, a database outage and shutdown are all "not ready": the instance is fine, it just should not get requests.
  • If the database check were in liveness, the third row would become "restart the container" on every instance at once.

The second question is readiness: can this instance serve requests now? If it fails, the platform stops sending traffic but leaves the instance running. Start-up, shutdown and a database outage are all "not ready", not "not alive". Section 15 added /actuator/health, one overall status; production needs these two.

The classic mistake is putting the database check in liveness. During a short MySQL outage every instance would be restarted again and again, which fixes nothing and makes recovery slower.

Probes in Actuator: /liveness and /readiness

A readiness probe is a URL the platform calls to ask: can this instance serve requests right now? If it fails, the platform stops sending traffic but leaves the instance running, as during start-up, shutdown or a database outage.

Spring Boot tracks both states for you and serves them at two URLs. ShopLite switches the probes on explicitly and adds the database check to readiness only.

Example 2 · application-prod.yml: probes with the db check in readiness

Runs in: the shoplite-api Spring Boot project, started with the prod profile

YAML
management:  endpoint:    health:      probes:        enabled: true      group:        readiness:          include: readinessState,db# Test it: stop the database for a moment, then call the probes# $ curl -i https://api.shoplite.example/actuator/health/liveness# $ curl -i https://api.shoplite.example/actuator/health/readiness
Sample output
HTTP/2 200
content-type: application/vnd.spring-boot.actuator.v3+json

{"status":"UP"}

HTTP/2 503
content-type: application/vnd.spring-boot.actuator.v3+json

{"status":"DOWN"}

What this code does

  • With MySQL unreachable, liveness stays UP (a restart would not help) while readiness is DOWN with 503, so the platform stops routing requests to this instance until the database is back.
  • During a graceful shutdown readiness shows {"status":"OUT_OF_SERVICE"}, also with 503, because Boot switches it to REFUSING_TRAFFIC.

Boot keeps LivenessState (CORRECT while the app runs) and ReadinessState, which becomes ACCEPTING_TRAFFIC only after start-up has finished and switches to REFUSING_TRAFFIC as soon as shutdown begins. Actuator serves them as health groups at /actuator/health/liveness and /actuator/health/readiness.

In Boot 4.1 the groups are on by default (Section 15's output already showed "groups":["liveness","readiness"]); older versions enabled them only on Kubernetes, so ShopLite sets management.endpoint.health.probes.enabled: true to be explicit. The db indicator goes in the readiness group only.

Predict the output

Which probe fails?

Read each setting and pick what happens.

Round 1 of 3

MySQL is stopped. What does the readiness URL return?

management.endpoint.health.group.readiness.include: readinessState,db
# MySQL is stopped
GET /actuator/health/readiness

Exposure and security: show only what is safe

A management port is a separate port, such as 8081, on which Spring Boot serves the Actuator endpoints. If the port is never published, only the platform and your monitoring can reach them, not the internet.

Health URLs are public, so they must say little. The configuration below exposes only health and info; the output shows what a guest sees and what an admin sees.

Example 3 · Safe exposure: health and info only, details for admins

Runs in: the shoplite-api Spring Boot project, started with the prod profile

YAML
management:  endpoints:    web:      exposure:        include: health,info  endpoint:    health:      show-details: when-authorized      roles: ADMIN# $ curl -s https://api.shoplite.example/actuator/health# $ curl -s -o /dev/null -w "%{http_code}\n" https://api.shoplite.example/actuator/env# $ curl -s https://api.shoplite.example/actuator/health -H "Authorization: Bearer $ADMIN"
Sample output
{"groups":["liveness","readiness"],"status":"UP"}
404
{"components":{"db":{"details":{"database":"MySQL","validationQuery":"isValid()"},"status":"UP"},"diskSpace":{"status":"UP","details":{...}},"livenessState":{"status":"UP"},"ping":{"status":"UP"},"readinessState":{"status":"UP"},"ssl":{"status":"UP"}},"groups":["liveness","readiness"],"status":"UP"}

What this code does

  • A guest gets only the overall status; env is not exposed, so it answers 404 and no setting can leak through it.
  • The admin's JWT has the ADMIN role, so the same URL shows every component. ShopLite's SecurityConfig already permits /actuator/health/** for everyone; the details rule is applied by Actuator itself.

Never expose env, configprops, beans or heapdump. Keep show-details: when-authorized with roles: ADMIN: anonymous callers see just {"status":"UP"}, while a signed-in admin sees each component.

The stricter option is management.server.port: 8081. With management.endpoint.health.probes.add-additional-paths: true, Boot also serves /livez and /readyz on the main port, so a platform that can only probe the main port still works.

Find the bug

Find the unsafe line

Click the line that makes the configuration unsafe.

Which line publishes too much?

Round 1 of 3

A probe server you can run: ready only after start-up

A shutdown hook is a thread the JVM runs when the process is asked to stop, for example by the SIGTERM that docker stop sends. Spring Boot uses one to close the application context, which turns readiness to REFUSING_TRAFFIC.

The program below uses only the JDK. /live always answers 200, /ready answers 503 until a simulated warm-up ends, and the shutdown hook marks the app not ready before it stops the server.

Example 4 · Probe server: /live, /ready and a shutdown hook

ProbeServerDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.concurrent.atomic.AtomicBoolean;
public class ProbeServerDemo {    static final AtomicBoolean ready = new AtomicBoolean(false);    static HttpServer server;    static HttpClient client = HttpClient.newHttpClient();
    static void answer(HttpServer s, String path, boolean liveness) {        s.createContext(path, exchange -> {            boolean ok = liveness || ready.get();            byte[] body = (ok ? "{\"status\":\"UP\"}" : "{\"status\":\"OUT_OF_SERVICE\"}")                    .getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(ok ? 200 : 503, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });    }
    static void probe(String when) {        try {            int port = server.getAddress().getPort();            for (String path : new String[] {"/live", "/ready"}) {                HttpResponse<String> r = client.send(                        HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path)).build(),                        HttpResponse.BodyHandlers.ofString());                System.out.printf("%-17s %-6s -> %d %s%n", when, path, r.statusCode(), r.body());            }        } catch (IOException | InterruptedException e) {            System.out.println(when + ": probe failed " + e);        }    }
    public static void main(String[] args) throws Exception {        server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        answer(server, "/live", true);        answer(server, "/ready", false);        server.start();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {            ready.set(false);                         // 1. stop new traffic first            System.out.println("shutdown hook: readiness OUT_OF_SERVICE");            probe("during shutdown");            server.stop(1);                           // 2. let in-flight requests finish            System.out.println("shutdown hook: server stopped");        }));
        probe("during start-up");        Thread.sleep(300);        ready.set(true);        System.out.println("start-up finished: readiness UP");        probe("serving");        System.exit(0);    }}
Output
during start-up   /live  -> 200 {"status":"UP"}
during start-up   /ready -> 503 {"status":"OUT_OF_SERVICE"}
start-up finished: readiness UP
serving           /live  -> 200 {"status":"UP"}
serving           /ready -> 200 {"status":"UP"}
shutdown hook: readiness OUT_OF_SERVICE
during shutdown   /live  -> 200 {"status":"UP"}
during shutdown   /ready -> 503 {"status":"OUT_OF_SERVICE"}
shutdown hook: server stopped

What this code does

  • /live never depends on ready, so it is 200 the whole time; /ready is 503 until warm-up ends and again as soon as shutdown starts.
  • System.exit(0) stands in for the SIGTERM that docker stop sends; both run the shutdown hook. The hook flips readiness before stopping the server, the same order Spring Boot follows in a graceful shutdown.
  • server.stop(1) waits up to one second for open exchanges to finish, a small version of Boot's spring.lifecycle.timeout-per-shutdown-phase.

A common slip is the wrong order: stopping the server first and flipping readiness afterwards leaves the platform sending requests to a closing server. Flip readiness first, then wait for in-flight requests.

Wiring probes into the platform and Compose

A health check is a URL or command that the platform or Compose runs on a schedule to mark a container healthy or unhealthy. Pointing it at the readiness probe makes the platform wait for the app before it sends traffic.

Point the platform health check at the readiness path, so a new version gets traffic only when it is ready. Platforms with two probes look like this.

YAML
# Kubernetes-style probes (reading code)livenessProbe:  httpGet: { path: /actuator/health/liveness, port: 8080 }  periodSeconds: 10  failureThreshold: 3readinessProbe:  httpGet: { path: /actuator/health/readiness, port: 8080 }  periodSeconds: 5  failureThreshold: 2

Example 5 · Compose health check on readiness

Runs in: a Linux VM with Docker, in /opt/shoplite

YAML
services:  api:    image: ghcr.io/asha-rao/shoplite-api:${IMAGE_TAG:?set IMAGE_TAG in .env}    healthcheck:      test: ["CMD-SHELL", "wget -qO- http://localhost:8080/actuator/health/readiness || exit 1"]      interval: 15s      timeout: 3s      retries: 3      start_period: 60s# $ docker compose up -d --wait# $ docker inspect --format '{{json .State.Health.Status}}' shoplite-api-1
Sample output
[+] Running 2/2
 ✔ Container shoplite-api-1    Healthy                           38.9s
 ✔ Container shoplite-caddy-1  Healthy                           39.4s
"healthy"

What this code does

  • BusyBox wget exits with an error on a 503, so the container is unhealthy while readiness is down; start_period: 60s keeps start-up failures from counting.
  • Plain Docker never restarts a container just because it is unhealthy; Compose uses the status for depends_on and --wait. Restarts on a failed liveness probe are a feature of platforms such as Kubernetes.

In Compose the healthcheck should call readiness too, because depends_on: condition: service_healthy and docker compose up --wait use it to decide when the API is ready. Give it a start_period long enough for Spring Boot and Flyway to start, so failures during start-up do not count.

Order of execution

A new version goes live

Tap the steps in the order they happen.

Next step

Check your understanding

12 quick questions