Ensures backend servers handle SIGTERM and other termination signals by draining active requests before exiting. Use when implementing or reviewing HTTP server startup/shutdown logic. Do not use for short-lived CLI tools or scripts that do not bind to a port.
Backend services must listen for OS signals (like SIGTERM and SIGINT) and perform a Graceful Shutdown procedure. This ensures that no in-flight requests are dropped abruptly during deployments or scaling events.
SIGTERM to safely drain traffic.signal.Notify (Go) or process.on('SIGTERM') (Node.js) to catch signals.// Create a context that listens for signals
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Start server in goroutine
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for signal
<-ctx.Done()
// Shutdown with timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
log.Fatal("Server forced to shutdown:", err)
}