Go Web Frameworks interview question · Most asked
How do you implement graceful shutdown for a Go HTTP server?
Summary
Listen for SIGINT/SIGTERM (signal.NotifyContext), then call server.Shutdown(ctx) with a timeout: it stops accepting new connections and waits for in-flight requests to finish before returning.
Longer Answer
Also close other resources (database pools, message consumers) after the server drains, and fail readiness checks at the start of shutdown so load balancers stop sending traffic.
Code Example
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go srv.ListenAndServe()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)
Key Points
- signal.NotifyContext for SIGTERM.
- server.Shutdown(ctx) drains requests.
- Close resources after; fail readiness first.
Deep dive: Go Web Frameworks: Production Ready
More most-asked Go Web Frameworks questions
- How do you test HTTP handlers in Go?
- How should a Go service use database/sql correctly?
- Compare Gin, Echo, Chi and Fiber.
- What is the http.Handler interface, and why is it central to Go web development?
- How do you pass request-scoped values (like the current user) through middleware in Go?
- Do you need a web framework in Go? What does Go 1.22's ServeMux provide?
- How do you design consistent error responses in a Go API?