---
title: Implement Graceful Shutdown
impact: MEDIUM
impactDescription: prevents data loss and ensures clean connection handling
tags: gin, go, stability, quality
---

## Implement Graceful Shutdown

Web servers should handle termination signals (`SIGINT`, `SIGTERM`) to allow inflight requests to finish and to close database connections cleanly. Gin's `Run()` method blocks and doesn't support this out of the box; use `http.Server` instead.

**Incorrect (standard Run):**

```go
func main() {
    r := gin.Default()
    r.GET("/", handler)
    r.Run(":8080") // Blocks and dies immediately on CTRL+C
}
```

**Correct (graceful shutdown):**

```go
func main() {
    router := gin.Default()
    srv := &http.Server{
        Addr:    ":8080",
        Handler: router,
    }

    go func() {
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("listen: %s\n", err)
        }
    }()

    // Wait for interrupt signal
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    if err := srv.Shutdown(ctx); err != nil {
        log.Fatal("Server Shutdown:", err)
    }
}
```

**Benefits:**
- Prevents dropping active user connections
- Allows finishing long-running database transactions
- Ensures monitoring tools report clean shutdown instead of "crash"

**Tools:** Go Standard Library, Gin
