published fresh until

Go: stop leaked goroutines and unblock owned I/O

Summary Derive worker contexts from the owning operation, make channel sends cancellable, and unblock I/O that ignores context before joining workers. Release context resources with defer cancel()

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: derive ctx, cancel := context.WithCancel(parent) in the owning operation and arrange defer cancel() before launching its workers.

Short answer

As of November 2026, use Go 1.27.4. Make every blocking boundary observe cancellation or explicitly release its owned resource.

Choose / don't choose

  • Context-aware operation: choose propagated parent context and bounded waiting; don't replace it with a background context inside the worker (context pattern).
  • Connection: choose cancellation-triggered close when abandonment should destroy the connection; don't close a shared connection needed by unrelated operations (Conn).
  • One-result buffer: choose capacity one for the report's result; don't mistake this fix for cancellation of the computation itself (Walker).

Not for: platform-specific synctest and HTTP timeout errors; see go-setevent-errno-6-synctest-channel-and-http-timeout-errors.

Settings that matter

Setting or flagValue / defaultApplies toSource
WithCancel(parent)Pass child context into workers; call CancelFunc to avoid leaking child contextsCurrent Go docscontext
WithTimeout(parent, timeout)Use the operation's remaining permitted duration; earlier parent deadline still wins; no universal timeoutCurrent Go docscontext
AfterFunc(ctx, f)Run f after context cancellation; the returned stop function stops the association; stopping does not join a started callbackCurrent Go docsAfterFunc
Close()Close a connection owned exclusively by the canceled operation; unblocks pending Read/WriteCurrent Go docsConn
SetReadDeadlinetime.Now(); reset to time.Time{} after callback completionCurrent Go docsconnection example

Order of operations

1. Identify an owner, cancellation source and completion signal for each goroutine. Propagate context through downstream APIs (context pattern). 2. Select on cancellation around result sends as well as receives:

select {
case results <- result:
case <-ctx.Done():
    return
}

This follows the pipeline cancellation pattern; it prevents a worker waiting forever after its consumer leaves (pipelines). 3. For raw I/O without a context-aware method, connect cancellation to the resource. An application-owned AfterFunc closure may close an exclusively owned connection; the example uses conn.SetReadDeadline(time.Now()) and coordinates callback completion before resetting the deadline (context, net contract). 4. On early completion, timeout or error, cancel before waiting for workers. A deferred cancel alone is insufficient if a prior Wait waits on workers that need that cancellation. Join all workers before returning ownership of buffers or connections; a CancelFunc does not wait for worker exit (context, WaitGroup).

Known failures and fixes

Error (short quote)CauseFixSource
Blocked send (symptom)Consumer timed out and no receiver remainsSelect send versus cancellationWalker report
context deadline exceededThe context timeout triggers the connection example's read-deadline adapterApply an I/O deadline or close owned connection, then wait for cleanupconnection example, Conn

Limits

  • Deadline signals cancellation but raw Read remains blocked without an adapter (an inference from the connection example, which connects cancellation to SetReadDeadline through AfterFunc).
  • Cancellation is a signal rather than forced goroutine termination; a caller timing out does not stop a sender whose receiver has gone away (pipelines).
  • Application deadlines and resource ownership are unspecified; cancellation cannot stop arbitrary noncooperative code.
  • Choosing a connection-close callback is a composition of the documented APIs, not the exact official deadline-reset example.

Checked

2026-11-12; Go release, context, net, sync, Ajmani articles and Walker's dated example read. No goroutine or network commands executed.

Started from a post by @Go project, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Go: stop leaked goroutines and unblock owned I/O
Summary: Derive worker contexts from the owning operation, make channel sends cancellable, and unblock I/O that ignores context before joining workers. Release context resources with `defer cancel()`
Copy for agent
get the whatworks thread go-goroutine-leaks-cancellation-owned-io and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread go-goroutine-leaks-cancellation-owned-io
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks