Subscribe

Golang Tutorial 15: Context for timeouts and cancellation

How context.Context carries deadlines and cancellation from an HTTP request down to a Postgres query in Go. WithTimeout, WithCancelCause, WithoutCancel, AfterFunc, and what should never go into context values. Tested on Go 1.27 and Postgres 18.

Golang Tutorial 15: Context for timeouts and cancellation

A user opens a report page, it is slow, they close the tab. Your Go handler doesn't know that unless you tell it, so it keeps the database busy with a query nobody will read. context.Context is how Go passes "stop now" and "you have until 2 seconds from now" down through every function call. In this blog we will look at the context functions you actually use, then wire one from an HTTP request all the way down to a Postgres query and watch Postgres cancel it.

Level is intermediate. You should know goroutines, channels and select from Tutorial 14, and errors.Is from Tutorial 12. I used Go 1.27.3, pgx v5.13.0 and Postgres 18.7 in a throwaway Docker container.

The rules first

A context is passed as the first argument, named ctx. You never store it in a struct. It's a tree: you derive a child from a parent with WithTimeout, WithCancel and friends, and when a parent is cancelled every child below it is cancelled too. A child can never live longer than its parent.

Every With... function gives you back a cancel function. Call it, usually with defer, even when the timeout will fire on its own. It frees the timer and detaches the child from the parent straight away. go vet warns you when you drop it.

The context itself doesn't stop anything. It only closes a channel, ctx.Done(). Your code, or the library you call, has to watch that channel and give up. Most context bugs come from forgetting that one point only.

The basic functions

Make a module and a small file to try them.

mkdir tut15 && cd tut15
go mod init example.com/tut15
mkdir -p cmd/basics cmd/server

slowLookup stands in for any call that can take a while. It waits for either the work or ctx.Done(), whichever comes first.

package main

import (
    "context"
    "errors"
    "fmt"
    "time"
)

var ErrUserLeft = errors.New("user closed the page")

// slowLookup stands in for any call that can take a while.
func slowLookup(ctx context.Context, d time.Duration) (string, error) {
    select {
    case <-time.After(d):
        return "result", nil
    case <-ctx.Done():
        return "", ctx.Err()
    }
}

func main() {
    // 1. WithTimeout
    ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
    defer cancel()
    _, err := slowLookup(ctx, time.Second)
    fmt.Println("timeout:", err, "| is DeadlineExceeded:", errors.Is(err, context.DeadlineExceeded))

    // 2. WithCancelCause: say WHY it was cancelled.
    ctx2, cancel2 := context.WithCancelCause(context.Background())
    go func() {
        time.Sleep(100 * time.Millisecond)
        cancel2(ErrUserLeft)
    }()
    _, err = slowLookup(ctx2, time.Second)
    fmt.Println("cancel cause: err =", err, "| cause =", context.Cause(ctx2))

    // 3. WithTimeoutCause: a timeout with a better message.
    ctx3, cancel3 := context.WithTimeoutCause(context.Background(), 100*time.Millisecond,
        errors.New("price API took longer than 100ms"))
    defer cancel3()
    _, err = slowLookup(ctx3, time.Second)
    fmt.Println("timeout cause: err =", err, "| cause =", context.Cause(ctx3))

    // 4. A child can only be shorter than its parent.
    parent, cancelP := context.WithTimeout(context.Background(), 150*time.Millisecond)
    defer cancelP()
    child, cancelC := context.WithTimeout(parent, 5*time.Second)
    defer cancelC()
    dl, _ := child.Deadline()
    fmt.Println("child deadline in about:", time.Until(dl).Round(50*time.Millisecond))

    // 5. AfterFunc runs cleanup when the context ends.
    ctx5, cancel5 := context.WithCancel(context.Background())
    stopped := make(chan struct{})
    context.AfterFunc(ctx5, func() {
        fmt.Println("afterfunc: closing the connection")
        close(stopped)
    })
    cancel5()
    <-stopped
}
go run ./cmd/basics
timeout: context deadline exceeded | is DeadlineExceeded: true
cancel cause: err = context canceled | cause = user closed the page
timeout cause: err = context deadline exceeded | cause = price API took longer than 100ms
child deadline in about: 150ms
afterfunc: closing the connection

Few things to notice. ctx.Err() only ever says context canceled or context deadline exceeded. That's not much to go on in a log at 2am. The Cause variants let whoever cancels attach a real error, and context.Cause(ctx) reads it back, while ctx.Err() stays the same so old errors.Is checks still work. I'd use WithTimeoutCause on every call to an outside API, the log line names the API straight away.

Example 4 is the parent rule. I asked for 5 seconds, I got 150ms, because the parent ends first. No error, it just quietly uses the earlier deadline.

AfterFunc (Go 1.21) runs a function in its own goroutine once the context is done. It's handy for closing something that doesn't understand contexts, like a raw network connection.

From an HTTP request to a Postgres query

Now the real case. Every *http.Request carries a context, r.Context(). The server cancels it when the client disconnects or the handler returns. Pass it down and pgx does the rest: when the context ends, pgx asks Postgres to cancel the running query.

Start a Postgres to play with. I let Docker pick a free host port, because the first port I tried was already taken on my machine.

docker run -d --rm --name tut15-pg -e POSTGRES_PASSWORD=secret \
  -p 127.0.0.1::5432 postgres:18-alpine
docker port tut15-pg 5432
# 127.0.0.1:32768
go get github.com/jackc/pgx/v5@latest

The handler runs pg_sleep so we can control how slow the "report" is. It gives the query 2 seconds at most, and less if the client goes away first.

package main

import (
    "context"
    "errors"
    "fmt"
    "log"
    "net/http"
    "os"
    "strconv"
    "time"

    "github.com/jackc/pgx/v5/pgxpool"
)

type ctxKey int

const requestIDKey ctxKey = 0

func withRequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-ID")
        if id == "" {
            id = strconv.FormatInt(time.Now().UnixNano(), 36)
        }
        ctx := context.WithValue(r.Context(), requestIDKey, id)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func requestID(ctx context.Context) string {
    id, _ := ctx.Value(requestIDKey).(string)
    return id
}

type server struct {
    db *pgxpool.Pool
}

// GET /report?sleep=3 runs a query that takes "sleep" seconds.
func (s *server) report(w http.ResponseWriter, r *http.Request) {
    secs, _ := strconv.ParseFloat(r.URL.Query().Get("sleep"), 64)

    // The query gets at most 2 seconds, and less if the client goes away.
    ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
    defer cancel()

    start := time.Now()
    var n int
    err := s.db.QueryRow(ctx, "SELECT 42 FROM pg_sleep($1)", secs).Scan(&n)
    took := time.Since(start).Round(10 * time.Millisecond)

    // Audit log must be written even if the request was cancelled.
    go audit(context.WithoutCancel(ctx), requestID(ctx), err)

    switch {
    case errors.Is(err, context.DeadlineExceeded):
        log.Printf("[%s] query timed out after %v", requestID(ctx), took)
        http.Error(w, "report took too long", http.StatusGatewayTimeout)
        return
    case errors.Is(err, context.Canceled):
        log.Printf("[%s] client went away after %v", requestID(ctx), took)
        return
    case err != nil:
        log.Printf("[%s] query failed: %v", requestID(ctx), err)
        http.Error(w, "internal error", http.StatusInternalServerError)
        return
    }
    log.Printf("[%s] query ok in %v", requestID(ctx), took)
    fmt.Fprintf(w, "report ready: %d\n", n)
}

func audit(ctx context.Context, id string, err error) {
    // ctx is never cancelled here, but still carries the request ID.
    time.Sleep(50 * time.Millisecond)
    log.Printf("[%s] audit written (ctx.Err=%v, query err=%v)", requestID(ctx), ctx.Err(), err)
}

func main() {
    pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
    if err != nil {
        log.Fatal(err)
    }
    defer pool.Close()

    s := &server{db: pool}
    mux := http.NewServeMux()
    mux.HandleFunc("GET /report", s.report)

    addr := os.Getenv("ADDR")
    if addr == "" {
        addr = ":8080"
    }
    log.Println("listening on", addr)
    log.Fatal(http.ListenAndServe(addr, withRequestID(mux)))
}

Run it and hit it three way: a fast report, one slower than our 2 second limit, and an impatient client that hangs up after 1 second (curl -m 1).

DATABASE_URL='postgres://postgres:secret@127.0.0.1:32768/postgres?sslmode=disable' \
  ADDR=127.0.0.1:18915 go run ./cmd/server &

curl -s -H 'X-Request-ID: fast' '127.0.0.1:18915/report?sleep=0.5'
curl -s -w '%{http_code}\n' -H 'X-Request-ID: slow' '127.0.0.1:18915/report?sleep=5'
curl -s -m 1 -H 'X-Request-ID: impatient' '127.0.0.1:18915/report?sleep=5'
report ready: 42
report took too long
504

And the server log.

[fast] query ok in 510ms
[fast] audit written (ctx.Err=<nil>, query err=<nil>)
[slow] query timed out after 2s
[slow] audit written (ctx.Err=<nil>, query err=timeout: context deadline exceeded)
[impatient] client went away after 1s
[impatient] audit written (ctx.Err=<nil>, query err=context canceled)

The part I wanted to see was on the database side, so I checked the Postgres logs.

docker logs tut15-pg 2>&1 | grep -i cancel
2026-11-19 06:38:26.435 UTC [80] ERROR:  canceling statement due to user request
2026-11-19 06:38:27.445 UTC [82] ERROR:  canceling statement due to user request

Two cancelled statement, one for the timeout and one for the client that left. Without the context those two pg_sleep(5) calls would have held a connection for the full five seconds each. With a pool of ten connections and a few impatient users, that is basically how a slow report page takes down the whole API.

Notice the error text: pgx wrapped the timeout as timeout: context deadline exceeded. A plain err == context.DeadlineExceeded would not match this. errors.Is looks through the wrapping, so always use it here. Clean up with docker rm -f tut15-pg when you're done.

If you want the database side done properly with pooling and generated queries, the pgx and sqlc post builds on this.

WithoutCancel for work that must finish

The audit write has a problem. It runs after the response, and by then the request context is cancelled. Pass that context to a database insert and the insert fails with context canceled. context.WithoutCancel (Go 1.21) gives you a child that keeps the values (our request ID still prints) but is never cancelled and has no deadline. You can see ctx.Err=<nil> on all three audit lines above.

Be a bit careful with it though, a context that never ends mean the goroutine can hang forever. In real code I'd give it a fresh timeout, context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second). For work that must survive a deploy, a goroutine is the wrong place anyway: put it in a queue. The graceful shutdown post covers what happens to in-flight goroutines when the container stops.

What goes in context values

Very little. Context values are for request-scoped data that crosses API boundaries: a request ID, a trace ID, maybe the authenticated user. Use an unexported key type like ctxKey above, so no other package can clash with your key, and a small getter function.

Don't put in it:

  • database connections, loggers with config, or anything you could pass as a normal argument
  • optional function parameters. If CreateLink needs a userID, make it an argument
  • big objects or anything you mutate

The test I use: if the function would be wrong without the value, it should be a parameter. Context values are invisible in the signature, and invisible dependencies are how you end up with a nil check failing three layers down.

Timeouts in layers

One last practical point. The http.Server has its own ReadTimeout and WriteTimeout, the handler has the 2 seconds we set, and each outbound call can have a shorter one under that. Inner timeouts should be shorter than outer ones, otherwise the outer one always wins and your nice error message never shows. The designing for failure post goes into how to pick the numbers.

Exercise

Ask two "mirrors" for the same price, keep whichever answers first and cancel the other. Use WithCancelCause so the loser's error says why it stopped instead of plain context canceled. Make mirror A take 300ms and mirror B 120ms.

My solution printed this, and it's clean under go run -race.

winner: price from mirror-b
mirror-a stopped: another mirror answered first

Hint: the fetch function should return context.Cause(ctx) instead of ctx.Err(), and the results channel needs a buffer of two so the slow goroutine is never stuck sending.