Sub topic 6
Shutting down without dropping requests
This chapter assumes you can build and run a Spring Boot executable JAR, you know how application.properties and environment variables work, and you understand basic HTTP and process signals. You will learn how Spring Boot stops a running application, why a default shutdown can drop requests, and how to configure it so deployments are safe.
Why shutdown matters
Every deployment stops an old instance and starts a new one. Servers also restart for patches, autoscalers remove instances, and Kubernetes moves pods between nodes. Each of these events asks the process to stop while it may still be serving requests.
Without graceful shutdown, the web server closes its listener and the JVM exits. A client that was halfway through a payment call gets a connection reset. The server may have already written to the database, so the client cannot tell whether the operation happened. Graceful shutdown narrows this window: the application stops taking new work, finishes work already accepted, and then exits.
What happens when the JVM receives a signal
On Linux, a process is asked to stop with a signal. The two you will meet most often are:
| Signal | Sent by | Effect on the JVM |
|---|---|---|
| SIGTERM (15) | `kill <pid>`, `systemctl stop`, `docker stop`, Kubernetes | Starts an orderly shutdown. Shutdown hooks run. |
| SIGKILL (9) | `kill -9`, the kernel out-of-memory killer, a stop that exceeded its timeout | The process ends immediately. No hooks run. |
Spring Boot registers a JVM shutdown hook. When SIGTERM arrives, the hook closes the ApplicationContext, which destroys beans, stops the web server, and releases resources such as connection pools. Graceful shutdown is a change to how the web server stops during that close.
The JVM reports the exit code 143 after SIGTERM, which is 128 plus 15. This is why the systemd unit in the earlier chapter sets SuccessExitStatus=143. Without it, systemd would record a normal stop as a failure.
Enabling graceful shutdown
Graceful shutdown is supported by all four embedded web servers (Tomcat, Jetty, Undertow, and Reactor Netty). It is on by default in recent Spring Boot versions, but it is good practice to state it explicitly so that the behavior is visible in your configuration.
# application.properties
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30sThe two properties mean the following:
server.shutdown=gracefultells the web server to stop accepting new requests and wait for active ones. The other value,immediate, closes everything at once.spring.lifecycle.timeout-per-shutdown-phasesets how long Spring waits for each shutdown phase. The default is 30 seconds. When the timeout expires, remaining requests are cut off and shutdown continues.
What "stop accepting new requests" means
The exact behavior depends on the server:
- Tomcat, Jetty, and Reactor Netty stop accepting new connections at the network level. A new client gets a connection refused error.
- Undertow keeps accepting connections but answers new requests with HTTP 503.
Existing keep-alive connections are also treated carefully. Requests already in progress are allowed to finish, and the server then closes those connections.
The shutdown sequence
The order of events matters when you tune timeouts. Spring Boot shuts down in phases, using the SmartLifecycle mechanism.
placeholderThe diagram below shows the sequence.
Two points follow from this order. First, the web server drains before beans are destroyed, so in-flight requests can still use the database connection pool. Second, the timeout applies to the draining phase. If a request takes longer than the timeout, it is interrupted and the client sees an error.
Work outside the request thread
Graceful shutdown covers HTTP requests. It does not automatically cover everything your application does. Check these common gaps:
@Asyncmethods and your own thread pools. Tasks may be abandoned when the context closes. Configure the executor to wait:
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=20s- Scheduled tasks. Set the equivalent
spring.task.scheduling.shutdown.*properties so a running job can finish. - Message listeners. Kafka and RabbitMQ containers stop consuming on shutdown, but a message being processed may be redelivered. Make handlers idempotent, meaning that processing the same message twice gives the same result.
- Long requests. Streaming responses and large uploads can run longer than any reasonable timeout. Decide how to handle them rather than raising the timeout without limit.
Choosing the timeout
The timeout should cover the longest request you consider normal, with a margin. If your 99th percentile request takes 2 seconds, 30 seconds is generous. A very large value delays every deployment when one client holds a connection open.
The application timeout must also fit inside the timeout of whatever stops the process. If the application waits 30 seconds but the platform sends SIGKILL after 10, the extra wait is wasted and requests are dropped anyway. Keep this ordering:
- Platform kill timeout (the largest)
- Spring
timeout-per-shutdown-phase - Longest normal request (the smallest)
In systemd, the kill timeout is TimeoutStopSec, which defaults to 90 seconds on most distributions. In Docker, docker stop waits 10 seconds by default and can be changed with --stop-timeout. In Kubernetes, it is terminationGracePeriodSeconds, which defaults to 30 seconds. With a 30 second Spring timeout, set the Kubernetes value higher, for example 45 seconds.
The SIGTERM must reach the JVM
A frequent failure is that the JVM never receives the signal. This happens when java is not the main process of the container.
This Dockerfile entrypoint works, because the exec form runs java directly as process 1:
ENTRYPOINT ["java", "-jar", "app.jar"]This one does not:
ENTRYPOINT java -jar app.jarThe shell form starts /bin/sh -c "java -jar app.jar". The shell becomes process 1 and often does not forward SIGTERM to its child. Docker waits for the full timeout, then sends SIGKILL, and no graceful shutdown happens. If you must use a wrapper script, end it with exec java -jar app.jar so that Java replaces the shell.
Load balancers and the readiness gap
Even with graceful shutdown, a race remains. When a pod or instance is told to stop, the load balancer or service proxy learns about it a moment later. During that gap it may still route new requests to an instance that is already refusing them. Clients see connection errors for a short time.
There are two common remedies:
- Fail readiness first. Spring Boot switches its readiness state to
REFUSING_TRAFFICwhen shutdown begins, so the readiness probe from the Actuator chapter starts failing. This tells the orchestrator to stop routing traffic. It helps only if the probe is checked often enough. - Delay the shutdown start. Add a short pause before SIGTERM takes effect, so the routing change spreads first. In Kubernetes this is a
preStophook that runssleep 5. In a plain environment, you can remove the instance from the load balancer before you stop it.
You will wire both into a Kubernetes manifest in a later chapter. For now, remember the principle: stop sending traffic, then stop the process.
Testing it yourself
Do not trust the configuration without trying it. Add a slow endpoint:
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SlowController {
@GetMapping("/slow")
public Map<String, String> slow() throws InterruptedException {
Thread.sleep(10_000);
return Map.of("status", "done");
}
}Start the application, then run these commands in two terminals.
# Terminal 1: start a request that takes 10 seconds
curl -i http://localhost:8080/slow
# Terminal 2: send SIGTERM while the request is running
kill -TERM "$(pgrep -f 'myapp-1.0.0.jar')"With server.shutdown=graceful, terminal 1 prints 200 OK after about 10 seconds, and the application then exits. Set server.shutdown=immediate and repeat. The curl command fails with an empty reply or a connection reset. The application log also shows the shutdown messages. Look for a line saying that graceful shutdown is in progress, followed by one saying it is complete.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Requests fail on every deployment | Graceful shutdown off, or SIGTERM not reaching the JVM | Set `server.shutdown=graceful`. Use the exec form of `ENTRYPOINT`. |
| Stop takes exactly the platform timeout, then the exit code is 137 | The process ignored SIGTERM and was killed | Check that Java is process 1 or that the script uses `exec`. |
| Service shows as failed after a normal stop | Exit code 143 treated as an error | Add `SuccessExitStatus=143` in systemd. |
| Background jobs are cut off | Executors not waiting for tasks | Enable `await-termination` for task executors. |
| Brief errors during rolling updates | Load balancer still routes to a stopping instance | Fail readiness first, and add a short pre-stop delay. |
| Shutdown is slow every time | A client holds a connection, or the timeout is too high | Lower the timeout, and set timeouts on clients and streams. |
Exercise
A service has spring.lifecycle.timeout-per-shutdown-phase=60s. It runs in Kubernetes with the default terminationGracePeriodSeconds. Its logs never show the "graceful shutdown complete" message during deployments, and requests that take 40 seconds are dropped. What is wrong, and what would you change?
Show answer
The Kubernetes default grace period is 30 seconds, which is shorter than the 60 second Spring timeout. After 30 seconds Kubernetes sends SIGKILL, so the JVM is killed before draining finishes and the 40 second requests are cut off. Set terminationGracePeriodSeconds higher than the Spring timeout, for example 75, or lower the Spring timeout to fit the platform limit. Also confirm that Java is process 1 so it receives SIGTERM.
Exercise
Why does ENTRYPOINT java -jar app.jar often lead to dropped requests during docker stop, while ENTRYPOINT ["java", "-jar", "app.jar"] does not?
Show answer
The shell form runs the command through /bin/sh -c, so the shell is process 1 and may not forward SIGTERM to Java. Docker then waits for its timeout and sends SIGKILL, which skips graceful shutdown. The exec form runs Java as process 1, so it receives SIGTERM directly and Spring can drain requests.