Lesson 5 of 9 · 25m
Graceful Shutdown: Stop Taking Work Before You Drop It
Handle signals, stop listeners, drain in-flight requests, close resources in order, and avoid the false confidence of a single shutdown timeout.
A deploy should not feel like pulling the power cord. Yet many services treat shutdown as an afterthought: SIGTERM arrives, the process exits, the load balancer keeps sending traffic for a few seconds, in-flight requests die mid-write, and users experience the rollout as random 502s. Graceful shutdown is not complicated, but it is sequenced.
The sequence is the design
A sane order is:
receive signal
stop accepting new connections
let in-flight requests finish within a bounded time
stop background workers
close outbound clients and database pools
exit before the orchestrator kills youOrdering matters. Closing the database first while handlers still need it is not graceful; it is merely faster failure.
Handle SIGTERM explicitly
Containers and systemd normally send SIGTERM before SIGKILL:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
errCh <- srv.ListenAndServe()
}()
select {
case err := <-errCh:
return err
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
return srv.Shutdown(shutdownCtx)
}Shutdown stops listeners and waits for active connections to become idle. It does not finish work that ignores context; that is why timeout discipline comes first.
Readiness must change before traffic disappears
Mark the service unready as soon as shutdown begins:
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
if !ready.Load() {
http.Error(w, "shutting down", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})Endpoint removal and health propagation are not instantaneous. Draining still matters even when readiness is correct.
Workers need shutdown contracts
Queue consumers, refresh loops, and broadcasters should accept context and report completion:
type Worker interface {
Run(ctx context.Context) error
}Cancel workers after the HTTP listener stops accepting new work, then wait with a deadline. Critical cleanup needs its own bounded path; do not reuse an already-cancelled request context.
Close resources in reverse dependency order
Things constructed later often depend on things constructed earlier. Close in reverse where practical. Do not ignore close errors from databases, telemetry exporters, or file handles; they can reveal writes that never reached their destination.
Field notes
- Kubernetes termination grace periods are hard ceilings, not polite suggestions.
Shutdowndoes not close hijacked connections such as websockets; track and close those separately.- Never use request context for shutdown cleanup. It may already be cancelled.
- Test deploys under load. Graceful shutdown that only works on an idle laptop is a rumor.
Was this lesson helpful?