If your error rate spikes for a few seconds every time you deploy, the cause is usually shutdown order: the pod stops accepting connections before the rest of the system stops sending them. Kubernetes does not coordinate these steps for you; your app and manifest have to.

What happens when a pod terminates

  1. The pod is marked Terminating. At the same time, two things start in parallel:
    • The pod is removed from Service endpoints (kube-proxy, ingress controllers and load balancers update over the next moments).
    • The preStop hook runs, if defined, then the container receives SIGTERM.
  2. The app has terminationGracePeriodSeconds (default 30) to exit.
  3. If it is still running, it gets SIGKILL.

Because endpoint removal and SIGTERM happen at the same time, some traffic can still arrive for a few seconds after SIGTERM. An app that exits immediately on SIGTERM drops those requests; that is your deploy-time burst of 502s.

The fix in three parts

1. A short preStop delay

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

The delay gives load balancers time to stop routing to the pod before the app begins shutting down. Recent Kubernetes versions also support a built-in sleep action for preStop, so images without a shell work too.

2. Handle SIGTERM by draining

const server = app.listen(8080);
let shuttingDown = false;

process.on('SIGTERM', () => {
  shuttingDown = true;                       // readiness now fails
  server.close(async () => {                 // stop accepting, finish in-flight
    await db.end();                          // close pools after requests finish
    process.exit(0);
  });
  setTimeout(() => process.exit(1), 30_000).unref();  // safety net
});

3. Fail readiness during shutdown

Readiness that returns 503 once shutdown starts removes the pod from any endpoints that still include it. See health check endpoints.

Long-lived connections

Keep-alive HTTP connections, WebSockets and gRPC streams outlive individual requests. On shutdown, stop accepting new requests on existing connections (send Connection: close on responses, or GOAWAY for HTTP/2) and give streaming clients a chance to reconnect elsewhere. Clients should retry idempotent requests that fail with connection errors; see retries with backoff and jitter.

Background workers

Queue consumers should stop fetching new messages on SIGTERM, finish (or requeue) the ones in progress, and then exit. Make sure terminationGracePeriodSeconds is longer than your longest normal job, or design jobs to be resumable.

Language notes

  • Node.js: server.close() stops new connections but waits for idle keep-alive sockets; recent Node versions offer closeIdleConnections() to speed this up.
  • Go: http.Server.Shutdown(ctx) drains gracefully within the context deadline.
  • Java/Spring Boot: server.shutdown=graceful with spring.lifecycle.timeout-per-shutdown-phase.
  • Python (gunicorn): SIGTERM triggers graceful worker shutdown within --graceful-timeout.

Verifying it works

Run a load test against a service while you trigger a rolling deploy, and watch error rates. With correct shutdown, the error count during the deploy should be zero or close to it. In production, deploy markers on APM charts make deploy-time error bursts easy to see; VitalRix APM shows deploys on every chart, and uptime checks from outside confirm users saw no failures.

Checklist

  1. preStop delay of a few seconds.
  2. SIGTERM handler that drains and then exits.
  3. Readiness fails during shutdown.
  4. Grace period longer than drain time.
  5. Clients retry idempotent requests.
  6. Verified with a load test during a rolling deploy.

A worked example

A team saw about 40 failed requests per deploy on a service handling 300 requests per second, always in the first two seconds after each pod received SIGTERM. Their Node.js server called process.exit() directly in the SIGTERM handler. They added a 5-second preStop sleep, replaced the exit with server.close() followed by closing database pools, and flipped readiness to 503 on SIGTERM. A load test during a rolling deploy then showed zero failed requests, and the deploy markers in APM no longer lined up with error spikes.

Node drains and spot instances

Pods are also terminated when nodes are drained for upgrades or when spot or preemptible instances are reclaimed. Drains respect the grace period; spot reclamation may give only a short warning. Use PodDisruptionBudgets so drains do not remove too many replicas at once, run enough replicas across nodes, and keep shutdown fast enough to fit inside short warnings.

Checking your current behaviour

# watch the endpoints of a service while you delete one pod
kubectl get endpoints api -w &
kubectl delete pod <one-api-pod>

If the pod disappears from endpoints only after the process has already stopped, requests in between are being dropped.

Why do I still see errors with a SIGTERM handler?

Because endpoint removal and SIGTERM happen in parallel. Add a short preStop delay so traffic stops before the app starts closing.

How long should terminationGracePeriodSeconds be?

Longer than the preStop delay plus your longest normal request or job. 30 to 60 seconds suits most web services.

Does this matter for scale-down too?

Yes. Any pod termination, including autoscaler scale-down and node drains, follows the same sequence.

Try VitalRix free

Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.