patterngoMajorpending
Go graceful shutdown pattern
Viewed 0 times
graceful shutdownsignal handlinghttp serversigtermsigint
Problem
Go HTTP servers need to handle shutdown gracefully, finishing in-flight requests before stopping.
Solution
Implement signal-based graceful shutdown:
For multiple services (DB, cache, workers):
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Simulate work
time.Sleep(2 * time.Second)
w.Write([]byte("OK"))
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Start server in goroutine
go func() {
log.Printf("Server starting on %s", srv.Addr)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down...")
// Give in-flight requests time to complete
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Forced shutdown: %v", err)
}
log.Println("Server stopped gracefully")
}For multiple services (DB, cache, workers):
// Shutdown in reverse order of startup
log.Println("Stopping HTTP server...")
srv.Shutdown(ctx)
log.Println("Closing worker pool...")
workerPool.Stop()
log.Println("Closing database...")
db.Close()
log.Println("Closing cache...")
cache.Close()Why
Without graceful shutdown, in-flight requests get terminated mid-response, database transactions are left incomplete, and resources leak.
Context
Go services that need clean shutdown
Revisions (0)
No revisions yet.