03 / 06

How would you implement graceful shutdown for an HTTP server handling long-lived connections?

Listen for SIGTERM/SIGINT, call server.Shutdown() with a deadline context, drain in-flight requests, and signal health checks as unhealthy before stopping to let the load balancer route away.

Graceful shutdown implementation
Shutdown checklist
  1. 1

    server.Shutdown() stops accepting new connections and waits for active requests to complete

  2. 2

    Set a shutdown deadline (30s) to force-close stuck connections after the timeout

  3. 3

    Mark health endpoint unhealthy before shutdown — gives load balancer time to drain

  4. 4

    Drain message queue consumers before exit to avoid duplicate processing on restart

  5. 5

    Use preStop hook in Kubernetes to add the delay before SIGTERM is sent