Health checks and failover
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)At 8 pm one ShopLite server crashes, and the balancer keeps sending it every third customer. Health checks and failover decide how fast traffic notices and moves away.
Your turn: when a server dies
ShopLite runs three servers behind a balancer. During a sale app-2 freezes: the process is still running, but every request to it hangs. Sketch what you would build, then compare it with the sections below.
- How does the balancer find out that
app-2is stuck, and how often would you ask? - Would you remove a server after one failed check? What goes wrong if you do, and if you never do?
- What happens if the balancer itself dies, or if a deploy stops a server while requests are running?
Liveness vs readiness
Health check is a small request that a load balancer or platform sends to each server every few seconds to learn if it can be trusted. It asks two questions: liveness (is the process working?) and readiness (can it serve traffic now?).
ShopLite's Spring Boot app can answer both questions with Actuator. A few settings switch the probes on.
management.endpoints.web.exposure.include=healthmanagement.endpoint.health.probes.enabled=truemanagement.endpoint.health.group.readiness.include=readinessState,dbExample 1 · Liveness and readiness probes of a Spring Boot app while it starts
Runs in: a terminal, with the shoplite-api Spring Boot app starting on port 8080
curl -i http://localhost:8080/actuator/health/livenesscurl -i http://localhost:8080/actuator/health/readinessHTTP/1.1 200
Content-Type: application/vnd.spring-boot.actuator.v3+json
{"status":"UP"}
HTTP/1.1 503
Content-Type: application/vnd.spring-boot.actuator.v3+json
{"status":"OUT_OF_SERVICE"}What this code does
- While the app is still starting, liveness is
UP(the process works) but readiness isOUT_OF_SERVICEwith status 503, so a balancer keeps traffic away. - Once startup finishes, readiness turns
UPwith 200 and the balancer adds the server to the pool.
Example 2 · Liveness and readiness endpoints with the JDK HTTP server
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); // false while the cache warms up
static void reply(com.sun.net.httpserver.HttpExchange ex, int status, String body) throws IOException { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); ex.getResponseHeaders().add("Content-Type", "application/json"); ex.sendResponseHeaders(status, bytes.length); try (OutputStream out = ex.getResponseBody()) { out.write(bytes); } }
public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); // any free port server.createContext("/health/liveness", ex -> reply(ex, 200, "{\"status\":\"UP\"}")); server.createContext("/health/readiness", ex -> { if (ready.get()) { reply(ex, 200, "{\"status\":\"UP\"}"); } else { reply(ex, 503, "{\"status\":\"OUT_OF_SERVICE\"}"); } }); server.start(); String base = "http://127.0.0.1:" + server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient();
try { for (String phase : new String[] {"starting (cache warming)", "ready"}) { if (phase.equals("ready")) { ready.set(true); } System.out.println("App is " + phase + ":"); for (String probe : new String[] {"liveness", "readiness"}) { HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + "/health/" + probe)).build(), HttpResponse.BodyHandlers.ofString()); System.out.println(" GET /health/" + probe + " -> " + r.statusCode() + " " + r.body()); } } } finally { server.stop(0); } }}App is starting (cache warming):
GET /health/liveness -> 200 {"status":"UP"}
GET /health/readiness -> 503 {"status":"OUT_OF_SERVICE"}
App is ready:
GET /health/liveness -> 200 {"status":"UP"}
GET /health/readiness -> 200 {"status":"UP"}What this code does
- The server listens on a free local port. Liveness always answers 200; readiness answers 503 until the
readyflag is set, like an app warming its cache. - Java's
HttpClientplays the load balancer's health checker. Spring Actuator returns the same codes for the same states.
A server that is starting, warming its cache or shutting down is alive but not ready.
The load balancer uses readiness to decide where to send requests; the platform (for example Kubernetes) uses liveness to decide when to restart a container. Keep liveness simple: if it checks the database and the database blips, every server restarts at once. Spring Boot Actuator exposes both at /actuator/health/liveness and /actuator/health/readiness.
Fix the error
Fix the probe settings
Each setting causes a problem. Pick the line that fixes it.
Round 1 of 2
A short database blip restarts every ShopLite server at the same time.
Error
Pods restart together whenever the database is slow for a moment.
A balancer that skips unhealthy servers
Service Unavailable (503) is the HTTP status for "I cannot handle this request right now". A balancer returns it when no server is healthy, so clients fail fast instead of waiting on a dead server.
The balancer keeps one healthy flag per server and its picker skips the unhealthy ones. Example 3 drops app-2 when it crashes.
Example 3 · A round robin balancer that skips servers marked down
import java.util.ArrayList;import java.util.List;
class Backend { final String name; boolean reallyUp = true; // the truth, which the balancer cannot see directly boolean markedHealthy = true; // what the balancer believes int failures = 0; int successes = 0; int served = 0;
Backend(String name) { this.name = name; }}
class HealthCheckedBalancer { static final int FAIL_THRESHOLD = 3; // mark DOWN after 3 failed checks in a row static final int RISE_THRESHOLD = 2; private final List<Backend> backends; private int next = 0;
HealthCheckedBalancer(List<Backend> backends) { this.backends = backends; }
void runHealthChecks(int second) { for (Backend b : backends) { if (b.reallyUp) { b.successes++; b.failures = 0; if (!b.markedHealthy && b.successes >= RISE_THRESHOLD) { b.markedHealthy = true; System.out.println(" t=" + second + "s " + b.name + " marked UP"); } } else { b.failures++; b.successes = 0; if (b.markedHealthy && b.failures >= FAIL_THRESHOLD) { b.markedHealthy = false; System.out.println(" t=" + second + "s " + b.name + " marked DOWN"); } } } }
Backend pick() { for (int tries = 0; tries < backends.size(); tries++) { Backend b = backends.get(next++ % backends.size()); if (b.markedHealthy) { return b; } } return null; }}
public class HealthCheckedBalancerDemo { public static void main(String[] args) { List<Backend> backends = new ArrayList<>(List.of(new Backend("app-1"), new Backend("app-2"), new Backend("app-3"))); HealthCheckedBalancer lb = new HealthCheckedBalancer(backends); int failed = 0;
for (int second = 1; second <= 12; second++) { if (second == 3) { backends.get(1).reallyUp = false; System.out.println(" t=3s app-2 crashes"); } if (second == 9) { backends.get(1).reallyUp = true; System.out.println(" t=9s app-2 is back"); } lb.runHealthChecks(second); for (int r = 0; r < 3; r++) { Backend b = lb.pick(); if (b != null && b.reallyUp) { b.served++; } else { failed++; } } } for (Backend b : backends) { System.out.println(b.name + " served " + b.served); } System.out.println("failed requests: " + failed); }}t=3s app-2 crashes t=5s app-2 marked DOWN t=9s app-2 is back t=10s app-2 marked UP app-1 served 15 app-2 served 5 app-3 served 14 failed requests: 2
What this code does
- app-2 crashes at t=3s. Checks fail at 3, 4 and 5 seconds, so it is marked DOWN at t=5s; the 2 requests sent to it before that fail.
- After it returns at t=9s, two good checks mark it UP at t=10s and it gets traffic again. The other servers absorb its share meanwhile.
The health checker updates each flag. If no server is healthy, the balancer should fail fast with 503 instead of looping or sending traffic to a dead server.
Detection is never instant. Between a crash and the next few failed checks, some requests still go to the dead server and fail, which is why clients retry safe requests and checks run every few seconds.
Thresholds: fail after N, recover after M
Flapping is a server going in and out of the pool again and again because single check results flip its state. Every change moves users around, so balancers use fall and rise thresholds to stop it.
One failed check can be a network blip, so balancers wait for several in a row. Example 4 compares two settings on the same 12 checks.
Example 4 · Thresholds stop a flaky server from flapping
public class ThresholdsDemo { // One check result per second for a server with a flaky network: true = check passed static final boolean[] CHECKS = {true, false, true, false, false, true, false, false, false, true, true, true};
static void run(int fall, int rise) { boolean up = true; int bad = 0; int good = 0; int changes = 0; StringBuilder line = new StringBuilder(); for (boolean ok : CHECKS) { if (ok) { good++; bad = 0; } else { bad++; good = 0; } if (up && bad >= fall) { up = false; changes++; } else if (!up && good >= rise) { up = true; changes++; } line.append(up ? "U" : "D"); } System.out.printf("fall=%d rise=%d %s (%d state changes)%n", fall, rise, line, changes); }
public static void main(String[] args) { System.out.println("checks: " + toText(CHECKS)); run(1, 1); // reacts to every blip: flapping run(3, 2); // waits for a pattern }
static String toText(boolean[] checks) { StringBuilder sb = new StringBuilder(); for (boolean c : checks) { sb.append(c ? "+" : "x"); } return sb.toString(); }}checks: +x+xx+xxx+++ fall=1 rise=1 UDUDDUDDDUUU (6 state changes) fall=3 rise=2 UUUUUUUUDDUU (2 state changes)
What this code does
- With fall=1 and rise=1, every single failed check flips the state: 6 changes in 12 seconds, each one moving users around.
- With fall=3 and rise=2, only the run of three failures marks it down, and two passes bring it back: 2 changes.
A balancer marks a server down after N failures in a row (the fall count, often 3) and back up after M successes in a row (the rise count, often 2).
The trade-off is speed: with checks every 2 seconds and a fall of 3, a dead server is removed after about 6 seconds. Passive health checks help: the balancer also watches real responses and ejects a server that returns many errors.
Predict the output
Predict the threshold
The checks run once per second (+ passed, x failed). Fall is 3.
Round 1 of 2
Where does the server end up after these seven checks?
Failover for the balancer and the database
Virtual IP is one address that clients use and that moves between an active and a passive machine. When the active balancer dies, the standby takes over the same address and clients notice nothing.
The balancer must not be a single point of failure. Example 5 runs two balancers that share one address.
Example 5 · Active-passive balancers sharing a virtual IP
public class ActivePassiveDemo { public static void main(String[] args) { String virtualIp = "203.0.113.10"; // the one address in DNS for shop.example String active = "lb-1"; String passive = "lb-2"; int missedHeartbeats = 0; final int MISS_LIMIT = 3; // heartbeats are sent every second
boolean[] lb1Alive = {true, true, true, false, false, false, false, false}; for (int second = 0; second < lb1Alive.length; second++) { String event; if (active.equals("lb-1") && !lb1Alive[second]) { missedHeartbeats++; event = "lb-2 missed heartbeat " + missedHeartbeats; if (missedHeartbeats >= MISS_LIMIT) { active = "lb-2"; passive = "lb-1 (down)"; event += " -> lb-2 takes over " + virtualIp; } } else { missedHeartbeats = 0; event = "heartbeat ok"; } System.out.printf("t=%ds %s holds %s, standby %s: %s%n", second, active, virtualIp, passive, event); } }}t=0s lb-1 holds 203.0.113.10, standby lb-2: heartbeat ok t=1s lb-1 holds 203.0.113.10, standby lb-2: heartbeat ok t=2s lb-1 holds 203.0.113.10, standby lb-2: heartbeat ok t=3s lb-1 holds 203.0.113.10, standby lb-2: lb-2 missed heartbeat 1 t=4s lb-1 holds 203.0.113.10, standby lb-2: lb-2 missed heartbeat 2 t=5s lb-2 holds 203.0.113.10, standby lb-1 (down): lb-2 missed heartbeat 3 -> lb-2 takes over 203.0.113.10 t=6s lb-2 holds 203.0.113.10, standby lb-1 (down): heartbeat ok t=7s lb-2 holds 203.0.113.10, standby lb-1 (down): heartbeat ok
What this code does
- lb-1 holds the virtual IP while it sends heartbeats. When it dies at t=3s, lb-2 counts missed heartbeats.
- After 3 missed heartbeats lb-2 takes over the same address, so clients keep using
203.0.113.10and never change configuration.
In an active-passive pair the active balancer holds the virtual IP and sends heartbeats; if the passive one misses several, it takes the address over (tools such as keepalived do this with VRRP). Cloud load balancers are run this way for you, across several zones.
Databases use the same idea: a standby replica is promoted when the primary dies, as the Databases at Scale module showed. One extra danger: if the old primary comes back still believing it is primary, two servers accept writes (split brain). Fencing stops it: every promotion raises an epoch number, and writes from an older epoch are rejected.
Graceful shutdown: drain before removing
Graceful shutdown is stopping a server in three steps: stop taking new requests, finish the requests already running, then exit. A timeout caps the wait so one stuck request cannot block a deploy.
Servers leave the pool all the time: deploys, scale-in, restarts. Example 6 compares a hard stop with a graceful one.
Example 6 · Hard stop vs graceful shutdown with a 10-second limit
import java.util.ArrayList;import java.util.List;
public class GracefulShutdownDemo { // Each in-flight request: seconds of work left static List<Integer> inFlight() { return new ArrayList<>(List.of(1, 2, 4, 6, 12)); // 12 s is a slow export }
public static void main(String[] args) { // 1. Hard stop: kill the process now List<Integer> hard = inFlight(); System.out.println("Hard stop: " + hard.size() + " in-flight requests cut off (users see errors)");
List<Integer> work = inFlight(); int timeout = 10; System.out.println("Graceful stop:"); System.out.println(" t=0s readiness -> 503, balancer stops sending new requests"); int finished = 0; for (int t = 1; t <= timeout; t++) { int done = 0; for (int i = 0; i < work.size(); i++) { work.set(i, work.get(i) - 1); } while (work.remove(Integer.valueOf(0))) { done++; } finished += done; if (done > 0) { System.out.println(" t=" + t + "s finished " + done + ", still running " + work.size()); } if (work.isEmpty()) { break; } } System.out.println(" timeout reached: " + finished + " finished, " + work.size() + " cut off, process exits"); }}Hard stop: 5 in-flight requests cut off (users see errors) Graceful stop: t=0s readiness -> 503, balancer stops sending new requests t=1s finished 1, still running 4 t=2s finished 1, still running 3 t=4s finished 1, still running 2 t=6s finished 1, still running 1 timeout reached: 4 finished, 1 cut off, process exits
What this code does
- A hard stop cuts off all 5 in-flight requests.
- The graceful stop fails readiness first, then lets requests finish: 4 complete within 10 seconds and only the 12-second export is cut off at the limit.
Killing the process at once cuts off every request in flight. A graceful shutdown first makes readiness fail, so the balancer stops sending new requests, then lets in-flight requests finish, then exits.
Spring Boot 3.4 and later (so ShopLite's Boot 4.1) shut down gracefully by default; spring.lifecycle.timeout-per-shutdown-phase (30 seconds by default) sets the cap. Long jobs such as big exports belong in background workers, not in a request that a deploy can cut off.
Order of execution
A graceful shutdown
Put the steps of one graceful shutdown in order.
Next step
Check your understanding
11 quick questions