Config and shutdown

A process must be able to finish: hear the signal, stop accepting new work, and close the database.

Config is read explicitly at startup: flags, environment variables, or a file. A default is fine for an address such as :8080 in development. A secret with no value is not replaced by a quiet empty string, and you do not start "however it turns out". If something required is missing, the process exits with an error before it starts listening on a port.

Shutdown in Go looks like a context from a signal:

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
<-ctx.Done()

SIGTERM is sent by an orchestrator and by docker stop. SIGINT is Ctrl+C. Catching the signal and immediately calling os.Exit is rough: the defers will not run, and requests will be cut off. Instead you call server.Shutdown. It stops accepting new connections and waits for the active ones within its context. Then the database is closed.

Shutdown looks at a context with its own deadline. Waiting forever is also bad: a stuck handler must not hold a rollout forever. A few seconds to finish is the usual compromise. Close cuts connections immediately. It is left as a fallback if the gentle shutdown did not fit in time.

Background goroutines must see the same context. Otherwise the server is no longer listening, and a worker is still writing into a closed database. Every go still needs a reason to finish.

After this trail you do not "know all of Go". You can read and write a small service: packages, errors, tests, goroutines with cancellation, and HTTP without magic. From here Middle grows on other people's code, on profiles, and on production incidents, not on one more tour of the syntax. Profiling, unsafe, the insides of the scheduler, and distributed transactions are separate trails. They are not pretended to have been learned in one course.

Practice

  1. Which signal Docker sends

    Which signal does docker stop send to a container by default?

    • SIGKILL immediately
    • SIGTERM
    • SIGHUP and nothing else
    • None. The container simply disappears with no signal
  2. Shutdown and Close

    How does http.Server.Shutdown differ from Close?

    • Shutdown waits for active requests, Close cuts them off
    • There is no difference
    • Close is gentler, Shutdown kills the process immediately
    • Shutdown works only in tests
  3. What the trail already covered

    Mark what you can now do in a small Go service without syntax hints.

    • Lay the code out in packages and not cycle the imports
    • Stop the server on SIGTERM without cutting off every defer
    • Write your own scheduler changes through unsafe
    • Check a pure function with a table test