February 27, 2026
Graceful Shutdown in Go: Why Most Implementations Are Wrong
Designing Deterministic Shutdown Flows for Production Systems

By Yaninyz witty
6 min read
You've probably seen this code, Maybe you've written it, or not.
A quick signal handler, a context cancel, maybe a WaitGroup โ ship it. But when your Kubernetes pod gets a SIGTERM at 3am and drops 200 in-flight requests, you'll wish you'd thought harder about this.
The "Good Enough" Trap
Most Go shutdown implementations look like this:
func main() {
srv := &http.Server{Addr: ":8080", Handler: handler}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.Shutdown(ctx)
}func main() {
srv := &http.Server{Addr: ":8080", Handler: handler}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.Shutdown(ctx)
}This example might look familiar, its is from the docs, in a thousand blog posts and it has serious problems.
Let's dissect exactly what's wrong, and then build something better.
Problem 1: Shutdown Order Is Non-Deterministic
When you call srv.Shutdown(), you stop accepting new connections and wait for active ones to finish. Fine. But what about:
- Background workers draining a job queue?
- A Kafka consumer mid-commit?
- Prometheus metrics being scraped during shutdown?
- A database transaction in flight on a connection you're about to close?
The naive implementation shuts down the HTTP server first, but your background goroutines may depend on shared state that the HTTP handlers were also modifying. You've just created a race condition at the worst possible time.
Shutdown order matters. And most code ignores it entirely.
Problem 2: context.WithTimeout Starts the Clock Too Early
Look at this pattern again:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.Shutdown(ctx)ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.Shutdown(ctx)That 30-second clock starts immediately. If your shutdown involves multiple sequential steps โ drain the HTTP server, flush a message buffer, close DB connections โ each step eats into the same budget.
The last step might get 200ms.
Worse, if step 1 takes 25 seconds legitimately (long-running requests), step 2 (your Kafka flush) will be interrupted mid-flight with no clean way to distinguish "timeout" from "done."
Problem 3: Errors Are Silently Dropped
srv.Shutdown(ctx)
// What if this returns an error? Nobody knows.srv.Shutdown(ctx)
// What if this returns an error? Nobody knows.http.Server.Shutdown returns an error. Context deadline exceeded means in-flight requests were abandoned โ you have partial writes, uncommitted state, and confused clients. Logging this isn't optional in production.
Problem 4: The WaitGroup Anti-Pattern
Here's another common pattern:
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
worker(ctx)
}()
}
<-quit
cancel()
wg.Wait()var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
worker(ctx)
}()
}
<-quit
cancel()
wg.Wait()Two problems:
cancel()is a broadcast โ all goroutines get cancelled simultaneously. There's no concept of "finish what you're doing before stopping."wg.Wait()blocks forever if a goroutine leaks. You have no shutdown deadline at the process level.
Here is how to think about the shutdown system, the right way
Here's the architecture we want:
Signal received
โ
โผ
[Phase 1] Stop accepting new work
โ - Close HTTP listener
โ - Pause Kafka consumer
โ
โผ
[Phase 2] Drain in-flight work
โ - Wait for HTTP handlers to finish
โ - Wait for job queue to empty
โ
โผ
[Phase 3] Flush and close resources
- Flush metrics/traces
- Close DB connections
- Close message broker connectionsSignal received
โ
โผ
[Phase 1] Stop accepting new work
โ - Close HTTP listener
โ - Pause Kafka consumer
โ
โผ
[Phase 2] Drain in-flight work
โ - Wait for HTTP handlers to finish
โ - Wait for job queue to empty
โ
โผ
[Phase 3] Flush and close resources
- Flush metrics/traces
- Close DB connections
- Close message broker connectionsEach phase has its own timeout budget. Failure in one phase is logged but doesn't block later phases.
The shutdown manager
// ShutdownManager orchestrates ordered, phased shutdown.
type ShutdownManager struct {
mu sync.Mutex
phases []shutdownPhase
timeout time.Duration
}
type shutdownPhase struct {
name string
timeout time.Duration
fn func(ctx context.Context) error
}
func NewShutdownManager(total time.Duration) *ShutdownManager {
return &ShutdownManager{timeout: total}
}
// Register adds a shutdown function to a named phase.
// Phases execute in registration order.
func (s *ShutdownManager) Register(name string, timeout time.Duration, fn func(ctx context.Context) error) {
s.mu.Lock()
defer s.mu.Unlock()
s.phases = append(s.phases, shutdownPhase{name, timeout, fn})
}
// Shutdown runs all phases sequentially with independent timeouts.
func (s *ShutdownManager) Shutdown(log *slog.Logger) error {
s.mu.Lock()
phases := s.phases
s.mu.Unlock()
var errs []error
for _, phase := range phases {
ctx, cancel := context.WithTimeout(context.Background(), phase.timeout)
log.Info("shutdown phase starting", "phase", phase.name)
if err := phase.fn(ctx); err != nil {
log.Error("shutdown phase failed", "phase", phase.name, "error", err)
errs = append(errs, fmt.Errorf("phase %s: %w", phase.name, err))
} else {
log.Info("shutdown phase complete", "phase", phase.name)
}
cancel()
}
return errors.Join(errs...)
}// ShutdownManager orchestrates ordered, phased shutdown.
type ShutdownManager struct {
mu sync.Mutex
phases []shutdownPhase
timeout time.Duration
}
type shutdownPhase struct {
name string
timeout time.Duration
fn func(ctx context.Context) error
}
func NewShutdownManager(total time.Duration) *ShutdownManager {
return &ShutdownManager{timeout: total}
}
// Register adds a shutdown function to a named phase.
// Phases execute in registration order.
func (s *ShutdownManager) Register(name string, timeout time.Duration, fn func(ctx context.Context) error) {
s.mu.Lock()
defer s.mu.Unlock()
s.phases = append(s.phases, shutdownPhase{name, timeout, fn})
}
// Shutdown runs all phases sequentially with independent timeouts.
func (s *ShutdownManager) Shutdown(log *slog.Logger) error {
s.mu.Lock()
phases := s.phases
s.mu.Unlock()
var errs []error
for _, phase := range phases {
ctx, cancel := context.WithTimeout(context.Background(), phase.timeout)
log.Info("shutdown phase starting", "phase", phase.name)
if err := phase.fn(ctx); err != nil {
log.Error("shutdown phase failed", "phase", phase.name, "error", err)
errs = append(errs, fmt.Errorf("phase %s: %w", phase.name, err))
} else {
log.Info("shutdown phase complete", "phase", phase.name)
}
cancel()
}
return errors.Join(errs...)
}Wiring It Up
func main() {
logger := slog.Default()
sm := NewShutdownManager(60 * time.Second)
// --- HTTP Server ---
srv := &http.Server{Addr: ":8080", Handler: buildHandler()}
sm.Register("http-stop-accepting", 5*time.Second, func(ctx context.Context) error {
// Stop accepting new requests immediately
return srv.Shutdown(ctx)
})
// --- Background Worker ---
workerCtx, workerCancel := context.WithCancel(context.Background())
workerDone := make(chan struct{})
go func() {
defer close(workerDone)
runWorker(workerCtx)
}()
sm.Register("worker-drain", 20*time.Second, func(ctx context.Context) error {
workerCancel() // signal the worker to stop
select {
case <-workerDone:
return nil
case <-ctx.Done():
return fmt.Errorf("worker did not drain in time: %w", ctx.Err())
}
})
// --- Database ---
db := connectDB()
sm.Register("db-close", 5*time.Second, func(ctx context.Context) error {
return db.Close()
})
// --- Signal handling ---
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
// Start serving
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
logger.Error("server error", "error", err)
os.Exit(1)
}
}()
logger.Info("server started", "addr", ":8080")
sig := <-quit
logger.Info("shutdown initiated", "signal", sig)
if err := sm.Shutdown(logger); err != nil {
logger.Error("shutdown completed with errors", "error", err)
os.Exit(1)
}
logger.Info("shutdown complete")
}func main() {
logger := slog.Default()
sm := NewShutdownManager(60 * time.Second)
// --- HTTP Server ---
srv := &http.Server{Addr: ":8080", Handler: buildHandler()}
sm.Register("http-stop-accepting", 5*time.Second, func(ctx context.Context) error {
// Stop accepting new requests immediately
return srv.Shutdown(ctx)
})
// --- Background Worker ---
workerCtx, workerCancel := context.WithCancel(context.Background())
workerDone := make(chan struct{})
go func() {
defer close(workerDone)
runWorker(workerCtx)
}()
sm.Register("worker-drain", 20*time.Second, func(ctx context.Context) error {
workerCancel() // signal the worker to stop
select {
case <-workerDone:
return nil
case <-ctx.Done():
return fmt.Errorf("worker did not drain in time: %w", ctx.Err())
}
})
// --- Database ---
db := connectDB()
sm.Register("db-close", 5*time.Second, func(ctx context.Context) error {
return db.Close()
})
// --- Signal handling ---
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
// Start serving
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
logger.Error("server error", "error", err)
os.Exit(1)
}
}()
logger.Info("server started", "addr", ":8080")
sig := <-quit
logger.Info("shutdown initiated", "signal", sig)
if err := sm.Shutdown(logger); err != nil {
logger.Error("shutdown completed with errors", "error", err)
os.Exit(1)
}
logger.Info("shutdown complete")
}The Worker Pattern That Actually Drains
Most workers look like this:
// โ This stops immediately, dropping work
func runWorker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case job := <-queue:
process(job)
}
}
}// โ This stops immediately, dropping work
func runWorker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case job := <-queue:
process(job)
}
}
}The problem: if ctx is cancelled while process(job) is running, the next iteration returns immediately โ leaving the queue full of unprocessed items.
Here is a draining worker:
// โ
Finishes current work and drains remaining items before stopping
func runWorker(ctx context.Context, queue <-chan Job) {
for {
select {
case job, ok := <-queue:
if !ok {
return // channel closed, we're done
}
process(job) // always finish what we started
case <-ctx.Done():
// Drain remaining items with a short deadline
drainCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
drainQueue(drainCtx, queue)
return
}
}
}
func drainQueue(ctx context.Context, queue <-chan Job) {
for {
select {
case job, ok := <-queue:
if !ok {
return
}
process(job)
case <-ctx.Done():
log.Printf("drain deadline exceeded, %d jobs remaining", len(queue))
return
}
}
}// โ
Finishes current work and drains remaining items before stopping
func runWorker(ctx context.Context, queue <-chan Job) {
for {
select {
case job, ok := <-queue:
if !ok {
return // channel closed, we're done
}
process(job) // always finish what we started
case <-ctx.Done():
// Drain remaining items with a short deadline
drainCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
drainQueue(drainCtx, queue)
return
}
}
}
func drainQueue(ctx context.Context, queue <-chan Job) {
for {
select {
case job, ok := <-queue:
if !ok {
return
}
process(job)
case <-ctx.Done():
log.Printf("drain deadline exceeded, %d jobs remaining", len(queue))
return
}
}
}Handling the Double-Signal Problem
In Kubernetes, if your pod doesn't exit within terminationGracePeriodSeconds, it gets a SIGKILL. There's no cleanup โ it's just dead. So you need two layers:
- SIGTERM: Begin graceful shutdown (your shutdown manager)
- SIGKILL: Kubernetes-imposed hard deadline (unavoidable)
But users and CI pipelines will also sometimes hit Ctrl+C twice. You should respect that:
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
sig := <-quit
logger.Info("shutdown initiated", "signal", sig)
// Start shutdown in a goroutine
shutdownDone := make(chan error, 1)
go func() {
shutdownDone <- sm.Shutdown(logger)
}()
// If we get a second signal, exit immediately
select {
case err := <-shutdownDone:
if err != nil {
os.Exit(1)
}
case sig := <-quit:
logger.Warn("forced shutdown", "signal", sig)
os.Exit(1)
}quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
sig := <-quit
logger.Info("shutdown initiated", "signal", sig)
// Start shutdown in a goroutine
shutdownDone := make(chan error, 1)
go func() {
shutdownDone <- sm.Shutdown(logger)
}()
// If we get a second signal, exit immediately
select {
case err := <-shutdownDone:
if err != nil {
os.Exit(1)
}
case sig := <-quit:
logger.Warn("forced shutdown", "signal", sig)
os.Exit(1)
}Liveness vs. Readiness During Shutdown
In kubernetes, your readiness probe should return unhealthy the moment shutdown starts.
This tells the load balancer to stop sending traffic before your server closes the listener. Without this, you'll get a window where requests are being routed to a pod that's about to stop accepting them.
var shuttingDown atomic.Bool
// Readiness endpoint
mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) {
if shuttingDown.Load() {
http.Error(w, "shutting down", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
// In your signal handler, before starting shutdown:
shuttingDown.Store(true)
// Give the load balancer time to see the 503 and stop routing
time.Sleep(5 * time.Second)
// Now begin actual shutdown
sm.Shutdown(logger)var shuttingDown atomic.Bool
// Readiness endpoint
mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) {
if shuttingDown.Load() {
http.Error(w, "shutting down", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
// In your signal handler, before starting shutdown:
shuttingDown.Store(true)
// Give the load balancer time to see the 503 and stop routing
time.Sleep(5 * time.Second)
// Now begin actual shutdown
sm.Shutdown(logger)That 5-second sleep looks wrong but it's correct. It's sometimes called the "pre-stop sleep" pattern. Kubernetes also supports lifecycle.preStop hooks for this, but doing it in-process is more reliable.
Testing Your Shutdown
This is the most neglected part. You can't verify deterministic shutdown without a test:
func TestGracefulShutdown(t *testing.T) {
sm := NewShutdownManager(10 * time.Second)
var order []string
var mu sync.Mutex
record := func(name string) func(ctx context.Context) error {
return func(ctx context.Context) error {
mu.Lock()
order = append(order, name)
mu.Unlock()
return nil
}
}
sm.Register("first", time.Second, record("first"))
sm.Register("second", time.Second, record("second"))
sm.Register("third", time.Second, record("third"))
err := sm.Shutdown(slog.Default())
require.NoError(t, err)
mu.Lock()
defer mu.Unlock()
assert.Equal(t, []string{"first", "second", "third"}, order)
}
func TestShutdownContinuesAfterPhaseError(t *testing.T) {
sm := NewShutdownManager(10 * time.Second)
sm.Register("fails", time.Second, func(ctx context.Context) error {
return errors.New("boom")
})
ran := false
sm.Register("still-runs", time.Second, func(ctx context.Context) error {
ran = true
return nil
})
err := sm.Shutdown(slog.Default())
assert.Error(t, err)
assert.True(t, ran, "second phase should run even after first fails")
}func TestGracefulShutdown(t *testing.T) {
sm := NewShutdownManager(10 * time.Second)
var order []string
var mu sync.Mutex
record := func(name string) func(ctx context.Context) error {
return func(ctx context.Context) error {
mu.Lock()
order = append(order, name)
mu.Unlock()
return nil
}
}
sm.Register("first", time.Second, record("first"))
sm.Register("second", time.Second, record("second"))
sm.Register("third", time.Second, record("third"))
err := sm.Shutdown(slog.Default())
require.NoError(t, err)
mu.Lock()
defer mu.Unlock()
assert.Equal(t, []string{"first", "second", "third"}, order)
}
func TestShutdownContinuesAfterPhaseError(t *testing.T) {
sm := NewShutdownManager(10 * time.Second)
sm.Register("fails", time.Second, func(ctx context.Context) error {
return errors.New("boom")
})
ran := false
sm.Register("still-runs", time.Second, func(ctx context.Context) error {
ran = true
return nil
})
err := sm.Shutdown(slog.Default())
assert.Error(t, err)
assert.True(t, ran, "second phase should run even after first fails")
}Write integration tests that send a SIGTERM to your process and verify:
- In-flight requests complete
- No DB transactions are left open
- Message offsets are committed
Thanks for reading. Read these too
Stop using Go configuration frameworks โ Master explicit configuration How to actually design a configuration that scales with your architecture โ not against it
Forget Go dependency injection frameworks โ Do this instead Because simplicity scales better than framework abstraction
5 Go patterns that made my code self documenting Here is how small design decision in Go eliminated the need for Most comments