Video in progress
During a deploy, a few requests fail with 502. How do you set up graceful shutdown and connection draining correctly?
When a pod is being shut down, the LB doesn't remove it from the list instantly, so after SIGTERM the application has to keep accepting traffic for a few seconds and finish the requests in flight. In Spring this is solved with server.shutdown=graceful and a preStop pause.
📖 Answer
When Kubernetes terminates a pod, two things happen in parallel: the kubelet sends SIGTERM to the container, and the endpoint controller removes the pod from the Service. This news takes a few seconds to reach kube-proxy, the ingress and the external LB. If the application stops immediately on SIGTERM, requests that arrive in that gap hit a closed port — 502.
The setup:
# application.yml
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 25s
# deployment
spec:
terminationGracePeriodSeconds: 45
containers:
- name: app
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 10"]
Since Spring Boot 3.4, server.shutdown is graceful by default; in earlier versions you have to enable it yourself — spelling it out doesn't hurt either way.
The order: preStop waits 10 seconds (the LBs manage to remove the pod from their list in that time) → SIGTERM → Spring stops accepting new connections and finishes the ones in progress for up to 25 seconds → it shuts down. terminationGracePeriodSeconds must be larger than the sum of the two, otherwise SIGKILL.
Easily forgotten spots:
- Kafka consumers must also commit offsets before stopping — Spring Kafka does this on container stop.
- Long requests (file uploads, SSE) won't fit in 25 seconds — they need a retry on the client.
- Keep-alive connections: graceful shutdown stops accepting new connections, but a request can still arrive over an old connection left in the proxy's pool and get cut off. Enabling upstream retries on the ingress for idempotent methods closes this gap.
Sign up to mark studied questions and save your progress.