Configure timeouts and graceful server shutdown
Configure timeouts and graceful server shutdown
http.Server controls connection and request I/O timeouts. ReadHeaderTimeout limits header reading; ReadTimeout includes reading the entire request; WriteTimeout bounds response writing according to the server protocol; IdleTimeout limits waiting for another keep-alive request. These are not a general handler CPU deadline. Choose values for workload, size limits and streaming needs.
package main
import ( "fmt" "net/http" "time")
func main() { srv := &http.Server{ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16384} fmt.Println(srv.ReadHeaderTimeout, srv.ReadTimeout, srv.WriteTimeout, srv.IdleTimeout, srv.MaxHeaderBytes)}This example constructs a configuration without listening. MaxHeaderBytes limits request header parsing, not body bytes; enforce body limits separately. Zero values often mean no timeout or a documented fallback. The numbers are illustrative, not universal defaults. For slow streams choose a specific deadline strategy rather than blindly using short write timeouts.
Expected output:
2s 5s 10s 30s 16384Allow an active request to finish
package main
import ( "context" "errors" "fmt" "io" "net" "net/http" "time")
func drain() error { entered := make(chan struct{}) release := make(chan struct{}) srv := &http.Server{ReadHeaderTimeout: time.Second, ReadTimeout: 2 * time.Second, WriteTimeout: 3 * time.Second, IdleTimeout: time.Second, MaxHeaderBytes: 8192, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(entered); <-release; fmt.Fprint(w, "done") })} ln, e := net.Listen("tcp", "127.0.0.1:0") if e != nil { return e } defer ln.Close() defer srv.Close() served := make(chan error, 1) go func() { served <- srv.Serve(ln) }() client := &http.Client{Timeout: 4 * time.Second} defer client.CloseIdleConnections() received := make(chan error, 1) go func() { res, e := client.Get("http://" + ln.Addr().String()) if e == nil { b, readErr := io.ReadAll(res.Body) res.Body.Close() e = readErr if e == nil && (res.StatusCode != 200 || string(b) != "done") { e = errors.New("bad response") } } received <- e }() select { case <-entered: case <-time.After(2 * time.Second): close(release) return errors.New("handler did not start") } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() stopping := make(chan error, 1) go func() { stopping <- srv.Shutdown(ctx) }() select { case e = <-served: case <-ctx.Done(): close(release) return ctx.Err() } close(release) if !errors.Is(e, http.ErrServerClosed) { return fmt.Errorf("serve: %v", e) } return errors.Join(<-received, <-stopping)}func main() { fmt.Println("graceful:", drain() == nil)}The fixture starts on 127.0.0.1 with an ephemeral port. Channels ensure one handler is active before Shutdown begins; Serve returns ErrServerClosed when the listener is closed. Releasing the handler permits the active response to finish. Shutdown closes listeners and idle connections, then waits for active connections to become idle until its context expires. Wait for Shutdown itself before exiting. It does not manage hijacked connections or arbitrary background tasks. In a real process use signal.NotifyContext, a fresh bounded shutdown context, explicit worker cleanup and a defined fallback (Close can interrupt active connections).
Expected output:
graceful: trueTry it locally
Create a server with a 1s header timeout and 15s idle timeout; print both. Then run the drain example separately and explain why Serve can return before Shutdown completes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 08: Configure timeouts and graceful server shutdown
Check the lesson objective before moving on.
What does Shutdown wait for?
Which field limits reading request headers?