Graceful shutdown in Go: the pattern every service needs

Posted by Kashyap Rishi · 2025-05-28

Every Go service should handle SIGTERM gracefully. Drain connections, flush buffers, close databases. This pattern has saved us from data loss dozens of times.

// Graceful shutdown pattern for Go services
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()

srv := &http.Server{Addr: ":8080", Handler: mux}
go func() {
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatal(err)
	}
}()

<-ctx.Done()
log.Println("Shutting down gracefully...")

shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)

Explore GitVibes