By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A shutdown that returns immediately is not graceful; it just looks neat in logs. This lab holds a request open, starts a shutdown, and proves the server refuses to finish until the request completes. The deterministic version uses channels instead of sleeps: the handler signals that it is running, blocks until the test releases it, and the shutdown goroutine is observed still waiting in between.
The lifecycle to prove: stop accepting new connections, let in-flight handlers complete, then exit. http.Server.Shutdown does the first two and returns when the last handler finishes or the context deadline expires. Your queue and background workers need the same treatment — close intake, drain, then exit.
http.Server on a net.Listen listener bound to 127.0.0.1:0 so the port is chosen by the OS.started channel and block on a release channel.started, then call Shutdown in a goroutine and observe that it has not returned.release; the request completes, then Shutdown returns.package main
import (
"context"
"fmt"
"net"
"net/http"
"sync"
"time"
)
func main() {
started := make(chan struct{})
release := make(chan struct{})
mux := http.NewServeMux()
mux.HandleFunc("GET /work", func(w http.ResponseWriter, _ *http.Request) {
close(started)
<-release
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("done"))
})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
server := &http.Server{Handler: mux, ReadHeaderTimeout: time.Second}
go func() {
_ = server.Serve(listener)
}()
var requests sync.WaitGroup
requests.Add(1)
status := 0
go func() {
defer requests.Done()
resp, err := http.Get("http://" + listener.Addr().String() + "/work")
if err != nil {
panic(err)
}
defer resp.Body.Close()
status = resp.StatusCode
}()
<-started
shutdownDone := make(chan struct{})
go func() {
defer close(shutdownDone)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
panic(err)
}
}()
time.Sleep(20 * time.Millisecond)
select {
case <-shutdownDone:
fmt.Println("unexpected: shutdown finished with a request in flight")
default:
fmt.Println("shutdown waiting for in-flight request")
}
close(release)
requests.Wait()
<-shutdownDone
fmt.Println("in-flight status:", status)
fmt.Println("shutdown completed cleanly")
}| Shutdown step | HTTP server | Queue worker |
|---|---|---|
| Stop intake | Server.Shutdown closes the listener | Close the jobs channel |
| Drain in-flight | Waits for active handlers | Workers finish the current job |
| Deadline | Shutdown context timeout | Context deadline on the drain |
| Exit cleanly | http.ErrServerClosed is success | WaitGroup join, then return |
| Report | Log the shutdown reason and duration | Record unprocessed job count |
Key takeaways
Graceful shutdown stops intake, drains in-flight work, then exits.
http.Server.Shutdown returns only after active handlers finish or the deadline expires.
Prove draining with channels, not sleeps: hold a handler open and observe the shutdown goroutine waiting.
Queue workers need the same sequence: close intake, drain, join.
Keep the shutdown deadline shorter than the orchestrator's grace period.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.