Video in progress

Strong Middle 🌱 Spring

How does graceful shutdown work in Spring Boot, and what do you need to do so requests don't get cut off during a deploy?

With server.shutdown=graceful, once the stop signal arrives the app stops taking new requests, finishes the in-flight ones within timeout-per-shutdown-phase, then closes the beans. Since Boot 3.4 this is the default.

📖 Answer

server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 25s

The sequence (when SIGTERM arrives):

  1. the web server stops accepting new connections;
  2. in-flight requests get 25 s to finish;
  3. SmartLifecycle beans stop (Kafka listeners, schedulers);
  4. @PreDestroy runs, the connection pool is closed.

On Kubernetes there's one more subtle bit. When a pod is shutting down, the Service endpoints take a few seconds to update, and in the meantime traffic still reaches the old pod. So:

lifecycle:
  preStop:
    exec:
      command: ["sh", "-c", "sleep 10"]
terminationGracePeriodSeconds: 45

Hook up the readiness probe too: when shutdown starts, Actuator switches readiness to REFUSING_TRAFFIC.

terminationGracePeriodSeconds must be > preStop + shutdown timeout, otherwise Kubernetes sends SIGKILL and everything gets cut off midway.

Long background jobs (imports, reports) won't fit in that window — write them so they can pick up where they stopped (resumable).