Go Context Cancellation From Zero: Stop Work When the Client Hangs Up
Go context cancellation from zero: build a 50-line server that stops a slow job when the client hangs up or a deadline passes, read the reason with context.Cause, and pass ctx down to your database and outbound calls.
Ada Brackett
4 min read
By Ada Brackett — Solnyxus editorial voice.
Go context cancellation is how a Go program says "stop, nobody wants this anymore." Without it, a server keeps building a report for a user who closed the tab ten seconds ago. In this post we build a small HTTP server that notices when the client leaves or a deadline passes, stops its work, and logs why.
Written for Go 1.27 (checked 4 November 2026). Everything here works on Go 1.22 or later, because the route pattern GET /report needs 1.22 and context.WithTimeoutCause needs 1.21.
What a context is
A context.Context is a value you pass as the first argument to anything that might take a while. It carries three things: a done channel that closes when the work should stop, a deadline if there is one, and a reason for stopping. Nothing stops by magic. Your code has to look at ctx.Done() and return.
For an HTTP server, Go hands you one for free. r.Context() is cancelled when the client's connection closes or when your handler returns.
The lab: a report that knows when to quit
Make a folder, run go mod init ctxlab, and save this as main.go:
// main.go — written for Go 1.27; needs Go 1.22+
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"time"
)
// slowReport builds a report one step at a time and checks ctx between steps.
func slowReport(ctx context.Context, steps int) (string, error) {
for i := 1; i <= steps; i++ {
select {
case <-ctx.Done():
return "", fmt.Errorf("stopped at step %d: %w", i, context.Cause(ctx))
case <-time.After(400 * time.Millisecond):
log.Printf("step %d/%d done", i, steps)
}
}
return fmt.Sprintf("report ready after %d steps\n", steps), nil
}
func reportHandler(w http.ResponseWriter, r *http.Request) {
steps := 10
if s := r.URL.Query().Get("steps"); s != "" {
n, err := strconv.Atoi(s)
if err != nil || n < 1 {
http.Error(w, "steps must be a positive number", http.StatusBadRequest)
return
}
steps = n
}
ctx, cancel := context.WithTimeoutCause(r.Context(), 3*time.Second,
errors.New("report took longer than 3s"))
defer cancel()
out, err := slowReport(ctx, steps)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusGatewayTimeout)
return
}
fmt.Fprint(w, out)
}
func main() {
http.HandleFunc("GET /report", reportHandler)
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
slowReport waits on two channels at once with select: the context's done channel and a 400 ms timer. Whichever is ready first wins.
Run it with go run . and try three things from a second terminal.
curl "localhost:8080/report?steps=3"
curl -i "localhost:8080/report"
curl "localhost:8080/report?steps=8" # press Ctrl-C after a second
The first finishes in about 1.2 seconds. The second needs 4 seconds, so the 3-second timeout fires and you get a 504 with "stopped at step 8: report took longer than 3s". For the third, the server log shows "stopped at step N: context canceled" a moment after you press Ctrl-C.
Why context.Cause matters
ctx.Err() only tells you "canceled" or "deadline exceeded." context.Cause(ctx) returns the reason you attached with WithTimeoutCause (or WithCancelCause), and falls back to ctx.Err() when nobody attached one. That is why the timeout says "report took longer than 3s" while the hang-up says "context canceled." In a log at 2 a.m., that difference saves time.
Always defer cancel()
Every WithCancel, WithTimeout and WithDeadline returns a cancel function. Call it, usually with defer, even when the work finishes normally. It releases the timer and the link to the parent context. go vet warns you when a cancel function is dropped.
Pass it down
The context only helps if it reaches the slow part. The standard library and most drivers take one:
rows, err := db.QueryContext(ctx, "SELECT id, total FROM orders WHERE day = $1", day)
database/sql gives up on the query when ctx is done, and drivers such as pgx ask PostgreSQL to cancel it.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/rates", nil)
An outbound request made this way is abandoned as soon as ctx ends, so one slow upstream does not hold your handler forever.
Common mistakes
- Storing a context in a struct field. Pass it as the first argument instead, named
ctx. - Using
context.Background()inside a handler. That throws away the client's cancellation. - Checking
ctx.Done()only once at the start. Check it between steps, or pass it to calls that check it for you. - Starting a goroutine that never watches ctx. It keeps running after the request is gone.
Try this next
Change the timeout to 5 seconds and run steps=8 again; it should finish. Then add a second goroutine that does part of the work in parallel and make both stop when ctx ends. If you want to go further, read the context package docs on go.dev for context.AfterFunc and context.WithoutCancel, and think about where each would fit in your own handlers.
Cloud
More like this
Cloud
Build a Tiny JSON API With Axum: Rust on the Web in Fifteen Minutes
Your Rust programs have been talking to the terminal. Time they talked to the internet. Build a notes API with Axum, with routes, JSON in and out, shared state and proper 404s, in about 50 lines.
Cloud
Ollama Review: Running Local LLMs on Your Own Machine, No Cloud Required
What if your AI assistant lived in your basement instead of someone else's data centre? A review of Ollama: how to run local LLMs with it, what hardware you really need, the API that makes it useful, and where it falls short.
Cloud
Async Rust With Tokio: Build an Echo Server That Juggles a Thousand Clients
One waiter, forty tables, and nobody waits for their soup. That's async. Learn async Rust with Tokio by building a 30-line TCP echo server, then meet the one mistake that freezes the whole restaurant.