Go context.DeadlineExceeded vs Canceled and Goroutine Leaks
A deadline is retryable and a cancellation is not, and both arrive wrapped. The errors.Is checks, the four handler timeouts, and the goroutine dump that names the leak.

Introduction & Quick Summary
Symptom. A service logs Get "https://api.partner.com/v1/orders": context deadline exceeded under load, and sometimes context canceled for the same code path. Meanwhile runtime.NumGoroutine() climbs from a few hundred to tens of thousands over a day, memory follows, and eventually the process is OOM-killed. Each individual error looks transient, so retries mask it until they do not.
Cause. context.DeadlineExceeded means a deadline you or your caller set has passed. context.Canceled means the context was cancelled from outside — a parent context, an HTTP client disconnect, a defer cancel() that ran early. They are different failures and deserve different handling: a deadline is often retryable, a cancellation usually is not. Goroutine leaks are almost always an unfinished send or receive or an unclosed response body: a goroutine blocked forever on a channel or a socket that nobody will ever read.
Fix. Give every outbound call a derived context with a timeout, test with errors.Is(err, context.DeadlineExceeded) rather than string matching, always defer resp.Body.Close() and drain the body, and make every goroutine you start capable of exiting when its context is done. Then take a goroutine dump and read the stacks, which name the exact blocking line.
Core Mechanics, Signatures & Reproducible Setup
Two contexts, two different meanings, both wrapped by *url.Error:
resp, err := client.Do(req)
switch {
case errors.Is(err, context.DeadlineExceeded):
// our deadline (or the client timeout) expired: candidate for retry
case errors.Is(err, context.Canceled):
// caller went away: do not retry, stop work
case err != nil:
// network or protocol error
}errors.Is reaches through *url.Error, fmt.Errorf("%w") and errors.Join, so wrapping is safe. String comparison (strings.Contains(err.Error(), "deadline")) breaks the moment a message changes or a proxy returns the phrase in a body.
A reproducible leak — every request starts a goroutine that can never finish:
var ch = make(chan int) // unbuffered, package level
func handler(w http.ResponseWriter, r *http.Request) {
go func() {
ch <- compute() // blocks forever: nothing receives
}()
w.WriteHeader(http.StatusAccepted)
}Fixing it means giving the send a way out:
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ch := make(chan int, 1) // buffered: send never blocks
go func() {
select {
case ch <- compute():
case <-ctx.Done(): // client gone, goroutine exits
}
}()
w.WriteHeader(http.StatusAccepted)
}The diagnosis is a dump. SIGQUIT prints every goroutine with its stack; net/http/pprof gives the same on demand:
import _ "net/http/pprof" // registers /debug/pprof on http.DefaultServeMux
// curl -s localhost:6060/debug/pprof/goroutine?debug=2 | head -100go tool pprof http://localhost:6060/debug/pprof/goroutine groups the stacks by function, so the leak shows as thousands of identical frames at your own line number.
Key Comparison Table
| Error | Source | Retry? | Check |
|---|---|---|---|
context.DeadlineExceeded | Your deadline or Client.Timeout | Usually yes, with backoff | errors.Is |
context.Canceled | Parent ctx, client disconnect, early cancel() | No | errors.Is |
net/http: request canceled | Transport-level cancellation | No | req.Context().Err() |
i/o timeout | Socket read/write deadline | Yes | net.Error.Timeout() |
connection reset by peer | Peer or LB closed the socket | Once, idempotent only | errors.Is(err, syscall.ECONNRESET) |
context deadline exceeded (Client.Timeout exceeded while awaiting headers) | http.Client.Timeout | Yes | url.Error.Timeout() |
| Goroutine leak | Signature in the dump | Fix |
|---|---|---|
| Unbuffered send with no reader | chan send in your handler | Buffer, or select with ctx.Done() |
| Response body never closed | net/http.(*persistConn).readLoop | defer resp.Body.Close() |
| Body closed but not drained | Many readLoop states | io.Copy(io.Discard, resp.Body) |
| Ticker never stopped | time.Tick frames | defer ticker.Stop() |
WaitGroup never done | sync.WaitGroup.Wait | defer wg.Done() on every path |
| Server handler blocked on a lock | sync.(*Mutex).Lock | Shorten the critical section |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. http.Client.Timeout and a context deadline fight each other
Client.Timeout covers the entire request including body read; a context deadline covers only the request. Mixing them produces the (Client.Timeout exceeded while awaiting headers) suffix on some errors and a bare context deadline exceeded on others, which sends debugging in two directions.
client := &http.Client{
Timeout: 0, // no global cap; the ctx owns the budget
Transport: &http.Transport{
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
ResponseHeaderTimeout: 8 * time.Second,
IdleConnTimeout: 90 * time.Second,
},
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)2. defer cancel() inside a loop
defer runs at function exit, so a loop that creates contexts accumulates timers and keeps every context alive until the handler returns. Cancel explicitly, or move the body into a closure:
for _, id := range ids {
func() {
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()
_ = fetch(ctx, id)
}()
}3. A cancelled context that is really a timeout
r.Context() on an HTTP server is cancelled when the client disconnects. If a load balancer has a 5 s timeout and your handler needs 6 s, the handler sees context canceled while the real cause is a timeout at the LB. Log both r.Context().Err() and the elapsed time; the pair distinguishes them:
start := time.Now()
err := doWork(r.Context())
log.Info("work done", "err", err, "ctxErr", r.Context().Err(), "elapsed", time.Since(start))4. errgroup that reports the wrong error
errgroup.WithContext cancels siblings when one fails, so the error you observe may be a sibling's context canceled rather than the original cause. Inspect ctx.Err() and use g.Wait()'s error, not the per-call one:
g, ctx := errgroup.WithContext(r.Context())
g.SetLimit(8)
for _, u := range urls {
u := u
g.Go(func() error { return fetchInto(ctx, u) })
}
if err := g.Wait(); err != nil {
// the first non-nil error, not a sibling cancellation
}5. Bodies that are closed but not drained
resp.Body.Close() without reading the body prevents connection reuse; the transport keeps the connection in a half-read state until IdleConnTimeout, and under high volume you see growing goroutines in readLoop plus too many open files. Drain small bodies:
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
log.Warn("upstream error", "status", resp.StatusCode, "body", string(body))
} else {
_, _ = io.Copy(io.Discard, resp.Body)
}6. Server timeouts that keep a stuck goroutine alive forever
A handler blocked on a downstream call holds its goroutine; without server write timeouts the connection never closes and the goroutine never returns. Set all four:
srv := &http.Server{
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 60 * time.Second,
Handler: mux,
}Common Compilation/Runtime Mistakes & Version Gotchas
- Comparing context errors as strings. Wrapped errors (
fmt.Errorf("fetch: %w", err)) do not equalcontext.DeadlineExceeded;==fails,errors.Isworks. This includeserrors.Joinfrom Go 1.20 anderrgroupresults. - Passing
nilcontext.http.NewRequestWithContext(nil, …)panics;context.TODO()is the placeholder for tests only. Handlers should derive fromr.Context(). - Storing a context in a struct. Contexts belong in call parameters; a stored context ties a long-lived object to one request's lifetime and cancels work at the wrong time.
time.Afterin a loop. Each call allocates a timer that lives until it fires; in a busy select loop this leaks. Usetimer := time.NewTimer(...)anddefer timer.Stop().context.Causesince Go 1.20. It returns the error passed toWithCancelCause, which is how you distinguish "cancelled because the parent failed" from "cancelled because the request ended".ctx.Err()alone loses that.- Leak tests missing.
go.uber.org/goleakinTestMaincatches a leak in CI instead of production:defer goleak.VerifyNone(t)after the test. - Simultaneous deadline and cancel. When both fire, which error you see depends on timing; treat
Canceledwith a fully elapsed deadline as a deadline, which is why logging elapsed time matters.
Related tools. Reproduce the upstream call outside Go with the cURL builder to see whether the timeout is on the wire or in the process, convert the deadline and elapsed values into a readable timeline with the timestamp converter, and format the goroutine dump's JSON logs for grouping with the JSON formatter.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo Module Errors: Checksum Mismatch, 404s, and Proxy Failures
A checksum mismatch is not a cache bug. Separate the proxy, the sum database, and go.sum, then fix the layer the message names instead of editing the hash.
Go iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.