Middle+
What is graceful shutdown and how does it work in Go?
sobes.tech AI
Answer from AI
Graceful shutdown is the proper termination of an application, during which it manages to complete current operations, release resources, and close connections correctly before fully stopping.
In Go, graceful shutdown is usually implemented by handling system signals (e.g., SIGINT, SIGTERM). When a signal is received, the application begins the shutdown process:
- Stops accepting new requests.
- Completes processing of current requests or tasks.
- Releases resources (databases, files, connections).
- Shuts down and exits.
Example of implementing graceful shutdown in Go:
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
srv := &http.Server{Addr: ":8080"}
// Run server in a separate goroutine
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("ListenAndServe(): %v", err)
}
}()
// Create channel to receive signals
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit // wait for signal
log.Println("Shutting down server...")
// Create context with timeout for shutdown
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
log.Println("Server exiting")
}
Thus, the application terminates correctly without interrupting active connections and operations.