By Chason ArthurRevision 126.014Published Updated

Go / Concurrency / Cancellation

Who left these workers running?

The customer cancels. The collector stops. The workers keep waiting. See the difference between starting concurrent work and owning its whole lifetime.

The idea in plain language

A goroutine needs an owner and a way to finish. A bounded worker pool limits active work; cancellation must reach both producers and workers; joining them establishes that shutdown has actually completed.

The browser runs the same Go engine compiled to WebAssembly inside a dedicated worker. Goroutines run concurrently, but this browser target is not a multicore throughput benchmark. A harness cleans up the deliberately blocked example after recording it. The native download includes an HTTP adapter and Go tests.

Your independent testing environment

Make the failure visible.

Keep the default 12 messages, 3 workers and early cancellation. Run without safeguards, then with safeguards. Compare peak active work and workers left at cancellation. Reset starts over and stops pending work.

Ready to try

—Peak active work
—Messages completed
—Workers at cancellation
—Workers after cleanup

Follow the decision

    Inspect the result

    Your result and database records will appear here.

    Why the change matters

    Show the canceled collector first. Explain who owns the queue, who closes it, how blocked work stops and why the function waits for workers. Separate concurrency safety from the delivery guarantee.

    Use the code viewer to inspect the original source that produced this release. Each file is checked against the release manifest before it is displayed. The complete download includes the runnable example, tests, setup instructions and third-party notices.

    Download this lab

    Keep exploring

    Follow the question you have next.

    Build the safeguards

    Eight explained steps, tradeoffs, pitfalls and a checkpoint before moving on.

    Read the tutorial

    Compare the choices

    Choose a pattern and an environment for the problem you actually have.

    Compare approaches

    Questions before you start

    Do I need to know how to code?

    No. Start with the default example, read the trace and compare the two implementations. The tutorial introduces the code after you have seen the result.

    Does this use real customer data or send anything?

    No. Examples use invented records and simulated downstream work. Each lab keeps its own transient environment; resetting it stops the experiment.

    What can this experiment prove?

    The browser runs the same Go engine compiled to WebAssembly inside a dedicated worker. Goroutines run concurrently, but this browser target is not a multicore throughput benchmark. A harness cleans up the deliberately blocked example after recording it. The native download includes an HTTP adapter and Go tests.

    Can I use or change the source?

    The original lesson and application source are MIT-licensed. Third-party runtimes retain their own licenses. Download the package and follow GETTING_STARTED before changing it.

    Lab discussion / Go Worker Lab

    What would you try next?

    Ask about the code, compare an approach, or describe an edge case. Reader comments are reviewed before publication.

    All lab discussions

    Reader comments

    Open the discussion to read and add reader comments.

    Read or write a comment →

    Code walkthrough

    Follow the implementation in code.

    These short excerpts connect the lab’s behavior to its implementation. Each example links to the full tutorial step for its context, tradeoffs and checkpoint. Names and dependencies belong to that source; the excerpts are not standalone programs.

    Example 01 · Tutorial excerpt

    Bound work before reaching the downstream service

    The safeguarded path creates a fixed number of workers and a queue whose capacity equals that count. A producer sends messages through the queue. When the queue fills, the producer waits, limiting how far it gets ahead. This is backpressure: the upstream workload must respect downstream capacity.

    jobs := make(chan int, config.Workers)
    for range config.Workers { /* start one worker */ }

    Read the full tutorial step

    Example 02 · Tutorial excerpt

    Send cancellation through every blocking boundary

    Both the producer send and the worker receive are select operations that also observe ctx.Done. A worker waiting for its simulated downstream result has its own cancellation branch. It stops its timer and records an incomplete outcome before returning. The final join runs after those paths settle.

    select {
    case <-ctx.Done(): return
    case jobs <- id:
    }

    Read the full tutorial step

    Example 03 · Tutorial excerpt

    Synchronize the shared observations

    Workers update the same counters. A mutex protects both updates and snapshots so measurements themselves do not introduce a data race. The live panel displays per-run started, completed, failed and peak values from the engine result. It does not treat process-wide goroutine counts as an exact measure of application leaks.

    c.mu.Lock()
    defer c.mu.Unlock()
    c.active++
    c.result.Started++

    Read the full tutorial step

    Example 04 · Tutorial excerpt

    Distinguish failure, cancellation and successful completion

    Every fourth message can be made to fail. That is a handled result from the simulated downstream operation, not a panic. Cancellation stops unfinished work; it does not make it successful. Run with cancellation disabled to compare completed plus failed outcomes with the message count.

    if config.FailEvery > 0 && id % config.FailEvery == 0 {
        c.end("failed")
    } else { c.end("completed") }

    Read the full tutorial step

    Example 05 · Tutorial excerpt

    Run the native service and review its boundaries

    The download includes a loopback HTTP adapter on 127.0.0.1:4188. It accepts a bounded JSON configuration, limits concurrent experiments, derives a deadline from the request context and returns the engine result. It is an independent local test environment, not a new public notification service.

    go test ./...
    go run ./cmd/server
    # POST a sample configuration to /api/run

    Read the full tutorial step