How to Set Up Zero-Downtime Deploys for Go

Achieve zero-downtime Go deploys by running new instances alongside old ones and using Server.Shutdown to gracefully drain active connections before stopping the old process.

Zero-downtime deploys in Go are achieved by running a new instance alongside the old one, draining connections, and swapping traffic. This approach relies on the net/http package's Server.Shutdown method to gracefully stop accepting new requests while finishing in-flight ones.

// 1. Start new server on a different port or via load balancer
// 2. Signal old server to drain
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
err := oldServer.Shutdown(ctx)
cancel()
if err != nil {
    log.Fatalf("Server forced to shutdown: %v", err)
}
// 3. Update load balancer to point to new server
// 4. Stop old server process

The Shutdown method closes the listener and waits for all active connections to close or timeout, ensuring no requests are dropped during the transition.