Programming languages · Advanced · 22 min
Cancel slow work in Go with context and timeouts
By Padding · Updated 18 Nov 2026
Go 1.27.4 · golang.org/x/sync 0.25.0 · Linux or macOS
You will build a Go 1.27 stock API whose handler calls a slow price service and a slow query at once, gives up after a time budget or when the client hangs up, and has a test proving it leaves no goroutines running.
On this page
A request handler that calls other systems is only as fast as the slowest of them. When a downstream service hangs, a handler with no limits waits with it, holding a goroutine, a connection and some memory for every request that piles up behind. When the person who sent the request gives up, the handler carries on working for nobody.
Go's answer is the context package. A context.Context is a value you pass down the call chain that carries a deadline and a "stop now" signal. Code that might wait checks it, and the standard library's network calls already do. One cancel at the top stops everything underneath.
In this tutorial you build a small stock API with one route, GET /stock/{sku}. To answer, it asks a price service for the item's price and counts the item's rows in a database at the same time. Both are stand-ins you write yourself, with knobs to make them slow or failing, so you can watch each kind of cancellation happen. You finish with a test that fails if the handler ever leaves work running after it returns.
This matters most where connections are unreliable. People on mobile data, on low-end Android phones or on prepaid bundles they are watching closely, often give up on a slow screen and retry. Without cancellation, every abandoned attempt keeps your server busy until it finishes.
Step 1 · Create the module
Make a throwaway folder and a module for the project:
mkdir -p ~/stock-api-demo
cd ~/stock-api-demo
go mod init example.com/stock-api
cat go.modEverything in this tutorial is in package main, split across a few files so that each step adds one piece.
Check it worked
go mod init prints go: creating new go.mod: module example.com/stock-api, and cat go.mod shows that module line and a go 1.26.0 line. That is deliberate: since Go 1.26, go mod init writes the previous minor version so that slightly older toolchains can still build the module.
Step 2 · Write a slow query that listens for cancellation
Create store.go. It stands in for a database query that reads 50 rows, each taking rowCost:
cat > store.go <<'GO'
package main
import (
"context"
"time"
)
// countStock stands in for a slow database query. It reads 50 rows, each
// taking rowCost, and stops as soon as ctx is cancelled or times out.
func countStock(ctx context.Context, sku string, rowCost time.Duration) (int, error) {
inStock := 0
for row := 0; row < 50; row++ {
select {
case <-ctx.Done():
return 0, context.Cause(ctx)
case <-time.After(rowCost):
}
inStock++
}
return inStock, nil
}
GOThree conventions are at work here, and the rest of the tutorial follows them:
- The context is the first parameter and is called
ctx. Functions take it as an argument; they do not store it in a struct for later. - Inside the loop,
selectwaits for whichever comes first: the next row, orctx.Done(), a channel that is closed when the context is cancelled or its deadline passes. A loop that never looks atctx.Done()cannot be stopped. - On cancellation it returns
context.Cause(ctx), the reason the context was stopped. For a plain cancel that iscontext.Canceled, for a timeoutcontext.DeadlineExceeded, and with the...Causevariants it is an error you choose.
A real database driver does this checking for you. With database/sql, you pass ctx to QueryContext or ExecContext, and the driver abandons the query when the context ends. Now write tests for the three outcomes in store_test.go:
cat > store_test.go <<'GO'
package main
import (
"context"
"errors"
"testing"
"time"
)
func TestCountStockFinishes(t *testing.T) {
got, err := countStock(context.Background(), "tea", time.Millisecond)
if err != nil || got != 50 {
t.Fatalf("got %d, %v; want 50, nil", got, err)
}
}
func TestCountStockStopsWhenCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Millisecond, cancel)
start := time.Now()
_, err := countStock(ctx, "tea", 20*time.Millisecond)
took := time.Since(start)
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
if took > 200*time.Millisecond {
t.Fatalf("took %v, want well under the full second", took)
}
t.Logf("stopped after %v", took.Round(10*time.Millisecond))
}
var errShuttingDown = errors.New("server is shutting down")
func TestCountStockReportsTheCause(t *testing.T) {
ctx, cancel := context.WithCancelCause(context.Background())
cancel(errShuttingDown)
_, err := countStock(ctx, "tea", 20*time.Millisecond)
if !errors.Is(err, errShuttingDown) {
t.Fatalf("err = %v, want errShuttingDown", err)
}
if !errors.Is(ctx.Err(), context.Canceled) {
t.Fatalf("ctx.Err() = %v, want context.Canceled", ctx.Err())
}
}
GO
go test -v -run CountStock .context.WithCancel returns a new context and a cancel function; calling cancel stops that context and every context derived from it. context.WithCancelCause is the same, except its cancel function takes an error, so whoever reads the context later can find out why. ctx.Err() still reports the general context.Canceled, so older code that checks for it keeps working.
Check it worked
All three tests pass. The cancelled test logs something like stopped after 50ms: the loop noticed the cancel after two or three rows, not after all 50, which would take a full second.
Step 3 · Call the slow service with a request that carries the context
Create supplier.go. It holds two things: a stand-in for a price service run by another team, and fetchPrice, the client code your handler uses to call it. The stand-in waits for as long as ?delay= says and fails on ?fail=1; those parameters exist only so you can steer it from curl.
cat > supplier.go <<'GO'
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
type quote struct {
SKU string `json:"sku"`
PriceMinor int `json:"priceMinor"`
}
// newSupplierMux stands in for a price service run by another team.
// ?delay=3s makes it slow and ?fail=1 makes it fail, so you can test both.
func newSupplierMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /prices/{sku}", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("fail") == "1" {
http.Error(w, "supplier is down", http.StatusServiceUnavailable)
return
}
delay, err := time.ParseDuration(r.URL.Query().Get("delay"))
if err != nil {
delay = 100 * time.Millisecond
}
start := time.Now()
select {
case <-time.After(delay):
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(quote{SKU: r.PathValue("sku"), PriceMinor: 1250})
case <-r.Context().Done():
log.Printf("supplier: caller went away after %v", time.Since(start).Round(10*time.Millisecond))
}
})
return mux
}
// fetchPrice asks the supplier for a price. The request carries ctx, so it
// is abandoned, connection and all, when ctx is cancelled or times out.
func fetchPrice(ctx context.Context, client *http.Client, baseURL, sku, rawQuery string) (quote, error) {
u := baseURL + "/prices/" + url.PathEscape(sku) + "?" + rawQuery
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return quote{}, err
}
resp, err := client.Do(req)
if err != nil {
return quote{}, fmt.Errorf("supplier: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return quote{}, fmt.Errorf("supplier: status %d", resp.StatusCode)
}
var q quote
if err := json.NewDecoder(resp.Body).Decode(&q); err != nil {
return quote{}, fmt.Errorf("supplier: %w", err)
}
return q, nil
}
GOhttp.NewRequestWithContext ties the outgoing request to ctx. If the context ends while the request is in flight, client.Do returns at once with an error that wraps the context's error, and the transport closes the connection. A request made with plain http.Get or http.NewRequest has no such link and waits until the server answers or the client's own timeout fires.
The stand-in shows the server side of the same mechanism: an incoming request's r.Context() is cancelled when the caller's connection closes. Test the client with a deadline shorter than the delay:
cat > supplier_test.go <<'GO'
package main
import (
"context"
"errors"
"net/http/httptest"
"testing"
"time"
)
func TestFetchPrice(t *testing.T) {
srv := httptest.NewServer(newSupplierMux())
defer srv.Close()
q, err := fetchPrice(context.Background(), srv.Client(), srv.URL, "tea", "delay=10ms")
if err != nil || q.PriceMinor != 1250 {
t.Fatalf("got %+v, %v", q, err)
}
}
func TestFetchPriceGivesUpAtTheDeadline(t *testing.T) {
srv := httptest.NewServer(newSupplierMux())
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
start := time.Now()
_, err := fetchPrice(ctx, srv.Client(), srv.URL, "tea", "delay=2s")
took := time.Since(start)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want context.DeadlineExceeded", err)
}
if took > 500*time.Millisecond {
t.Fatalf("took %v, want about 200ms", took)
}
t.Logf("gave up after %v: %v", took.Round(10*time.Millisecond), err)
}
GO
go test -v -run FetchPrice .context.WithTimeout returns a context whose deadline is the given time from now. Always defer cancel() straight after: it releases the context's timer as soon as the function returns, even when the work finishes early. go vet warns when a cancel function is not called on every path.
Check it worked
Both tests pass. The deadline test logs something like gave up after 200ms: supplier: Get "http://127.0.0.1:.../prices/tea?delay=2s": context deadline exceeded, and the stand-in logs supplier: caller went away after 200ms. The supplier stopped waiting too, because the closed connection cancelled its request context.
Step 4 · Tag each request with an ID, and keep everything else out of the context
A context can also carry values, through context.WithValue. It is tempting to use this as a bag for anything a function might need. Do not. Values in a context are untyped, invisible in function signatures and easy to forget in tests. Keep them to data that belongs to one request and must cross API boundaries: a request ID or trace ID, or the identity of an already-authenticated caller.
Things that do not belong in a context value:
- Optional parameters or settings, such as a page size or a "dry run" flag. Make them real arguments.
- Shared dependencies: database pools, HTTP clients, loggers, configuration. Put them in a struct, as the
apptype in the next step does. - Anything a function needs in order to work. If a function fails without a value, it should be a parameter.
Create requestid.go with middleware that gives each request an ID and a helper that puts it in front of log lines:
cat > requestid.go <<'GO'
package main
import (
"context"
"fmt"
"log"
"net/http"
"sync/atomic"
)
// requestIDKey is unexported, so no other package can read or overwrite
// the value by accident.
type requestIDKey struct{}
func withRequestID(next http.Handler) http.Handler {
var counter atomic.Int64
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := fmt.Sprintf("req-%d", counter.Add(1))
w.Header().Set("X-Request-ID", id)
ctx := context.WithValue(r.Context(), requestIDKey{}, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func requestID(ctx context.Context) string {
if id, ok := ctx.Value(requestIDKey{}).(string); ok {
return id
}
return "-"
}
// logf prefixes every log line with the request ID from ctx.
func logf(ctx context.Context, format string, args ...any) {
log.Printf("[%s] %s", requestID(ctx), fmt.Sprintf(format, args...))
}
GO
cat > requestid_test.go <<'GO'
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestRequestID(t *testing.T) {
h := withRequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, requestID(r.Context()))
}))
for _, want := range []string{"req-1", "req-2"} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if rec.Body.String() != want || rec.Header().Get("X-Request-ID") != want {
t.Fatalf("body %q, header %q; want %q", rec.Body.String(), rec.Header().Get("X-Request-ID"), want)
}
}
}
GO
go test -v -run RequestID .The key is a value of an unexported, empty struct type. Two packages that both used the string "requestID" as a key would collide; a private type cannot. requestID returns - when there is no ID, so code that logs works the same in tests that skip the middleware.
Check it worked
TestRequestID passes: the first request gets req-1 in both the body and the X-Request-ID header, and the second gets req-2.
Step 5 · Run both lookups under one time budget
Now the handler. It runs the price call and the stock count at the same time with errgroup, from the Go team's golang.org/x/sync module. Add it at a fixed version:
go get golang.org/x/sync@v0.25.0Create handler.go:
cat > handler.go <<'GO'
package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"golang.org/x/sync/errgroup"
)
var errOverBudget = errors.New("stock lookup ran over its time budget")
type app struct {
supplierURL string
client *http.Client
budget time.Duration
rowCost time.Duration
}
type stockReply struct {
SKU string `json:"sku"`
InStock int `json:"inStock"`
PriceMinor int `json:"priceMinor"`
}
func (a *app) stock(w http.ResponseWriter, r *http.Request) {
sku := r.PathValue("sku")
ctx, cancel := context.WithTimeoutCause(r.Context(), a.budget, errOverBudget)
defer cancel()
g, gctx := errgroup.WithContext(ctx)
var q quote
var inStock int
g.Go(func() error {
var err error
q, err = fetchPrice(gctx, a.client, a.supplierURL, sku, r.URL.RawQuery)
return err
})
g.Go(func() error {
var err error
inStock, err = countStock(gctx, sku, a.rowCost)
return err
})
err := g.Wait()
switch {
case err == nil:
writeJSON(w, http.StatusOK, stockReply{SKU: sku, InStock: inStock, PriceMinor: q.PriceMinor})
case r.Context().Err() != nil:
logf(ctx, "client went away, stopped work: %v", context.Cause(r.Context()))
case errors.Is(context.Cause(ctx), errOverBudget):
logf(ctx, "gave up: %v", context.Cause(ctx))
writeJSON(w, http.StatusGatewayTimeout, map[string]string{"error": "the lookup took too long"})
default:
logf(ctx, "lookup failed: %v", err)
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "the price service failed"})
}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
GO
go mod tidy
go vet ./...Read the handler from the top:
- The work starts from
r.Context(), notcontext.Background(). That is what links it to the client: when the client disconnects, this context is cancelled, and so is everything derived from it. context.WithTimeoutCauseadds a deadline ofa.budgeton top, and names the reason. When the budget runs out,ctx.Err()is stillcontext.DeadlineExceeded, butcontext.Cause(ctx)iserrOverBudget, which tells you which of several possible deadlines fired.errgroup.WithContextderivesgctx. The first function passed tog.Gothat returns an error cancelsgctx, so the other lookup stops too, andg.Waitwaits for both goroutines to return before giving you that first error. There is no point counting stock for a price you cannot show.- The two closures each write their own variable. Reading them after
g.Waitis safe, becauseWaitreturns only once both goroutines have finished. - The
switchchecks the client first. If the client has gone, nobody will read a reply, so the handler logs and returns without writing one. Otherwise a blown budget becomes504 Gateway Timeoutand a supplier failure becomes502 Bad Gateway.
Check it worked
go mod tidy and go vet ./... finish without printing anything, and go.mod now has a require golang.org/x/sync v0.25.0 line.
Step 6 · Run the API and watch it give up
Create main.go. It starts the supplier stand-in on port 8091 and the stock API on port 8090, both on 127.0.0.1 only. The budget is 1.5 seconds and each of the 50 rows costs 10 milliseconds, so a normal lookup takes about half a second:
cat > main.go <<'GO'
package main
import (
"log"
"net/http"
"time"
)
func main() {
supplier := &http.Server{
Addr: "127.0.0.1:8091",
Handler: newSupplierMux(),
ReadHeaderTimeout: 5 * time.Second,
}
go func() { log.Fatal(supplier.ListenAndServe()) }()
a := &app{
supplierURL: "http://127.0.0.1:8091",
client: &http.Client{Timeout: 10 * time.Second},
budget: 1500 * time.Millisecond,
rowCost: 10 * time.Millisecond,
}
mux := http.NewServeMux()
mux.HandleFunc("GET /stock/{sku}", a.stock)
srv := &http.Server{
Addr: "127.0.0.1:8090",
Handler: withRequestID(mux),
ReadHeaderTimeout: 5 * time.Second,
}
log.Println("stock API on", srv.Addr, "with the supplier stand-in on", supplier.Addr)
log.Fatal(srv.ListenAndServe())
}
GO
go build -o stock-api .
./stock-api > api.log 2>&1 &http.Client{Timeout: 10 * time.Second} is a ceiling for any single call through that client, a safety net. The per-request budget comes from the context, which can only make a call shorter. The server writes its log to api.log, so you can read it once the requests are done.
Send four requests: a normal one, one where the supplier takes three seconds, one where the supplier fails, and one where curl itself gives up after one second:
curl -s -w '%{http_code} in %{time_total}s\n' http://127.0.0.1:8090/stock/tea
curl -s -w '%{http_code} in %{time_total}s\n' 'http://127.0.0.1:8090/stock/tea?delay=3s'
curl -s -w '%{http_code} in %{time_total}s\n' 'http://127.0.0.1:8090/stock/tea?fail=1'
curl -s --max-time 1 'http://127.0.0.1:8090/stock/tea?delay=3s' || echo "curl gave up with exit code $?"
sleep 1
cat api.logCheck it worked
The first request prints {"sku":"tea","inStock":50,"priceMinor":1250} and 200 in about 0.5 seconds. The second prints {"error":"the lookup took too long"} and 504 after about 1.5 seconds, not 3. The third prints {"error":"the price service failed"} and 502 almost at once: the failure cancelled the stock count, which would otherwise have run for half a second. The fourth prints curl gave up with exit code 28, curl's code for a timeout.
api.log holds lines like these, with dates and times in front and possibly in a different order:
stock API on 127.0.0.1:8090 with the supplier stand-in on 127.0.0.1:8091
supplier: caller went away after 1.5s
[req-2] gave up: stock lookup ran over its time budget
[req-3] lookup failed: supplier: status 503
[req-4] client went away, stopped work: context canceled
supplier: caller went away after 1sThe req-4 line is the client disconnect at work: curl closed the connection, Go cancelled r.Context(), and the cancel flowed down through the budget context and the errgroup into both lookups. Stop the server, in the same terminal:
kill %1
wait || trueStep 7 · Prove the handler leaves nothing running
A handler that returns while a goroutine it started is still waiting has leaked that goroutine. Under load, leaks pile up until the process runs out of memory. Create handler_test.go. It calls the handler directly in four situations, checks the status and how long each took, then checks that the number of goroutines is back where it started:
cat > handler_test.go <<'GO'
package main
import (
"context"
"net/http"
"net/http/httptest"
"runtime"
"testing"
"time"
)
func TestStockStopsEverythingItStarts(t *testing.T) {
supplier := httptest.NewServer(newSupplierMux())
defer supplier.Close()
transport := &http.Transport{}
a := &app{
supplierURL: supplier.URL,
client: &http.Client{Transport: transport},
rowCost: 5 * time.Millisecond, // 250ms for all 50 rows
}
cases := []struct {
name string
query string
budget time.Duration
clientQuit time.Duration // 0 means the client waits
wantStatus int // 0 means no reply is written
maxTime time.Duration
}{
{"ok", "delay=10ms", 2 * time.Second, 0, http.StatusOK, time.Second},
{"supplier slow", "delay=5s", 100 * time.Millisecond, 0, http.StatusGatewayTimeout, 200 * time.Millisecond},
{"supplier fails", "fail=1", 2 * time.Second, 0, http.StatusBadGateway, 150 * time.Millisecond},
{"client quits", "delay=5s", 2 * time.Second, 50 * time.Millisecond, 0, 150 * time.Millisecond},
}
before := runtime.NumGoroutine()
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
a.budget = tc.budget
req := httptest.NewRequest(http.MethodGet, "/stock/tea?"+tc.query, nil)
req.SetPathValue("sku", "tea")
if tc.clientQuit > 0 {
ctx, cancel := context.WithCancel(req.Context())
time.AfterFunc(tc.clientQuit, cancel)
req = req.WithContext(ctx)
}
rec := httptest.NewRecorder()
start := time.Now()
a.stock(rec, req)
took := time.Since(start)
if tc.wantStatus == 0 && rec.Body.Len() != 0 {
t.Errorf("wrote %q to a client that had gone", rec.Body.String())
}
if tc.wantStatus != 0 && rec.Code != tc.wantStatus {
t.Errorf("status = %d, want %d", rec.Code, tc.wantStatus)
}
if took > tc.maxTime {
t.Errorf("took %v, want at most %v", took, tc.maxTime)
}
})
}
// Close the pooled keep-alive connection, then wait for every goroutine
// the handler started, here and in the supplier, to finish.
transport.CloseIdleConnections()
deadline := time.Now().Add(2 * time.Second)
for runtime.NumGoroutine() > before {
if time.Now().After(deadline) {
buf := make([]byte, 1<<16)
n := runtime.Stack(buf, true)
t.Fatalf("%d goroutines still running, started with %d:\n%s",
runtime.NumGoroutine(), before, buf[:n])
}
time.Sleep(10 * time.Millisecond)
}
t.Logf("goroutines before: %d, after: %d", before, runtime.NumGoroutine())
}
GO
go test -race -v -run StockStops .The "client quits" case simulates a disconnect by cancelling the request's context after 50 milliseconds, which is what the server does when the connection closes. transport.CloseIdleConnections() closes the one connection kept open for reuse after the successful case, so its goroutines end too. The test polls for up to two seconds, because goroutines that have been told to stop still need a moment to return. If the count never comes back down, it fails and prints every goroutine's stack, which shows exactly where the stray one is waiting. -race turns on the race detector, which would flag the two closures if they shared a variable without the Wait in between.
Check it worked
All four subtests pass and the test logs something like goroutines before: 3, after: 3. To see it catch a mistake, delete the case <-ctx.Done(): branch and its return in store.go and run the test again: the slow, failing and quitting cases now each take the full 250 milliseconds of the stock count and fail their timing checks. Put the lines back afterwards and run go test -race ./... to confirm everything passes.
Step 8 · Clean up
Remove the project folder. Go stays installed, and golang.org/x/sync stays in your module cache, where other projects can reuse it:
cd ~
rm -rf ~/stock-api-demoCheck it worked
ls ~/stock-api-demo reports No such file or directory.
Next steps
- Go deeper on goroutines, channels and
select: run work concurrently in Go with goroutines and channels. - Put this pattern into a fuller service: build a JSON API with the Go standard library.
- Decide what each error means to the caller: handle errors the Go way with wrapping and errors.Is.
- Stop the whole server cleanly on Ctrl+C or
SIGTERMwithsignal.NotifyContext, the same context idea one level up: write your first web server in Go.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials