Cancel Slow Work With context.WithTimeout and r.Context()
Propagate cancellation signals and deadlines with context.WithTimeout, pair every context with defer cancel(), and respect r.Context() in HTTP handlers. After this, abandoned requests stop immediately.
Skip ahead
Already creating child contexts with context.WithTimeout and defer cancel()? Jump to Case 3: checking ctx.Done() in pure-Go loops or Case 4: parent cancellation cascades.
When an HTTP user closes their browser tab—or an upstream database query hangs for 30 seconds—your Go service should abort the wasted work immediately instead of holding database locks and goroutines until the slow call eventually finishes. Go threads deadlines and cancellation through every package using one standard value: context.Context.
Case 1: Bounding a slow operation with context.WithTimeout
Always call defer cancel() on the very next line after context.WithTimeout. If your work finishes in 10 ms instead of waiting for the 2-second timeout, cancel() immediately frees the internal timer and detaches the child context from its parent:
package main
import (
"context"
"errors"
"fmt"
"time"
)
func slowWork(ctx context.Context, d time.Duration) error {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
err := slowWork(ctx, 200*time.Millisecond)
fmt.Printf("err=%v is_deadline=%v\n", err, errors.Is(err, context.DeadlineExceeded))
}
err=context deadline exceeded is_deadline=true
Case 2: Always derive from r.Context() in HTTP handlers
Inside an HTTP handler, never write context.WithTimeout(context.Background(), 2*time.Second)—that detaches your timeout from the incoming HTTP request! Derive from r.Context() instead so both your 2-second timeout and a client disconnect cancel the downstream database query:
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, "SELECT id, email FROM users WHERE active = $1", true)
if errors.Is(err, context.DeadlineExceeded) {
http.Error(w, "database timeout", http.StatusGatewayTimeout)
return
}
Case 3: Go does not preempt pure-Go loops automatically
Passing ctx to db.QueryContext or http.NewRequestWithContext lets those libraries abort I/O immediately, but a CPU-bound loop processing 100,000 items ignores ctx unless you check ctx.Done() explicitly on each batch:
for _, item := range items {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
transform(item)
}
Case 4: Parent cancellation cascades downward—never upward
Contexts form a parent-child tree. When a parent context cancels, every child derived from it cancels right away even if the child still had seconds left on its deadline:
parent, cancelParent := context.WithCancel(context.Background())
child, cancelChild := context.WithTimeout(parent, 5*time.Second)
defer cancelChild()
cancelParent() // client disconnected!
<-child.Done()
fmt.Printf("parent=%v child=%v\n", parent.Err(), child.Err())
parent=context canceled child=context canceled
Conversely, if child hits a short 200 ms timeout while querying an optional recommendations service, parent stays alive so your handler can return the main page with a fallback list.
💡 Tip
Need to tell why a context was canceled in logs? Use context.WithTimeoutCause(parent, 2*time.Second, ErrSlowUpstream) (Go 1.21+) and read the exact cause with context.Cause(ctx).
Common mistakes
- Forgetting
defer cancel(): Leaks timers and parent references until the deadline expires;go vet ./...catches this automatically. - Storing
ctxinside a struct field: Ties every method call to one stale request lifetime. Always passctx context.Contextas the first parameter of each function. - Using
context.Background()inside handlers: Ignores client disconnects and keeps burning DB/API capacity after the browser tab closes.
⚠ Warning
Do not pass required dependencies (like *sql.DB or user IDs) through context.WithValue. Keep WithValue strictly for optional cross-cutting telemetry like trace IDs or request IDs.
What happens if you skip this
Slow downstream queries pile up when impatient users hit refresh—holding database connections and goroutines long after callers have disappeared until the service saturates its connection pool.
Related course: Go Intermediate.
About
Propagate cancellation signals and deadlines with context.WithTimeout, pair every context with defer cancel(), and respect r.Context() in HTTP handlers. After this, abandoned requests stop immediately.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.