Go errgroup SetLimit: Why Cancellation Does Not Stop Admission

Go errgroup SetLimit bounds active tasks; it does not make submission cancellation-aware. Calling g.SetLimit(4) configures a Group's concurrency limit. Once every slot is full, context cancellation by itself will not unblock a caller waiting to submit a task.

The distinction is between admission, execution, and joining. Adding WithContext provides a cancellation signal, yet each boundary must handle it explicitly. Transport deadlines form a separate boundary; see the related Python Requests timeout and retry guide.

On this page
  1. Evidence: one pinned errgroup release
  2. Trace admission, execution, and Wait separately
  3. Reproduction: three assertions without a timing benchmark
  4. Read the assertions as expectations, not performance results
  5. Choose where cancellation-aware admission belongs
  6. Failure modes: nested submission and misleading fixes
  7. Limitations and a focused batch audit

Evidence: one pinned errgroup release#

This source-level analysis covers golang.org/x/sync v0.17.0. It is not an upgrade recommendation or a claim about the newest release. The conclusions below come from the linked implementation and upstream tests, not execution of the example.

The Go repository’s tag-reference response identifies commit 04914c200cb38d4ea960ee6a4c314a028c632991. Its first-party implementation is https://raw.githubusercontent.com/golang/sync/04914c200cb38d4ea960ee6a4c314a028c632991/errgroup/errgroup.go; the upstream tests provide additional assertions.

A commit identifies the inspected revision, not application correctness. For the related distinction between artifact identity and trust, see what SHA-256 checksums prove.

Trace admission, execution, and Wait separately#

In Go, the submitting goroutine sends to the internal semaphore synchronously before registering the task or spawning a goroutine. When that semaphore is full, the caller blocks without inspecting any context.

Inside the launched function, application code owns cooperation with cancellation. The Go team’s first-party explanation, https://go.dev/blog/context, describes Done as a signal that functions should abandon work and return—not a mechanism that forcibly terminates goroutines.

The version-specific package reference documents that Wait blocks until all started tasks finish and returns the first non-nil error among them. Canceling the parent context neither sets this error nor cuts the wait short. Because Wait always cancels the derived context before returning, avoid reusing that context afterward.

Reproduction: three assertions without a timing benchmark#

Use a supported Go toolchain capable of building the pinned module, with network access for dependency resolution. Work in a new disposable directory rather than changing an application’s dependencies.

mkdir errgroup-boundary
cd errgroup-boundary
go mod init example.com/errgroup-boundary
go get golang.org/x/sync@v0.17.0
go list -m golang.org/x/sync

Save this complete file as admission_test.go. It uses channels to establish ordering instead of guessing how much scheduling time a sleep provides.

package boundary

import (
    "context"
    "errors"
    "testing"

    "golang.org/x/sync/errgroup"
)

func TestGoAdmitsCanceledContext(t *testing.T) {
    parent, cancel := context.WithCancel(context.Background())
    defer cancel()
    g, ctx := errgroup.WithContext(parent)
    g.SetLimit(1)

    release := make(chan struct{})
    g.Go(func() error {
        <-release
        return nil
    })

    cancel()
    <-ctx.Done()
    denied := !g.TryGo(func() error { return nil })
    close(release)

    seen := make(chan error, 1)
    g.Go(func() error {
        seen <- ctx.Err()
        return nil
    })
    if err := g.Wait(); err != nil {
        t.Fatalf("Wait = %v; want nil", err)
    }
    if !denied {
        t.Fatal("full limit admitted an extra task")
    }
    if err := <-seen; !errors.Is(err, context.Canceled) {
        t.Fatalf("task context = %v; want canceled", err)
    }
}

func TestTryGoAdmitsCanceledContext(t *testing.T) {
    parent, cancel := context.WithCancel(context.Background())
    defer cancel()
    g, ctx := errgroup.WithContext(parent)
    g.SetLimit(1)
    cancel()
    <-ctx.Done()

    seen := make(chan error, 1)
    if !g.TryGo(func() error {
        seen <- ctx.Err()
        return nil
    }) {
        t.Fatal("free slot rejected the task")
    }
    if err := g.Wait(); err != nil {
        t.Fatalf("Wait = %v; want nil", err)
    }
    if err := <-seen; !errors.Is(err, context.Canceled) {
        t.Fatalf("task context = %v; want canceled", err)
    }
}

func TestSuccessfulWaitCancelsContext(t *testing.T) {
    g, ctx := errgroup.WithContext(context.Background())
    g.Go(func() error { return nil })
    if err := g.Wait(); err != nil {
        t.Fatalf("Wait = %v; want nil", err)
    }
    if !errors.Is(ctx.Err(), context.Canceled) {
        t.Fatalf("context after Wait = %v; want canceled", ctx.Err())
    }
}
go test -run 'Test(GoAdmitsCanceledContext|TryGoAdmitsCanceledContext|SuccessfulWaitCancelsContext)$' -count=1 -timeout=10s .

The timeout guards against a hung example; it is not a measured cancellation target. The commands and assertions are provided for reproduction, not presented as an observed run.

Read the assertions as expectations, not performance results#

The first test holds the only slot, cancels the parent, and checks that TryGo rejects submission while capacity is full. After releasing the held function, a subsequent Go call admits work that sees an already-canceled context.

Both functions deliberately return nil, so the assertion expects Wait to return nil. Returning ctx.Err() instead would supply a task error for the group to report.

The second test isolates TryGo with free capacity after cancellation. The third expects successful Wait to cancel the derived context, consistent with upstream TestWithContext cases.

These assertions do not measure how long a blocked Go call remains blocked. The absence of a cancellation branch follows from the source, not a timing experiment.

Choose where cancellation-aware admission belongs#

For a finite batch, SetLimit often suffices. Inspect the context before calling Go and again inside each task prior to heavy operations. Pre-submission checks cannot abort an in-flight semaphore wait, while in-task checks run only after a slot opens.

When a blocked producer needs immediate interruption, switch to a fixed worker pool fed by a bounded channel. Launch workers before sending jobs, and use select to race channel sends against context cancellation. The official pipelines and cancellation article explains this pattern and how abandoned receivers can leave senders stuck.

Selecting on cancellation does not guarantee a hard admission cutoff, because Go chooses pseudo-randomly when both send and done cases are ready. Workers must still verify context state before doing costly work, and strict cutoffs require explicit synchronization.

The worker count caps concurrent execution, whereas channel buffer size caps waiting items—not total memory footprint or downstream output volume. Assign clear responsibility for closing channels and ensure every pipeline stage can exit cleanly on upstream or downstream failure.

Failure modes: nested submission and misleading fixes#

Nested submission can deadlock. With a limit of one, an active function calling Go on that same group blocks forever waiting for the very slot it holds, and context cancellation cannot break the wait. Keep task submission flat or route child tasks through an independent pool.

Extra goroutines move the queue. Wrapping each g.Go in an outer goroutine merely shifts unbounded waiting onto the Go runtime scheduler. Because WaitGroup registration occurs only after acquiring a semaphore token, finish coordinating submissions before relying on Wait as the final barrier. Follow the documented first-call-before-Wait rule.

Rejection needs a policy. A false result from TryGo indicates the group skipped the task entirely. Handle this by dropping the item, routing it to a bounded queue, or running a controlled fallback. Spinning in a tight loop around TryGo wastes CPU without providing fair admission or context awareness, and executing fallback work inline bypasses the group's concurrency cap.

Zero is not a pause switch. Setting the limit to zero blocks or rejects all new tasks, and errgroup panics if SetLimit runs while goroutines remain active—making it unsuitable for dynamic throttling or graceful shutdown.

Limitations and a focused batch audit#

This source-level analysis is pinned to one release. It establishes neither throughput, memory use, fairness, nor cancellation latency. Cancellation cannot stop application code that does not observe it or otherwise return. Driver, network, and callback behavior requires separate integration tests with deadlines and failure cases.

  1. Compare your application’s actual module version with this baseline.
  2. Identify what releases each admission, operation, and joining wait.
  3. Decide whether callers need task errors, parent cancellation when tasks return nil, or collected results.
  4. Keep group-context lifetime separate from follow-up work.
  5. Test canceled parents with free and full capacity, successful joining, and nested-submission hazards.

If admission can resume only when another function returns, decide whether that is the cancellation contract your application needs.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *