Sobes.tech
Senior

What is Graceful Shutdown and why is it needed?

sobes.tech AI

Answer from AI

Graceful Shutdown is the proper termination of an application or service, where it completes current tasks, releases resources, and does not accept new requests. This is necessary to prevent data loss, inconsistent states, and to ensure a smooth transition during updates or shutdowns.

In Go, this is usually implemented by listening to OS signals (such as SIGINT, SIGTERM) and subsequently calling shutdown functions:

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"
)

func main() {
    srv := &http.Server{Addr: ":8080"}

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

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt)
    <-quit

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

This approach allows completing current requests and properly stopping the server.

What is Graceful Shutdown and why is it needed… - sobes.tech