Video in progress

Even with graceful shutdown on, a few 502 errors show up during a deploy. Why, and how do you fix it?

When a pod is being deleted, SIGTERM and removal from the endpoints happen in parallel. By the time the app gets SIGTERM and closes connections, the load balancer and kube-proxy may still send it traffic. Usually waiting a few seconds in preStop closes this race condition.

📖 Answer

When a pod goes into Terminating, two things start at the same time:

  1. the kubelet runs the preStop hook (if there is one), then sends SIGTERM to the container;
  2. the control plane removes the pod from the EndpointSlice, and this change reaches kube-proxy, the Ingress controller and the cloud load balancers with some delay.

If the second is slower, the app is already refusing new connections while the Ingress still sends it requests, and you get 502/503.

spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: app
      lifecycle:
        preStop:
          sleep:
            seconds: 10        # K8s 1.30+; on older versions: exec: ["sh","-c","sleep 10"]

During preStop the app works as usual, and meanwhile the traffic routing has time to update. Then SIGTERM arrives and Spring's graceful shutdown finishes the current requests.

Do the time math: preStop (10s) + Spring timeout-per-shutdown-phase (20s) + a margin < terminationGracePeriodSeconds (45s). The grace period includes the preStop time too, and many people forget this.

A sleep through exec requires a shell in the image. A distroless image has none, so you use the newer sleep hook or a delay inside the app. A retry on the client side helps too, but only for idempotent requests.