Golang & Concurrency (50 Qs)•Part 3: Go Microservices, HTTP, gRPC & Architecture (33 - 44)
Implementing Graceful Shutdown in Go Microservices.
senior LevelCode ExampleSystem DesigngRPCMicroservices
In Simple Words:
When Kubernetes terminates a pod, it sends SIGTERM. A graceful shutdown allows active in-flight HTTP requests to complete before exiting:
go
server := &http.Server{Addr: ":8080", Handler: mux}
// Listen for termination signals
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()
<-stop // Wait for SIGTERM
// Grace period for active requests to finish
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Forced shutdown: %v", err)
}