Timeouts and Graceful Shutdown

1 min read
#go #reliability #web
>> Series Navigation

Building Production Go Web Servers

  1. 1. ServeMux Foundations
  2. 2. Middleware Without Magic
  3. > 3. Timeouts and Graceful Shutdown
  4. 4. Logs, Metrics, and Traces

Production servers need boundaries. Without timeouts, slow clients and stuck dependencies can consume resources indefinitely.

Configure the Server

srv := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       10 * time.Second,
    WriteTimeout:      30 * time.Second,
    IdleTimeout:       60 * time.Second,
}

Propagate Cancellation

Pass r.Context() into downstream calls so work stops when the client leaves or the server shuts down.

Shutdown Flow

Listen for SIGTERM, stop accepting new traffic, allow in-flight requests to finish, then close background workers.