Golang. How to write gracefull shutdown
- User
Golang. How to write gracefull shutdown
- Assistant
Golang. How to write gracefull shutdown
To implement a graceful shutdown in Go (Golang), you'll need to ensure that your application can handle OS signals to initiate the shutdown process, allow ongoing operations to complete, and release any resources before exiting. This is particularly important for servers and long-running applications to prevent data loss, corruption, or other unintended side effects.
Here's a step-by-step guide on how to write a graceful shutdown in Go:
Set Up Signal Handling
Use the os/signal package to listen for interrupt signals like SIGINT (Ctrl+C) or SIGTERM. This allows your application to detect when it's supposed to shut down.
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
Start Your Server or Main Process in a Goroutine
Run your main server or process in a separate goroutine. This allows the main goroutine to continue running and listen for the shutdown signal.
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Could not listen on %s: %v\n", addr, err)
}
}()
Wait for Shutdown Signal
Block the main goroutine until a signal is received. When a signal is caught, proceed to initiate the shutdown process.
<-quit
log.Println("Shutting down server...")
Initiate Server Shutdown
Use the Shutdown method provided by the net/http package to gracefully shut down the server. This method allows the server to stop accepting new connections but still finishes processing ongoing requests.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
Wait for Background Processes to Finish
If you have background goroutines (e.g., workers, processing jobs), use synchronization primitives like sync.WaitGroup to wait for them to complete their tasks.
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// Background processing
}()
wg.Wait()
Clean Up Resources
Close any open resources like database connections, file handles, or network sockets to prevent resource leaks.
if err := db.Close(); err != nil {
log.Printf("Error closing database: %v", err)
}
Here's a complete example demonstrating how to implement a graceful shutdown in an HTTP server:
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
addr := ":8080"
server := &http.Server{
Addr: addr,
Handler: http.DefaultServeMux,
}
// Example handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world!"))
})
// Start the server in a goroutine
go func() {
log.Printf("Starting server on %s\n", addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Could not listen on %s: %v\n", addr, err)
}
}()
// Channel to listen for interrupt or terminate signals
quit := make(chan os.Signal, 1)
// relay os.Interrupt to the quit channel
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
// Block until a signal is received.
<-quit
log.Println("Shutting down server...")
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
// Optionally, wait for other services to gracefully shutdown
// e.g., close database connections, flush logs, etc.
// Wait for background goroutines to finish
var wg sync.WaitGroup
// Assume you have some background workers
wg.Wait()
log.Println("Server exiting")
}
In this example:
os.Signal and signal.Notify to listen for OS interrupt signals.sync.WaitGroup.Use Contexts: Pass context.Context to your goroutines and handlers so they can listen for cancellation signals and stop processing if needed.
func handler(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
// Handle cancellation
return
default:
// Proceed with processing
}
}
Handle Timeouts Appropriately: Set reasonable timeouts for the shutdown process to prevent long waits.
Close Idle Connections: For servers, consider enabling keep-alives so idle connections don't prevent shutdown.
server := &http.Server{
Addr: addr,
Handler: yourHandler,
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
Test the Shutdown Process: Regularly test your graceful shutdown to ensure all components of your application respond correctly to shutdown signals.
Implementing a graceful shutdown in Go involves coordinating signal handling, context cancellation, and proper resource management. By following the steps above, you can ensure that your Go applications shut down cleanly, without leaving behind unfinished tasks or leaked resources. This approach enhances the reliability and robustness of your applications, especially in production environments where uptime and data integrity are critical.
Not yet included in a published release.