Build a Multi-Route Service With Graceful Shutdown
Wire signal.NotifyContext and server.Shutdown(ctx) so in-flight HTTP requests finish before exit, and verify with go test -race. After this, deploys drop zero active requests.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
When Docker, systemd, or Kubernetes rolls out a new version of your Go API, it sends SIGTERM to the old container before stopping it. If your server does not handle that signal—or exits immediately—every checkout, webhook, or SQL write currently in flight gets severed mid-request, causing client 502 Bad Gateway errors on every single deploy.
Go's standard library makes zero-downtime graceful shutdown clean in ~30 lines using signal.NotifyContext and srv.Shutdown(shutCtx).
Skip ahead
If you already wire signal.NotifyContext, ignore http.ErrServerClosed on shutdown, pass a fresh background timeout context to srv.Shutdown, and close database pools afterward, take the section quiz or move on to "Generics, Constraints, and slices/maps Packages."
Experiment 1: What happens during a graceful shutdown
When you call srv.Shutdown(shutCtx), Go performs three coordinated steps automatically:
- Closes the listening TCP socket immediately so no new connections are accepted (your load balancer shifts new traffic to healthy pods).
- Closes all idle keep-alive connections.
- Waits patiently for every active in-flight HTTP handler to finish writing its response—up until
shutCtx's deadline expires.
Experiment 2: The complete multi-route service with graceful shutdown
Read every line of run(ctx context.Context) error carefully—each line prevents a subtle production shutdown bug:
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func run(ctx context.Context) error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
}
errCh := make(chan error, 1)
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
close(errCh)
}()
select {
case err := <-errCh:
return err
case <-ctx.Done():
slog.Info("shutting down gracefully")
shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(shutCtx)
}
}
func main() {
if err := run(context.Background()); err != nil {
fmt.Fprintln(os.Stderr, "server error:", err)
os.Exit(1)
}
}
Experiment 3: Three subtle shutdown bugs this pattern avoids
- Treating
http.ErrServerClosedas a crash: The momentsrv.Shutdowncloses the listener,srv.ListenAndServe()always returnshttp.ErrServerClosed. Checking!errors.Is(err, http.ErrServerClosed)separates a real startup failure (like port 8080 already in use) from a normal shutdown. - Passing the already-canceled
ctxtosrv.Shutdown(ctx): OnceSIGTERMfires,ctxis already canceled! Passing it tosrv.ShutdownmakesShutdownreturn immediately without waiting for in-flight requests. Always deriveshutCtxfrom a freshcontext.Background()with a timeout (e.g., 10s, shorter than Kubernetes's 30sterminationGracePeriodSeconds). - Closing
db.Close()too early: Becausedb.Close()should run aftersrv.Shutdown(shutCtx)finishes draining active handlers, registerdefer db.Close()before starting the server and letsrv.Shutdownreturn beforerun()exits.
Common mistakes
- Using an unbuffered
errCh := make(chan error): If bothSIGTERMand a server error happen together, an unbuffered channel can block the server goroutine; usemake(chan error, 1). - Listening only for
os.Interrupt(Ctrl+C) and forgettingsyscall.SIGTERM: Works on your laptop, then gets hard-killed inside Docker and Kubernetes, which sendSIGTERM. - Using shell-form
CMD ./serverin Docker: Shell form runs/bin/sh -c ./serveras PID 1, which often swallowsSIGTERMinstead of forwarding it to your Go binary! Always use exec formENTRYPOINT ["/server"].
💡 Tip
Because run(ctx context.Context) error accepts a parent context, your integration tests can cancel ctx after 50 ms to verify that your entire server boots, serves /health, and shuts down cleanly without leaking goroutines.
What happens if you skip this step
Every rolling deployment aborts active user requests mid-response—producing 502 errors, partially written files, and interrupted database transactions during normal business hours.
Why does passing the signal-notified ctx directly into srv.Shutdown(ctx) fail to drain active HTTP requests?
About
Wire signal.NotifyContext and server.Shutdown(ctx) so in-flight HTTP requests finish before exit, and verify with go test -race. After this, deploys drop zero active requests.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.