Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

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.

Course Home

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:

  1. Closes the listening TCP socket immediately so no new connections are accepted (your load balancer shifts new traffic to healthy pods).
  2. Closes all idle keep-alive connections.
  3. 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.ErrServerClosed as a crash: The moment srv.Shutdown closes the listener, srv.ListenAndServe() always returns http.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 ctx to srv.Shutdown(ctx): Once SIGTERM fires, ctx is already canceled! Passing it to srv.Shutdown makes Shutdown return immediately without waiting for in-flight requests. Always derive shutCtx from a fresh context.Background() with a timeout (e.g., 10s, shorter than Kubernetes's 30s terminationGracePeriodSeconds).
  • Closing db.Close() too early: Because db.Close() should run after srv.Shutdown(shutCtx) finishes draining active handlers, register defer db.Close() before starting the server and let srv.Shutdown return before run() exits.

Common mistakes

  • Using an unbuffered errCh := make(chan error): If both SIGTERM and a server error happen together, an unbuffered channel can block the server goroutine; use make(chan error, 1).
  • Listening only for os.Interrupt (Ctrl+C) and forgetting syscall.SIGTERM: Works on your laptop, then gets hard-killed inside Docker and Kubernetes, which send SIGTERM.
  • Using shell-form CMD ./server in Docker: Shell form runs /bin/sh -c ./server as PID 1, which often swallows SIGTERM instead of forwarding it to your Go binary! Always use exec form ENTRYPOINT ["/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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.