Go & Kubernetes··2 min read

Graceful Shutdown in Go and Kubernetes: Draining Active HTTP and Worker Goroutines With Zero 502s

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Graceful Shutdown in Go and Kubernetes: Draining Active HTTP and Worker Goroutines With Zero 502s

Why SIGTERM Races Against Kubernetes Endpoint Removal

When Kubernetes terminates a pod during a rolling update, two events happen in parallel, not in sequence:

  1. The kubelet sends SIGTERM to your container process.
  2. The Kubernetes API server removes the pod's IP from the EndpointSlice and notifies the Ingress controller (NGINX, Traefik, or AWS ALB).

Propagating that EndpointSlice update across every node's iptables/IPVS rules and ingress worker takes 1 to 3 seconds. If your Go server immediately closes its TCP listener upon receiving SIGTERM, any request routed to that pod during those 2 seconds fails with HTTP 502 Bad Gateway.


1. The Kubernetes preStop Hook Synchronization Window

Adding a preStop lifecycle hook gives the Ingress controller time to stop sending new traffic before SIGTERM ever reaches the Go binary:

spec:
  terminationGracePeriodSeconds: 35
  containers:
    - name: api
      lifecycle:
        preStop:
          exec:
            command: ["/bin/sh", "-c", "sleep 5"]

2. Coordinated HTTP and Background Worker Drain in Go

Once SIGTERM arrives, we drain active HTTP requests first, and only close the RabbitMQ consumer and PostgreSQL connection pool after all in-flight handlers finish:

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

<-ctx.Done()
log.Println("SIGTERM received: draining in-flight HTTP requests...")

shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

if err := httpServer.Shutdown(shutdownCtx); err != nil {
	log.Printf("HTTP shutdown error: %v", err)
}

workerGroup.StopAndWait()
dbPool.Close()

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles