Every deploy sends your server a signal. What happens in the next few seconds decides whether a customer sees an error page or nothing at all. A graceful shutdown means three things: stop accepting new connections, let in-flight requests finish, and give up after a deadline.
The whole pattern
The standard library already does the hard part. http.Server.Shutdown closes the listeners, then waits for active connections to go idle. Your job is to call it at the right moment and to bound how long it may take.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: mux}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()
<-ctx.Done() // wait for the signal
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("forced shutdown: %v", err)
}
Things that still bite
- Long-lived connections. WebSockets and streaming responses are hijacked, so
Shutdowndoes not wait for them. Track them yourself. - Background goroutines. Workers started by handlers need their own context and a
sync.WaitGroup. - The load balancer. Fail the readiness check first, wait a couple of seconds, then shut down, so no new traffic is routed to you.
Rule of thumb: the shutdown timeout should be shorter than the grace period your orchestrator gives the process, or it will be killed mid-drain.
Put this in a small helper once and every service you write gets zero-downtime deploys for free. It is one of the best returns on twenty lines of code you will find.
