Video in progress
How do you turn on graceful shutdown in Spring Boot, and what does it actually do?
With server.shutdown=graceful, when SIGTERM arrives the web server stops accepting new requests and gives the current ones time to finish. The time is capped with spring.lifecycle.timeout-per-shutdown-phase.
📖 Answer
server:
shutdown: graceful # the default starting with Spring Boot 3.4
spring:
lifecycle:
timeout-per-shutdown-phase: 20s
The sequence is roughly:
- The JVM receives SIGTERM, and the shutdown hook starts closing the Spring context.
- The readiness state switches to
REFUSING_TRAFFIC. - Tomcat/Netty stops accepting new connections and waits for running requests to finish (up to 20 seconds).
- Then the beans are closed:
@PreDestroy, the connection pool, Kafka consumers.
An important match: Kubernetes' terminationGracePeriodSeconds must be larger than the timeout in Spring. Otherwise SIGKILL arrives while Spring is still waiting.
Graceful shutdown covers only HTTP requests. For an ExecutorService you started yourself, or for @Scheduled tasks, you have to think separately: for example, setWaitForTasksToCompleteOnShutdown(true) and setAwaitTerminationSeconds(...) on a ThreadPoolTaskExecutor. Otherwise a half-finished background job is cut off silently.
Sign up to mark studied questions and save your progress.