Skip to content
Engineering Thoughts
ArticlesTopicsSeriesLearningResources
Search⌘ K

Engineering Thoughts

Field notes for engineers building systems that have to work.

AboutArchiveRSSGitHub

© 2026 Sibilesh. Built with care and open tools.

gointermediate1 min readJul 5, 2026

Structured Concurrency in Go with Context

Use cancellation, ownership, and bounded parallelism to build Go services that shut down cleanly and remain understandable.

SBy Sibilesh

On this page

  1. Cancellation is part of the API
  2. Bound every fan-out

Goroutines are inexpensive, but they are not free and they do not have an owner by default. Structured concurrency gives each unit of work a lifetime tied to the request that created it.

Cancellation is part of the API

Pass context.Context as the first argument and never store it on a long-lived struct.

A bounded worker group
func hydrate(ctx context.Context, ids []string) error {
    group, ctx := errgroup.WithContext(ctx)
    group.SetLimit(8)
 
    for _, id := range ids {
        id := id
        group.Go(func() error {
            if err := ctx.Err(); err != nil {
                return err
            }
            return fetchAndStore(ctx, id)
        })
    }
    return group.Wait()
}
Avoid detached work

If a request starts background work that must outlive it, hand that work to a durable queue. Replacing the context with context.Background() only hides ownership.

Bound every fan-out

Unbounded parallelism moves the bottleneck downstream. Choose a limit from dependency capacity, then verify it with load tests and production telemetry.

The easiest concurrency code to operate has clear ownership, a deadline, and one place where errors rejoin the caller.

Keep exploring

Related field notes.

devops
devopsintermediate2 min

Building GitLab Pipelines That Fail Well

A practical system for fast, observable CI/CD pipelines that recover gracefully when infrastructure and dependencies misbehave.

Jul 12, 2026
kubernetes
kubernetesbeginner1 min

The Kubernetes Signals I Check First

A repeatable debugging sequence for separating scheduling, networking, application, and capacity failures in Kubernetes.

Jun 21, 2026

Continue the discussion

Comments are enabled at deployment.

Configure the public Giscus environment variables to connect GitHub Discussions.