Video in progress
How do you take a pod out of traffic cleanly when it is shutting down or during maintenance? How do `ReadinessState.REFUSING_TRAFFIC` and graceful shutdown work here?
When Spring Boot gets SIGTERM, it switches readiness to REFUSING_TRAFFIC, and with server.shutdown=graceful it stops taking new requests and finishes the ones already started. But traffic keeps arriving for a few seconds until Kubernetes removes the endpoint, so you also need a preStop delay. To take a pod out manually, you publish an AvailabilityChangeEvent.
📖 Answer
Do you see 502 or "connection reset" errors during a deploy? This is often the reason. The sequence is: Kubernetes sends SIGTERM to the pod and, in parallel, removes it from the Service endpoints. News that the endpoint is gone takes a few seconds to reach kube-proxy and the ingresses. If the application shuts down in that window, incoming requests are cut off.
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 20s
# Deployment
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 10"] # wait for the endpoints to be updated
terminationGracePeriodSeconds: 40
For maintenance (for example, while a cache is reloading) you can take the pod out of traffic without killing it:
@Component
class CacheReloader {
private final ApplicationEventPublisher events;
void reload() {
AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC);
try {
doReload();
} finally {
AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC);
}
}
}
/actuator/health/readiness returns 503 immediately, and on its next check the readiness probe removes the pod from the Service.
How to verify it from monitoring: during a deploy, look at whether 5xx and the "aborted" requests in http_server_requests spike. If you see a small error spike on every rollout, preStop or terminationGracePeriodSeconds is not enough.
Sign up to mark studied questions and save your progress.