CodeGym /Cursos /Go SELF /Stopping an HTTP server without losing requests

Stopping an HTTP server without losing requests

Go SELF
Nível 63, Lição 0
Disponível

1. Why you cannot “just stop the process”

If you have only been writing educational programs so far, then “stopping the server” probably looked something like this: press Ctrl+C, the terminal goes “pffft”, and everything ends. For a small demo, that is fine. But as soon as the server starts handling real requests, an unpleasant truth suddenly appears: “the process exited” does not mean “clients received proper responses”.

Imagine that right now your service is processing a task-creation request, has already read the request body, has already started writing to storage... and then the process gets killed forcefully. The client may receive a broken connection, and the data may end up in a strange intermediate state. There are also long polling, large responses, slow clients, and all the other fun things that make backend developers start drinking herbal tea and calling it “observability”.

That is exactly why we introduce the concept of graceful shutdown: the server stops accepting new connections and tries to finish already started requests cleanly. In this lecture, we will build the skeleton of the server lifecycle: caught an OS signal → canceled the context → moved on to shutdown. The main thing is to wait for the event properly: via <-ctx.Done() and without “let’s wait 100 ms and check again” loops.

Which signals matter: SIGINT and SIGTERM

OS signals sound like something from the world of “kernels, drivers, and gloomy people in hoodies”, but in practice they are just the standard way for an operating system to tell your process: “it is time to shut down”. The idea is very simple: the process gets a chance to leave gracefully instead of disappearing in the middle of important work, like a supporting character in a side scene.

The most important signals for us are SIGINT and SIGTERM. SIGINT usually arrives when you press Ctrl+C in the terminal (that is, “the user asked to stop”). SIGTERM is a more “system-level” signal: process managers, containers, orchestrators, CI infrastructure, and even an admin who decided to stop the service in a civilized way often send it.

It is useful to keep a small meaning table in mind:

Signal How it usually arrives Human meaning
SIGINT
Ctrl+C “Please stop”
SIGTERM
system/orchestrator “Finish work cleanly”

Important: a signal is not a command to “die immediately”, but a polite request to shut down. Our job is to accept it and initiate a predictable shutdown.

2. Signals → context: NotifyContext and waiting on Done

signal.NotifyContext: a “signal context” without callbacks

Once in Go you have already started to love context.Context, going back to the low-level “subscribe to signals, read from the channel, remember to unsubscribe” approach is not appealing. And the good news is: you do not have to go back.

The os/signal package gives us the function signal.NotifyContext(parent, ...), which turns OS signals into a context. In other words, we get a ctx that will be canceled when the process receives one of the selected signals. It feels very “Go-like”: from that point on, we work everywhere through ctx, as if it were just an ordinary cancellation by timeout or by pressing a “Cancel” button.

Mini example: create a context that will be canceled on Ctrl+C and on SIGTERM:

import (
	"context"
	"os"
	"os/signal"
	"syscall"
)

func makeSignalContext() (context.Context, func()) {
	sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	return sigCtx, stop
}

It is important to notice the second return value: stop. This is the function that unsubscribes us from signals and releases subscription resources. It is almost always placed nearby with defer so you do not forget:

sigCtx, stop := makeSignalContext()
defer stop()

If you forget stop(), the program may not explode right away. But that is exactly the kind of mistake that lives in code for years because “well, it worked”. So it is better to get used to it: created a resource — immediately add defer for cleanup.

ctx.Done(): how to wait for cancellation correctly without polling

This is where we pin down the key building block of this lecture: how to wait for shutdown correctly.

The context.Context interface has the Done() method, which returns a channel. This channel is used as a “cancellation signal”: when the context is canceled, the channel “fires” (technically, it is closed), and everyone waiting on it wakes up.

Why is the channel read-only? Because whoever is waiting for cancellation usually must not be able to cancel the “parent”. This is reflected in the interface itself: Context has no Cancel method, and Done() returns a receive-only channel.

In practice, it comes down to one line that looks like magic until you get used to it:

<-sigCtx.Done() // blocks until the context is canceled

This is not polling, not “check every 100 ms”, not “spin in a loop”. It is honest event waiting. With this approach, the Go runtime does not make your CPU sad at 100% just because you are waiting for Ctrl+C.

To really “see” this waiting, we can make a tiny demo (just for understanding, not for production):

import (
	"context"
	"fmt"
)

func waitForCancel(ctx context.Context) {
	fmt.Println("waiting...") // waiting...
	<-ctx.Done()
	fmt.Println("canceled!")  // canceled!
}

The idea here is this: while ctx is not canceled, the program sits on the line <-ctx.Done() and leaves everyone alone.

4. Skeleton: server, goroutine, and waiting for a signal

Why we cannot do without a goroutine

Now let us put everything together into one lifecycle. The main technical problem sounds very simple: ListenAndServe() blocks execution. If you write “start the server, then wait for a signal” in one line, you will never get to the signal waiting stage — because the server has already occupied your main thread forever (or at least until it is stopped).

That is why we use the classic approach: start the server in a way that allows us to wait for the signal in parallel. For this we need just one goroutine. For now, think of a goroutine as a “lightweight execution thread”: we launch a piece of work alongside so the main flow can handle coordination. We are not diving deep into concurrency right now — we only need this practical trick.

Let us draw a simple diagram of who does what:

flowchart TD
    A[main goroutine] --> B[create sigCtx via NotifyContext]
    B --> C[start the HTTP server]
    C --> D["wait for <-sigCtx.Done()"]
    D --> E[initiate server shutdown]

main skeleton: context, server, and launching in a goroutine

Imagine that we already have a mux with handlers for our educational task API (we built it in previous topics). In this lecture, we focus on the signal and waiting.

main skeleton (part 1): create the context and the server.

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	mux := http.NewServeMux()
	srv := &http.Server{Addr: ":8080", Handler: mux}

	_ = sigCtx
	_ = srv
}

main skeleton (part 2): start the server in a goroutine so that main is not blocked.

import (
	"errors"
	"log"
	"net/http"
)

go func() {
	err := srv.ListenAndServe()
	if err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Printf("server error: %v", err)
	}
}()

Notice http.ErrServerClosed. When a server is stopped normally, ListenAndServe() often returns exactly this error. It should not be logged as an “incident”, otherwise your logs will look like a hypochondriac’s diary: “everything is bad!” — when in fact everything is fine. That is why we filter it through errors.Is.

And finally — waiting for the signal without polling, exactly with the line we pinned down:

import "log"

log.Printf("server started on %s", srv.Addr)
<-sigCtx.Done()
log.Printf("signal received, shutting down...")

At this point, your main “wakes up” when the signal arrives. And this is exactly where you will initiate graceful shutdown.

Important: in this lecture, we are not going deep into the shutdown call itself (there are nuances there, and the main one is that a timeout is mandatory). Our goal here is to “make it” to the shutdown moment correctly: catch the signal and not waste CPU on waiting loops.

To tie everything together into a more coherent fragment (without making one huge listing), we can mentally glue the pieces like this:

sequenceDiagram
    participant M as main goroutine
    participant S as server goroutine
    participant OS as OS signals

    M->>M: sigCtx := NotifyContext(...)
    M->>S: go ListenAndServe()
    M->>M: <-sigCtx.Done()
    OS-->>M: SIGINT/SIGTERM
    M->>M: start shutdown

Mini route /health to see the behavior “live”

So that this does not remain an abstraction, let us add one simple “health” endpoint to ServeMux that responds immediately. This is convenient: you can hit it in the browser or with curl and see that the server is alive, then press Ctrl+C and watch it go through the shutdown path gracefully.

Example handler (kept as short as possible):

import (
	"net/http"
)

func handleHealth(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("ok\n")) // ok
}

Route registration in main:

mux := http.NewServeMux()
mux.HandleFunc("GET /health", handleHealth)

Now your lifecycle looks like this: the server runs, /health responds with ok\n, you press Ctrl+C, sigCtx is canceled, <-sigCtx.Done() unblocks, and then shutdown begins.

Yes, for now we have not shown “how exactly to shut it down” — we are intentionally keeping the focus on the signal and the waiting. What matters is that the entry point to shutdown is already there, and it is not tied to “checking a flag in a loop”, but to the context.

5. Typical mistakes

Mistake #1: waiting for a signal with a polling loop and time.Sleep.
When people first hear “you need to wait for an event”, their hand automatically writes for { ... time.Sleep(100*time.Millisecond) }. It works, but it is bad style: extra latency, extra load, more code, more places for mistakes. In Go, waiting for context cancellation is done directly: <-ctx.Done(). The channel is already a ready-made “button”; there is no need to invent your own.

Mistake #2: forgetting to call stop() after signal.NotifyContext.
NotifyContext subscribes the process to signals. If you do not call stop(), you leave the subscription hanging longer than necessary. In small demos it is often “not visible”, but the habit is dangerous. Train yourself: got stop — immediately write defer stop() next to it.

Mistake #3: logging http.ErrServerClosed as a real error.
During a normal shutdown, ListenAndServe() often ends with http.ErrServerClosed. If you print this as “ERROR”, your logs will look like the server is constantly crashing. Filter this error with errors.Is, and log only unexpected errors.

Mistake #4: trying to stop the server “after ListenAndServe”, without running anything in parallel.
If ListenAndServe() sits in main without a goroutine, the code below it will never execute while the server is alive. Therefore, signal waiting and shutdown initiation need to be arranged so that main can handle them: either the server in a goroutine, or the shutdown in a goroutine. Otherwise, you get an ideally “eternal” server that cannot be shut down cleanly — almost like some legacy projects.

Mistake #5: not understanding why Done() is read-only.
Sometimes you want to say, “can I close this channel myself?” No, you cannot, and that is the right thing: Done() is a signal from the context owner to dependent operations. The recipient of the signal must not be able to cancel someone else’s work. That is the meaning of context as a cancellation tree.

1
Tarefa
Go SELF, nível 63, lição 0
Bloqueado
Botão de emergência
Botão de emergência
1
Tarefa
Go SELF, nível 63, lição 0
Bloqueado
Tempo de atividade
Tempo de atividade
1
Tarefa
Go SELF, nível 63, lição 0
Bloqueado
Pulso do servidor
Pulso do servidor
1
Tarefa
Go SELF, nível 63, lição 0
Bloqueado
Sinal em segundo plano
Sinal em segundo plano
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION