Go Context Cancellation: Stop Work the Moment 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
5 min read
By Ada Brackett — Solnyxus editorial voice. Drafted with AI assistance; reviewed by the team.
Somewhere right now, a Go server is building a report for someone who closed the tab ten seconds ago. It'll finish the job, it'll write the bytes, and nobody will read them. Go context cancellation is the fix, and it's how a Go program says "stop, nobody wants this anymore." Today we'll build a small HTTP server that notices when the client walks away or a deadline passes, quits its work, and tells you 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 actually 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.
Here's the part people miss. Nothing stops by magic. Your code has to look at ctx.Done() and return.
For an HTTP server you don't even have to make one. r.Context() is cancelled when the client's connection closes or when your handler returns. Free. I love free.
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))
}
The heart of it is that select in slowReport. It waits on two channels at once, the context's done channel and a 400 ms timer, and whichever is ready first wins.
Run it with go run ., open a second terminal, and poke it three ways:
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 one finishes in about 1.2 seconds. Boring, good.
The second needs 4 seconds of work against a 3-second budget, so the timeout fires and you get a 504 reading "stopped at step 8: report took longer than 3s". Watch the server log while it happens: steps one through seven tick by, then it just stops.
The third is my favourite. Hit Ctrl-C, glance at the server, and a moment later there's "stopped at step N: context canceled". The server noticed you left. That little line still makes me happy every time.
Go context cancellation, and why context.Cause matters
ctx.Err() only ever tells you "canceled" or "deadline exceeded." Two words. context.Cause(ctx) hands back the reason you attached with WithTimeoutCause (or WithCancelCause), and falls back to ctx.Err() when nobody attached one.
That's why the timeout says "report took longer than 3s" while the hang-up says "context canceled." Honestly, I'd attach a cause to every timeout you create. In a log at 2 a.m. the difference between "deadline exceeded" and a sentence that names the thing that was slow is the difference between going back to bed and opening six more files.
Always defer cancel()
Every WithCancel, WithTimeout and WithDeadline gives you back a cancel function. Call it, usually with defer, even when the work finishes on time. It releases the timer and the link to the parent context. (If you forget, go vet will nag you about the dropped cancel function, which is one of the few nags I'm grateful for.)
Pass it all the way down
A 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 go further and ask PostgreSQL to cancel it.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/rates", nil)
Build your outbound requests this way and they're abandoned the moment ctx ends, so one sluggish upstream can't hold your handler hostage.
The mistakes I see most
- Storing a context in a struct field. Pass it as the first argument instead, named
ctx. - Reaching for
context.Background()inside a handler. That quietly throws away the client's cancellation. - Checking
ctx.Done()once at the top and never again. Check between steps, or hand ctx to calls that check for you. - Starting a goroutine that never watches ctx. It'll keep running long after the request is gone.
Try this next
Bump the timeout to 5 seconds and run steps=8 again; it should finish this time. Then make it harder: split the work across a second goroutine running in parallel and get both of them to stop when ctx ends. Once that clicks, open the context package docs on go.dev, read up on context.AfterFunc and context.WithoutCancel, and go find the handler in your own code that's still building reports for empty rooms.
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.