
Context Cancellation and Query Timeouts in Go SQL Code
Put a deadline on every Go database call: a 200 ms context cancels a 5 second query on the server too, and statement_timeout is the backstop.
Tag
13 articles

Put a deadline on every Go database call: a 200 ms context cancels a 5 second query on the server too, and statement_timeout is the backstop.

Test that Go code stops when its context is cancelled or times out: short deadlines, errors.Is, WithCancelCause and a guard timeout so a hang fails fast.

Find who cancelled a context in Go and fix the error: client disconnects, a deferred cancel that runs too early, errgroup siblings and detached work.

Use context cancellation properly in a Go web service: pass r.Context down, set deadlines in middleware, stop streaming loops, detach background work.

When r.Context() is cancelled in a Go handler, what it saves downstream, and why an HTTP/1 handler that never reads the body never sees a disconnect.

Add useful context to Go errors: what to say at each layer, what the standard library already says, how to avoid stutter, and when to use fields.

Use context.WithCancelCause and context.Cause from Go 1.20 to record why a context ended, with timeout causes from Go 1.21 and a fan-out pattern.

Compare context.WithTimeout and WithDeadline in Go: the same mechanism, how to choose, how deadlines nest, and how to share one budget across calls.

Use context.AfterFunc to run cleanup when a context ends and context.WithoutCancel to detach work from a request, with runnable examples and traps.

How context.Canceled and context.DeadlineExceeded travel through Go code, how to test for them after wrapping, and how Cause records why a context ended.

A guide to context in Go: the Context interface, cancel trees, timeouts and deadlines, values, passing rules, HTTP and database use, and common mistakes.

When to use context.WithValue in Go: request IDs and identity, typed keys and accessors, collision traps, lookup cost, and what to keep out of the context.