Graceful Shutdown
Properly shut down server while completing active requests.
Running
go run main.go
Server starts on http://localhost:3090
Testing Graceful Shutdown
- Start server
- Make a request to
/slow(takes 5 seconds) - Press
Ctrl+Cwhile request is processing - Watch logs - server waits for request to complete
- Server shuts down gracefully
Implementation
Signal Handling
shutdownSignal := make(chan os.Signal, 1)
signal.Notify(shutdownSignal, os.Interrupt, syscall.SIGTERM)
// Wait for signal
<-shutdownSignal
Wait for Active Requests
for {
if activeRequests == 0 {
log.Println("✅ All requests completed")
return
}
log.Printf("⏳ Waiting... (active: %d)", activeRequests)
time.Sleep(1 * time.Second)
}
Timeout
ctx, cancel := context.WithTimeout(
context.Background(),
30 * time.Second,
)
defer cancel()
Shutdown Flow
- Receive shutdown signal (Ctrl+C or SIGTERM)
- Stop accepting new connections
- Wait for active requests to complete
- Execute cleanup tasks
- Exit process
Best Practices
- Set appropriate timeout (30-60 seconds)
- Log shutdown progress
- Track active requests
- Clean up resources
- Notify monitoring systems