liveBook · Manning

Graceful shutdown

As explained in Go in Practice, Second Edition

A graceful shutdown is an orderly termination procedure that allows active work and resources to be completed or released before a service stops.

A graceful shutdown stops a web server without abruptly abandoning active work. The server listens for operating-system signals, stops accepting new connections, and gives current request handlers time to finish before exiting. section 2.3.2

A practical implementation follows this sequence:

  • Create a signal channel and register interrupt and kill signals with signal.Notify. section 2.3.2
  • Run ListenAndServe in a goroutine so the main flow can monitor the signal channel concurrently. section 2.3.2
  • After a signal arrives, call the server's Shutdown method; it stops new connections and waits for current requests to complete. section 2.3.2
Listing 2.14 More graceful shutdown using signals
package main

import (
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "time"
)

func main() {
    handleFunc := newHandler()    #1
    server := &http.Server{       #1
        Addr:    “:8080",
        Handler: handleFunc,
    }

    ch := make(chan os.Signal, 1)               #2
    signal.Notify(ch, os.Interrupt, os.Kill)    #2

    go func() {
        server.ListenAndServe()     #3
    }()

    time.Sleep(5 * time.Second)                    #4
    <-ch                                          
    if err := server.Shutdown(nil); err != nil {
        panic(err)                                
    }
}

type handler struct{}

func newHandler() *handler {
    return &handler{}
}

func (h *handler) ServeHTTP(res http.ResponseWriter, 
req *http.Request) { #5
    query := req.URL.Query()
    name := query.Get("name")
    if name == "" {
        name = "Inigo Montoya"
    }
    fmt.Fprint(res, "Hello, my name is ", name)
}

A complete Go server wires an HTTP handler, a signal channel, concurrent ListenAndServe execution, a wait, and Shutdown into one runnable example. section 2.3.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains signal channels, goroutines, and Shutdown behavior, while deferring deeper concurrency details.
Examples
Uses a Go HTTP server on port 8080 with a Hello World handler and a signal-driven Shutdown call.
What it assumes
Assumes basic Go HTTP servers and handlers, then adds goroutines and operating-system signal handling.
What you can do after
Operate a Go HTTP server that drains active requests after receiving an operating-system signal.
How it connects
Connects operating-system signals, goroutines, HTTP handlers, and server connection management.

Also explained in

Compare how 4 books explain graceful shutdown →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.