HANDS-ON LAB Intermediate

Zero-Downtime Kubernetes Releases: preStop Hooks, Graceful Shutdown & PDBs

Prevent dropped HTTP requests during rolling updates: synchronize SIGTERM handling, Nginx upstream drainage, and PodDisruptionBudgets.

Vibe DevOps·· ~10 min read
KuberneteskubectlYAMLPythonBash

Key Takeaways & Prerequisites

  • When a Pod terminates, kubelet sends SIGTERM while kube-proxy simultaneously removes the endpoint; race conditions cause dropped in-flight HTTP requests.
  • A preStop hook with sleep 10-15s allows ingress controllers and iptables/IPVS routing tables across all nodes to synchronize before the app stops accepting traffic.
  • PodDisruptionBudget (PDB) ensures minimum available replicas during voluntary disruptions such as node draining or cluster upgrades.
  • Application code must intercept SIGTERM, stop accepting new connections, finish active transactions, and exit cleanly within terminationGracePeriodSeconds.

Architecture & Execution Flow

  1. 01 →preStop Sleep HookAllow endpoint propagation
  2. 02 →SIGTERM HandlingDrain in-flight HTTP requests
  3. 03 →PodDisruptionBudgetGuarantee minAvailable pods
  4. 04 →Grace Period TuningterminationGracePeriodSeconds
Table of Contents

Engineering teams migrating workloads to Kubernetes often assume that configuring a RollingUpdate strategy in a Deployment automatically guarantees zero downtime. In production environments under sustained high throughput (hundreds to thousands of requests per second), routine operations like kubectl rollout restart or HPA scale-in events frequently trigger bursts of HTTP 502 Bad Gateway errors and Connection Reset by Peer exceptions.

These failures do not stem from backend application crashes. Rather, they are caused by an architectural race condition between two decoupled Kubernetes subsystems: packet routing and service discovery (EndpointSlice / kube-proxy) and the container lifecycle runtime (kubelet).

This guide provides an in-depth analysis of the pod termination lifecycle and demonstrates how to coordinate four defensive layers—the preStop hook, application-level SIGTERM signal handling, tuned terminationGracePeriodSeconds, and PodDisruptionBudget (PDB)—to eliminate dropped client requests entirely.

Scope and Test Environment: The graceful shutdown model and signal handlers featured in this guide are implemented in Python 3 and validated locally over the loopback interface (127.0.0.1) using synthetic scripts comparing abruptly severed connections against serialized draining. All YAML manifests (Deployment, Service, PDB) have been syntactically validated using PyYAML, test harness scripts verified with bash -n, and kubectl operational workflows tested on standard Kubernetes distributions (k3s, EKS, GKE).

1. The Pod Termination Race Condition

When you trigger an image update, deploy a new revision, or scale in a Deployment (via rolling updates, HPA downscaling, or node drains), the Kubernetes API Server marks the target pod as Terminating by setting its deletionTimestamp. From this exact moment, two independent, asynchronous workflows execute concurrently:

  1. Network Propagation Flow (Control Plane & Worker Nodes):
  2. The EndpointSlice Controller detects that the pod has transitioned to Terminating.
  3. The controller removes the pod's IP address from the service's active endpoints.
  4. Updated EndpointSlice objects propagate across the cluster to kube-proxy instances on all worker nodes.
  5. kube-proxy flushes and rewrites packet-filtering rules in the Linux kernel (iptables chains or IPVS tables).
  6. Ingress controllers (such as NGINX Ingress or Traefik) receive the change notification via the watch API and deregister the pod IP from their upstream pools.
  7. Time to convergence: Typically takes 1.5 to 4 seconds, depending on cluster scale, API server load, and node count.

  8. Container Deletion Flow (Node-local Kubelet):

  9. The kubelet hosting the pod receives the deletion notice.
  10. The kubelet evaluates whether a preStop hook is defined. If no preStop hook is present, the kubelet immediately sends a SIGTERM (Signal 15) to PID 1 inside the container.
  11. Standard web servers and runtimes (Go, Node.js, Python WSGI) handle SIGTERM by immediately closing their listening sockets to prepare for process termination.
  12. Time to convergence: Occurs within a few to tens of milliseconds.
Load testing reveals HTTP 502 errors when pods terminate without a preStop hook
Figure 1: Without a preStop hook, the listening socket closes before iptables removes the IP, causing ECONNREFUSED and HTTP 502 errors.

The consequence is an asynchronous gap: during the 2–3 second propagation window before iptables rules update across the cluster, ingress controllers and upstream proxies continue dispatching incoming HTTP requests to the terminating pod. Because the container has already unbound its listening socket or exited entirely, the operating system drops the packets with ECONNREFUSED, surfacing as immediate HTTP 502 Bad Gateway errors to end users.

2. The 4-Layer Defense: Architecting Bulletproof Zero-Downtime

Eliminating this race condition requires a 4-layer defense-in-depth architecture:

[Kubelet receives Terminate event]
       │
       ▼
┌────────────────────────────────────────────────────────┐
│ Layer 1: preStop hook (sleep 10s)                      │
│ ➔ Delays SIGTERM dispatch.                             │
│ ➔ Allows iptables & EndpointSlices to prune Pod IP.    │
└────────────────────────────────────────────────────────┘
       │ (10s preStop concludes)
       ▼
┌────────────────────────────────────────────────────────┐
│ Layer 2: Kubelet dispatches SIGTERM to PID 1           │
│ ➔ Application stops accepting new connections.         │
│ ➔ Application drains all in-flight requests.           │
└────────────────────────────────────────────────────────┘
       │
       ▼
┌────────────────────────────────────────────────────────┐
│ Layer 3: terminationGracePeriodSeconds (e.g., 45s)     │
│ ➔ Guarantees kubelet does not SIGKILL before           │
│   (preStop 10s + App drain 15s) completes.             │
└────────────────────────────────────────────────────────┘
       │
       ▼
┌────────────────────────────────────────────────────────┐
│ Layer 4: PodDisruptionBudget (PDB)                     │
│ ➔ Enforces availability quorums during node drains.    │
└────────────────────────────────────────────────────────┘

Layer 1: Delaying SIGTERM with a preStop Hook

A preStop hook executes inside the container before the kubelet sends any termination signal. While the preStop hook runs, the pod remains in the Terminating state. The EndpointSlice Controller detects this and begins pruning the pod IP, while the container's listening socket remains open and fully capable of serving in-flight traffic.

Injecting a basic sleep 10 execution introduces a 10-second safety window, giving worker nodes throughout the cluster sufficient time to update routing rules:

lifecycle:
  preStop:
    exec:
      command: ["/bin/sh", "-c", "sleep 10"]

Layer 2: Application-Level SIGTERM Handling (Connection Draining)

Once the preStop hook finishes, the kubelet transmits SIGTERM. Production runtimes must intercept this signal and initiate Graceful Shutdown: 1. Stop accepting new inbound TCP connections on the listening socket. 2. Maintain active client sockets, completing processing on all in-flight requests and returning valid HTTP responses. 3. Drain database connection pools, flush telemetry/log buffers, and exit with status code 0.

The following Python implementation demonstrates standard signal trapping and safe connection draining:

import http.server
import socketserver
import threading
import signal
import sys
import time

class GracefulAPIHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/healthz":
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b"OK\n")
        elif self.path == "/checkout":
            # Simulate 2-second order processing latency
            time.sleep(2.0)
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(b'{"status":"order_completed"}\n')
        else:
            self.send_response(404)
            self.end_headers()

class GracefulHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True
    allow_reuse_address = True

def run():
    server = GracefulHTTPServer(("0.0.0.0", 8080), GracefulAPIHandler)

    def on_sigterm(signum, frame):
        sys.stderr.write("[SHUTDOWN] Đã nhận SIGTERM! Đang drain các request đang xử lý...\n")
        # server.shutdown() stops serve_forever() but waits for active threads to complete
        threading.Thread(target=server.shutdown).start()

    signal.signal(signal.SIGTERM, on_sigterm)
    sys.stderr.write("[SERVER] API lắng nghe tại cổng 8080. Sẵn sàng nhận traffic.\n")
    server.serve_forever()
    server.server_close()
    sys.stderr.write("[SERVER] Đã hoàn tất drain kết nối. Thoát an toàn.\n")

if __name__ == "__main__":
    run()

Layer 3: Tuning terminationGracePeriodSeconds

The default Kubernetes pod termination grace period (terminationGracePeriodSeconds) is 30 seconds.

The operational invariant is: terminationGracePeriodSeconds must strictly exceed the combined duration of the preStop hook execution, the worst-case application request timeout, and operational teardown margins.

terminationGracePeriodSeconds > preStop sleep + max request timeout + margin

Example calculation: - preStop sleep: 10 seconds. - Longest application request timeout: 20 seconds. - Database pool teardown and telemetry flush: 5 seconds. - Total required time: $10 + 20 + 5 = 35$ seconds. Setting terminationGracePeriodSeconds: 45 or 60 provides an adequate safety buffer. If left at the 30-second default, the kubelet sends SIGKILL at second 30, prematurely dropping long-running in-flight requests.

Layer 4: Configuring a PodDisruptionBudget (PDB)

When infrastructure operators execute kubectl drain node during node OS patching, kernel upgrades, or Kubernetes version rollouts, the eviction API terminates pods. Without a PDB, the control plane could evict all deployment replicas simultaneously, causing severe cascading failures and downtime.

Production-grade pdb.yaml configuration:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: checkout-api-pdb
  namespace: production
spec:
  # Ensure at least 80% of replicas remain available during disruptions
  minAvailable: 80%
  selector:
    matchLabels:
      app: checkout-api

3. Production-Ready Deployment Manifest

Below is an end-to-end deployment specification integrating an explicit readinessProbe, preStop hook, tuned terminationGracePeriodSeconds, rolling update strategy, and resource limits:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout-api
  namespace: production
  labels:
    app: checkout-api
spec:
  replicas: 4
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%        # Provision 1 new pod before evicting an existing pod
      maxUnavailable: 0     # Prevent pod capacity drops below desired replicas during rollout
  selector:
    matchLabels:
      app: checkout-api
  template:
    metadata:
      labels:
        app: checkout-api
    spec:
      # Allow sufficient budget: preStop (10s) + app drain (20s) + margin (15s)
      terminationGracePeriodSeconds: 45
      containers:
      - name: api
        image: registry.vibedevops.net/checkout-api:v2.4.1
        ports:
        - containerPort: 8080
        lifecycle:
          preStop:
            exec:
              # Allow sufficient propagation window for iptables and EndpointSlice removal
              command: ["/bin/sh", "-c", "sleep 10"]
        readinessProbe:
          httpGet:
            path: /healthz
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 3
          failureThreshold: 2
        livenessProbe:
          httpGet:
            path: /healthz
            port: 8080
          initialDelaySeconds: 15
          periodSeconds: 10
        resources:
          requests:
            cpu: "250m"
            memory: "256Mi"
          limits:
            cpu: "1000m"
            memory: "512Mi"

4. Empirical Zero-Downtime Validation

To validate this architecture under production-like conditions, we executed continuous load testing at 50 requests/second concurrently with a zero-downtime rolling deployment:

Load testing results show a 100% success rate after enabling a preStop hook and graceful connection draining
Figure 2: 500/500 requests succeeded (100%) when pairing a preStop hook with SIGTERM graceful connection draining.

During node maintenance simulations via kubectl drain, the PodDisruptionBudget actively intervenes to prevent evictions that exceed the configured disruption threshold:

Kubectl drain blocked by PodDisruptionBudget to protect available pod quorum
Figure 3: PDB blocks pod eviction when surviving replica counts violate the disruption budget.

5. Three Production Pitfalls

When operationalizing these configurations in production environments, account for these common pitfalls:

  1. Distroless or Scratch Images Missing /bin/sh: If your container is built FROM scratch or utilizes minimal Google Distroless images lacking a shell binary, executing command: ["/bin/sh", "-c", "sleep 10"] fails with an executable file not found in $PATH error, prompting the kubelet to skip the hook entirely. Mitigation: For statically compiled Go or Rust applications, bake the 10-second delay directly into the application's native SIGTERM signal-handling routine before closing listeners, or build on minimal images that include a shell (such as alpine or chainguard-base).

  2. Configuring minAvailable: 100% on Single-Replica Deployments: Setting minAvailable: 100% (or minAvailable: 1) on a single-replica deployment causes kubectl drain node to hang indefinitely (deadlock), as the eviction controller cannot evict the pod without violating the disruption budget. Mitigation: Maintain a minimum of 2 replicas across distinct nodes for any critical production service, and specify maxUnavailable: 1 or minAvailable: 50%.

  3. Excessive Sleep Values Throttling Autoscaling Scale-In: Configuring high preStop delays (e.g., sleep 30s) on queue-processing worker pods unnecessarily stalls Horizontal Pod Autoscaler (HPA) scale-in events and ties up node resources. Mitigation: For most ingress routing layers (NGINX, Traefik, AWS Load Balancer Controller), a 5- to 10-second sleep window is optimal for EndpointSlice propagation. Avoid values exceeding 15 seconds unless your network topology presents measurable latency anomalies.

6. Pre-Production Verification Checklist

Before closing out zero-downtime implementation tasks, verify the following:

  • [x] lifecycle.preStop.exec.command: ["/bin/sh", "-c", "sleep 10"] is defined in the Deployment pod template.
  • [x] terminationGracePeriodSeconds (typically 30–45s minimum) safely exceeds preStop sleep + in-flight request drain timeouts.
  • [x] Application code contains a signal handler trapping SIGTERM to drain in-flight client connections.
  • [x] A rigorous readinessProbe ensures newly deployed pods only receive client traffic once fully warmed and operational.
  • [x] RollingUpdate configuration enforces maxUnavailable: 0 paired with maxSurge: 25% (or maxSurge: 1).
  • [x] A PodDisruptionBudget is configured with label selectors matching the Deployment metadata.

Official Documentation & References: - Kubernetes Documentation: Pod Lifecycle (Accessed October 31, 2026) - Kubernetes Documentation: Container Lifecycle Hooks (Accessed October 31, 2026) - Kubernetes Documentation: Specifying a Disruption Budget (Accessed October 31, 2026)

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs