Graceful Shutdown in Go: Safely Finish Requests and Release Resources
Graceful shutdown is the process of stopping a service from accepting new work when it receives a termination signal, giving work already started a bounded time to finish, and then closing resources. Go’s http.Server.Shutdown closes listeners and idle connections and waits for active requests to finish, but it does not clean up hijacked connections such as WebSockets or other application work automatically. The application must finish before the container runtime force-stops it.
Graceful shutdown is the process of stopping a service from accepting new work when it receives a termination signal, giving work already started a bounded time to finish, and then closing resources. Go’s http.Server.Shutdown closes listeners and idle connections and waits for active requests to finish, but it does not clean up hijacked connections such as WebSockets or other application work automatically. The application must finish before the container runtime force-stops it.
Graceful shutdown is more than process exit
An operating system or container runtime usually sends a termination signal to a process. If the application does not handle it, the process may exit immediately, cutting off a response or leaving a worker before it saves a queued job’s result. Waiting indefinitely has the opposite problem: deployment can stall until the orchestrator forcibly terminates the process.
A graceful shutdown therefore has two parts. First, stop intake so the service does not start new work. Second, finish in-flight requests and jobs, then close the resources they use before a defined deadline. Removing an instance from a load balancer is a separate network-draining step. This guide focuses on what happens inside a Go process afterward: the HTTP server, workers, and resources.
Shutdown stages and order
A Go HTTP service can use the following sequence after a termination signal. An HTTP server alone is not enough when the process also has a worker pool or message consumer; coordinate them under the same deadline.
| Stage | Action | Completion condition |
|---|---|---|
| 1. Detect shutdown | Deliver SIGTERM or an OS interrupt to an application context | One shutdown path starts; behavior for further signals is defined |
| 2. Stop new input | Close the HTTP listener, lower readiness, and stop workers from fetching new messages | No new request or job starts |
| 3. Finish active work | Allow active HTTP requests and already-fetched jobs a bounded time to finish | Results are committed or left in a safe retry state |
| 4. Close dependent resources | After work ends, close the DB pool, message client, telemetry exporter, and other dependencies | No shutting-down work can access a closed resource |
| 5. Exit or enforce deadline | Exit normally, or record deadline expiry and cancel remaining work/connections | The process exits before the platform’s grace period expires |
The order depends on resource dependencies. If a request uses the database, keep the DB pool open until that request finishes. A worker that has fetched a message should stop fetching new messages, finish or return the fetched message for redelivery, and only then close the broker connection. Telemetry may need to stay available until the final logs or spans are exported.
Go HTTP server example
This example shows shutdown for an HTTP server in a Linux container using Go 1.16 or later; signal.NotifyContext was added in Go 1.16. The code is illustrative and has not been run or compiled.
func run() error {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "ok\n")
})
server := &http.Server{Addr: ":8080", Handler: mux}
ctx, stop := signal.NotifyContext(
context.Background(), os.Interrupt, syscall.SIGTERM,
)
defer stop()
serveErr := make(chan error, 1)
go func() { serveErr <- server.ListenAndServe() }()
select {
case <-ctx.Done():
// Restore the default exit behavior for a second termination signal.
stop()
case err := <-serveErr:
if !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("serve HTTP: %w", err)
}
return nil
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
// Force-close ordinary HTTP connections that exceeded the deadline.
closeErr := server.Close()
if closeErr != nil {
return fmt.Errorf("shutdown HTTP: %v; force close: %w", err, closeErr)
}
return fmt.Errorf("graceful HTTP shutdown: %w", err)
}
if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("serve HTTP after shutdown: %w", err)
}
return nil
}
func main() {
if err := run(); err != nil {
log.Print(err)
os.Exit(1)
}
}Running the server in a goroutine lets the main flow wait for a signal while still receiving startup errors. On a signal, Shutdown closes listeners so the server accepts no new connections, closes idle connections, and waits for active requests to finish. After shutdown, ListenAndServe returns http.ErrServerClosed, which is an expected exit. If the shutdown context expires, the example calls Close to force-close ordinary HTTP connections; that can interrupt responses and is not equivalent to a successful graceful shutdown.
http.Server.Shutdown does not close or wait for hijacked connections. WebSockets and upgraded protocols need their own notification, tracking, and deadline. Go’s RegisterOnShutdown can start protocol-specific notifications, but it does not wait for them to finish. The application must track those connections and wait separately or close them at the deadline.
The container’s shutdown time budget
The application must finish before the container runtime or platform force-stops it. Docker stop sends the configured stop signal (or SIGTERM if none is configured), then sends SIGKILL after its wait limit. In Kubernetes, the Pod’s terminationGracePeriodSeconds countdown begins before the preStop hook runs. Because the hook must finish before the termination signal is sent, its duration and application cleanup share the same total budget.
For example, if the total grace period is 60 seconds and the hook takes 15 seconds, the app has less than 45 seconds to clean up. Leave room for signal delivery, scheduling delay, and the forced-stop boundary. The example’s 20-second timeout is for illustration, not a universal recommendation. Set the real deadline using maximum request/job duration, message redelivery behavior, platform limits, and deployment design.
Background work and resource cleanup
Stopping the HTTP server does not automatically cancel background goroutines. Share a shutdown context with workers or send an explicit Stop signal so they stop fetching new work while tracking what is already running. For a fetched message, check the order of processing and acknowledgment: acknowledging before processing risks data loss; stopping after processing but before acknowledgment can cause redelivery and duplicate execution. Make the job idempotent.
Close a resource only after its users have stopped. For example, close the DB pool and message client after requests and workers finish, then flush observability data last. Do not assume defer alone guarantees the required order; call cleanup functions explicitly and pass each stage its remaining time. Record cleanup errors without logging secrets or sensitive configuration.
Verification and recovery
Send `SIGTERM` in a development environment and confirm that no new request starts.
Confirm that a slow request started before the signal finishes within the limit.
Observe requests, workers, message consumers, and WebSockets separately; identify components that need their own shutdown path.
Deliberately shorten the deadline and confirm that a `Shutdown` timeout is recorded and forced cleanup runs. Record that remaining requests may be interrupted.
In Docker/Kubernetes, compare the configured stop signal, hook time, total grace period, and process exit time. During a rolling update, confirm capacity does not disappear before the replacement is ready.
If shutdown stalls, use instrumentation to find remaining requests or jobs. Safely redeliver retryable work, resolve the cause, then adjust the deadline policy. Increasing the limit without a cause can prolong deployments and stuck shutdowns.
Passing does not mean only that the process eventually exits. Confirm that new input stopped, in-flight work completed or followed the stated expiry/retry policy, dependent resources closed after their final use, and the process exited before the platform’s forced-stop deadline.
Sources and scope
Go `net/http`, [Server.Shutdown](https://pkg.go.dev/net/http#Server.Shutdown)
Go `os/signal`, [NotifyContext](https://pkg.go.dev/os/signal#NotifyContext)
Kubernetes, [Container lifecycle hooks](https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/)
Docker, [docker container stop](https://docs.docker.com/reference/cli/docker/container/stop/)
The core example is limited to Go 1.16+ os/signal.NotifyContext and the standard net/http server. Platform behavior is based on the Docker and Kubernetes documentation read; no application code or container shutdown was tested. The 20-second example timeout is illustrative.