Go Web Frameworks interview question · Most asked

How do you implement graceful shutdown for a Go HTTP server?

Create a free account to save this page, take notes and track your progress. Sign in

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

← All Go Web Frameworks questions

Was this page helpful?