1. Why Shutdown exists and why a timeout is mandatory
When you first bring up an HTTP server, it seems that "stopping" it is as simple as exiting main(). Alas, a server is a social creature: it has active connections, requests "in progress", buffers, and clients that are under no obligation to behave politely. In this section, we will look at what exactly Shutdown does, and why without a timeout you risk getting a zombie process: it "should finish, apparently", but somehow it does not.
(*http.Server).Shutdown(ctx) is a graceful shutdown. The idea is this: the server stops accepting new connections and gives already started requests a chance to finish "normally". But the key word here is chance. If a request is stuck, the client holds the connection, the handler is too slow, or you are waiting on an external resource somewhere, the wait can drag on.
And this is where an important idea appears: the context sets the upper bound on waiting time. In Go, a context can signal that "time is up" through a deadline/timeout and cancellation. And context.WithTimeout is the standard way to create a derived context with a deadline.
If you call Shutdown(context.Background()), you are saying: "wait as long as needed". For production, that is like saying "I'm going away for five minutes" and disappearing for three days. So the rule is simple and strict:
Always call Shutdown with a context created via context.WithTimeout (a timeout is mandatory).
Here is a small table for reference:
| Method | What it does in practice | What happens to active requests | What is the catch |
|---|---|---|---|
|
graceful shutdown | tries to wait for completion | without a timeout it may wait forever |
|
hard shutdown | connections are cut | users may see disconnects/errors |
2. The canonical shutdown pattern with WithTimeout
Basic pattern: WithTimeout + defer cancel() + Shutdown
Many beginners try to "cut corners": write srv.Shutdown(context.Background()) or create a timeout but forget cancel(). That is normal: the brain saves energy and assumes "well, it will sort itself out". But contexts have resources (timers, links), and the correct pattern is not bureaucracy, but code hygiene.
The canonical shutdown pattern looks like this: create a context with a timeout, immediately set defer cancel(), then call Shutdown. WithTimeout creates a derived context that will be canceled automatically when the time expires.
A mini-example (in a vacuum, without signals and without a server "around" it):
package main
import (
"context"
"log"
"net/http"
"time"
)
func stopServer(srv *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("shutdown error: %v", err)
}
}
What matters here is not only that there is a timeout, but also that cancel() is called reliably. Yes, the context will be canceled by the timeout anyway, but cancel() is "clear your plate": release the associated resources earlier if we finished sooner.
How to log a Shutdown error
Beginners often expect Shutdown to be either "successful" or "broken". In reality, there is a third mode: "we tried, but time ran out". And that is not always a catastrophe — but it is always a signal that your application does not fully respect cancellation or that your timeout is genuinely too small.
If the timeout expires, you will usually see an error related to context.DeadlineExceeded. And ctx.Err() for such a context will also be context.DeadlineExceeded. This is the standard mechanism: the deadline arrives, the context is canceled, and operations should finish.
An example of a more "talkative" diagnosis without unnecessary drama:
package main
import (
"context"
"errors"
"log"
"net/http"
"time"
)
func shutdownWithLog(srv *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
log.Printf("shutdown: timeout exceeded")
return
}
log.Printf("shutdown error: %v", err)
}
}
It is important not to confuse two layers of errors:
- http.ErrServerClosed is the expected error from ListenAndServe when the server closes normally (filter it where the server is started).
- context.DeadlineExceeded is the signal that the shutdown procedure did not fit within the deadline (log it in the shutdown branch).
3. How to choose a shutdown timeout
It is tempting to give a universal number: "set 5 seconds and happiness will follow." But in programming, magic numbers do not work well (except for 42, but that is a different course). Instead, you need a way to reason: how much time does the server need to finish requests properly?
The logic is this: the shutdown timeout should be large enough for your "usual" requests to finish, and small enough so the process does not hang forever. If you build an API where a typical request runs for 20–50 milliseconds, then a 30-second shutdown sounds generous. If you have operations that really take 2–3 seconds (for example, heavy aggregation), then a 1-second shutdown will regularly cut the process off too early.
Because in Go context propagates deadlines and cancellation down the call stack, a proper architecture usually leads to handlers and dependencies either finishing within a reasonable time, or being canceled correctly via context.
In a tutorial task server (a hypothetical todo/tasks) you can start with 5 seconds. The main point is not the number, but that it exists and is written explicitly in the code.
A good style is to move the timeout into a constant so it does not get lost among the logic:
package main
import "time"
const shutdownTimeout = 5 * time.Second
4. Graceful shutdown in main(): signal, timeout, Shutdown
Overall scheme
In main(), the server is usually started and blocks the thread through ListenAndServe(). At the same time, the termination signal arrives "from outside", so we need a place where we wait for the signal and initiate shutdown. We do this through signal.NotifyContext and waiting for <-sigCtx.Done(), and then add the proper Shutdown with a timeout.
Schematically, it looks like this:
flowchart TD
A[main: HTTP server starts] --> B[ListenAndServe blocks]
A --> C["goroutine: wait for <-sigCtx.Done()"]
C --> D["create shutdownCtx = WithTimeout(...)"]
D --> E["call srv.Shutdown(shutdownCtx)"]
E --> F[ListenAndServe finishes]
Starting the server and waiting for a signal
Startup code (assume mux is already built):
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
mux := http.NewServeMux()
srv := &http.Server{Addr: ":8080", Handler: mux}
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go shutdownOnSignal(sigCtx, srv)
err := srv.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("server error: %v", err)
}
}
The most interesting part is hidden in shutdownOnSignal. Let's implement it so that the timeout is mandatory:
package main
import (
"context"
"log"
"net/http"
"time"
)
const shutdownTimeout = 5 * time.Second
func shutdownOnSignal(sigCtx context.Context, srv *http.Server) {
<-sigCtx.Done() // wait for the stop event
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("shutdown error: %v", err)
}
}
Notice the detail: we use WithTimeout(context.Background(), ...), not WithTimeout(sigCtx, ...). Why? Because sigCtx is already canceled at the moment we reach shutdown (we have just returned from <-sigCtx.Done()), and if we make it the parent, we get a context that is "canceled immediately". Then shutdown will effectively not wait at all.
That is exactly why in the shutdown branch you often use a separate "neutral" parent — context.Background().
Why Shutdown cannot be called simply "after ListenAndServe"
A typical beginner trap looks like this:
err := srv.ListenAndServe()
srv.Shutdown(...)
It seems logical: "when the server finishes working, then shutdown." But ListenAndServe is a blocking call: while the server is running, this line will not return. That means you simply will not reach Shutdown.
So shutdown is started "next to" it, most often via a goroutine: the main thread serves the server, and the parallel one waits for the stop signal and calls shutdown. This is not "magic", just two parallel tasks.
Small refactor of main() for readability
When code grows, main() turns into "noodles": routes, DI, logging, and shutdown. We are not doing deep layered architecture yet, but a small refactor is already useful: move server construction into a function and leave only the lifecycle in main().
Example:
package main
import (
"net/http"
)
func newServer() *http.Server {
mux := http.NewServeMux()
// mux.HandleFunc(...) // your handlers were already written earlier
return &http.Server{Addr: ":8080", Handler: mux}
}
Then main() becomes "cleaner":
package main
import (
"context"
"os"
"os/signal"
"syscall"
)
func main() {
srv := newServer()
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go shutdownOnSignal(sigCtx, srv)
runServer(srv)
}
And runServer is the place where we filter http.ErrServerClosed:
package main
import (
"errors"
"log"
"net/http"
)
func runServer(srv *http.Server) {
err := srv.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("server error: %v", err)
}
}
This split into functions is good because now you can almost physically not "accidentally" call Shutdown without a timeout: you have one function where shutdown lives, and the WithTimeout call is already there.
5. Common mistakes with Server.Shutdown(ctx) and timeouts
Mistake #1: Shutdown(context.Background()) "because it is easier".
This is the most dangerous version of "easier". It turns process termination into a lottery: if some request gets stuck, Shutdown may wait for a very long time. The fix is simple and disciplinary: create the shutdown context only through context.WithTimeout(...), and make the timeout value explicit in a constant.
Mistake #2: they use WithTimeout but forget cancel().
Even if the timeout triggers on its own, cancel() is the proper release of resources associated with the context. In Go, the convention is to always call cancel(), usually via defer cancel() right after creating the context. It is a small habit that unexpectedly saves a lot of nerves in large systems.
Mistake #3: they use an already canceled context as the parent for the shutdown context.
A common scenario: you waited for <-sigCtx.Done(), and then do context.WithTimeout(sigCtx, 5*time.Second). But sigCtx is already canceled, which means the child context will also be canceled immediately. As a result, shutdown is "instant" and there will be no waiting. It is better to create the context from context.Background() in the shutdown branch.
Mistake #4: they log http.ErrServerClosed as a "server error".
This is the expected completion of ListenAndServe during a normal shutdown. If you log it as an error, you get noise in the logs and false alarms. Filter it through errors.Is(err, http.ErrServerClosed) where the server is started.
Mistake #5: they ignore the Shutdown error.
If Shutdown did not fit within the timeout, you want at least to know it from the logs. Even in a learning project, it is useful to print a message; otherwise you will be sure that "everything shut down nicely", when in fact part of the requests was cut off by the deadline.
GO TO FULL VERSION