all snippets
2025-01-18javaspring-bootkubernetes

Graceful shutdown in Spring Boot on Kubernetes

How to make in-flight KYC requests finish cleanly when a pod is rotated.

Graceful shutdown in Spring Boot on Kubernetes

When a pod gets a SIGTERM during a rolling deploy, any in-flight request can be killed mid-flight. For KYC that means a half-written audit row and a very grumpy compliance team.

Two flags do most of the work:

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

And on the Deployment:

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

The preStop sleep gives the Service endpoints controller time to remove the pod before Spring stops accepting connections. Combined with a 30s Spring shutdown phase, we drain the queue instead of dropping it.

Rule of thumb: terminationGracePeriodSeconds > preStop + timeout-per-shutdown-phase.