Build a Go microservice boilerplate with graceful shutdown. When receiving SIGTERM, stop accepting new requests, wait for active requests to finish with a timeout, and close database connections properly before exiting.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The plan is to implement a Go microservice with an HTTP server that gracefully shuts down on SIGINT/SIGTERM, using server.Shutdown with a context timeout to stop accepting new requests and wait for active ones to finish, plus properly closing the database connection afterward. I'll illustrate this with code showing signal handling, server start in a goroutine, and optional WaitGroup tracking wrapped around HTTP handlers.
Below is a minimal-but-complete Go microservice boilerplate that demonstrates graceful shutdown:
Listens for SIGTERM/SIGINT.
Stops accepting new requests on signal.
Waits for in-flight requests to finish with a configurable timeout.
Closes database connections before exiting.
You can adapt the database driver, routing, and handler logic to your needs.
go
// main.go
package main
import (
"context"
"database/sql"
"errors"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
_ "github.com/lib/pq" // Example for Postgres; swap out for your driver
)
const (
serverAddr = ":8080"
shutdownTimeout = 10 * time.Second
readHeaderTimeout = 5 * time.Second
)
// DBClient is an interface to abstract database operations.
// Replace with your own type or just use *sql.DB directly.
type DBClient interface {
PingContext(ctx context.Context) error
Close() error
}
func main() {
// Initialize DB connection (example: Postgres)
db, err := initDB()
if err != nil {
log.Fatalf("initDB error: %v", err)
}
defer func() {
if err := db.Close(); err != nil {
log.Printf("db.Close error: %v", err)
}
}()
// Create the main router/handler
router := http.NewServeMux()
router.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := db.PingContext(ctx); err != nil {
http.Error(w, "DB unreachable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Simulate some work
time.Sleep(100 * time.Millisecond)
w.Write([]byte("hello"))
})
// Wrap the router in a request-tracking middleware to handle in-flight requests
trackedHandler := requestTrackingMiddleware(router)
server := &http.Server{
Addr: serverAddr,
Handler: trackedHandler,
ReadHeaderTimeout: readHeaderTimeout,
}
// Start the server in a goroutine
serverErrors := make(chan error, 1)
go func() {
log.Printf("Starting server on %s", serverAddr)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
serverErrors <- err
}
}()
// Listen for OS signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
select {
case err := <-serverErrors:
log.Fatalf("server error: %v", err)
case sig := <-sigChan:
log.Printf("received signal %v; initiating graceful shutdown", sig)
}
// Create a context for the shutdown deadline
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
// Stop accepting new requests, wait for in-flight to complete or timeout
if err := server.Shutdown(ctx); err != nil {
log.Printf("server shutdown error: %v", err)
}
// Close DB connections (deferred above), or explicitly:
// if err := db.Close(); err != nil {
// log.Printf("db close error: %v", err)
// }
log.Println("server stopped gracefully")
}
// initDB initializes a database connection. Replace DSN/driver as appropriate.
func initDB() (*sql.DB, error) {
// Example DSN: postgres://user:pass@host:port/dbname?sslmode=disable
dsn := "postgres://user:pass@localhost:5432/mydb?sslmode=disable"
db, err := sql.Open("postgres", dsn)
if err != nil {
return nil, err
}
// Optional: ping to verify connection
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, err
}
return db, nil
}
// requestTrackingMiddleware tracks active requests using a WaitGroup.
// On shutdown, http.Server.Shutdown will no longer accept new requests,
// but we also ensure all in-flight requests finish (or time out).
func requestTrackingMiddleware(next http.Handler) http.Handler {
var wg sync.WaitGroup
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wg.Add(1)
defer wg.Done()
next.ServeHTTP(w, r)
})
}
How it works
Server startup
The server is created with http.Server{Addr: serverAddr, Handler: trackedHandler} and started in a goroutine with ListenAndServe.
Signal handling
The process listens for SIGINT/SIGTERM on sigChan. When received, it triggers a graceful shutdown.
Stop accepting new requests server.Shutdown(ctx) closes listeners so no new connections are accepted.
Wait for active requests with timeout Shutdown blocks until the context expires or all connections are idle. We wrap handlers with a middleware that tracks active requests using a WaitGroup. If you want to wait on this explicitly beyond Shutdown, you can store the WaitGroup outside and do wg.Wait() with a select on timeout; however, http.Server.Shutdown already waits up to the provided context deadline and then forcibly closes lingering connections.
Close database
After shutdown completes (or times out), the DB handle is closed to free resources.
Notes / Extensions
Change the DSN in initDB and the driver import to match your database.
Add logging, configuration, or environment-variable parsing as needed.
For bigger apps, you might split this into packages (e.g., cmd, internal/server, internal/db) and add dependency injection.
If you need more control over in-flight request tracking (e.g., to wait after Shutdown returns), you can embed the WaitGroup in a struct and explicitly Wait() on it before exit.