Worker Pools, Pipelines, Fan-Out/Fan-In, errgroup, Bounded Concurrency
"Informally, a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function." — Sameer Ajmani, Go Concurrency Patterns: Pipelines and cancellation, The Go Blog, 13 March 2014
Summary: A worker pool is a fixed number of goroutines reading a jobs channel and writing a results channel; a pipeline is a chain of such stages; fan-out puts several goroutines on one stage and fan-in merges their outputs; errgroup, semaphore.Weighted and a chan struct{} cap how many things run at once. Together they turn "do 50 000 things concurrently" into code that is bounded, cancelable, ordered when it must be, and leak-free. Focus: Fixed workers, jobs and results channels, the WaitGroup that closes results, result ordering by index and reorder buffers, per-job timeout, panic recovery per job, graceful drain, chan struct{} and semaphore.Weighted semaphores, errgroup (WithContext, Go, TryGo, SetLimit, Wait, first error cancels, context.Cause), collecting every error with errors.Join, pipeline stages with ctx cancellation, buffered stages and backpressure, fan-out/fan-in with Merge, static split vs shared queue and work stealing, batches with slices.Chunk, iter.Seq sources, rate limiting with x/time/rate, retry with idempotency keys, pool sizing (NumCPU, GOMAXPROCS, CPU-bound vs IO-bound), observability (queue depth, in-flight, latency histogram), goroutine leaks and the Go 1.27 goroutineleak profile, the classic bugs, conc, and Laravel queue workers, Horizon and Concurrency::run. Learning goal: Pick the right concurrency shape for a job, write it so that every goroutine has an owner and an exit, prove the concurrency cap, the ordering and the absence of leaks in tests, and size and observe it in production.
This page owns the patterns built from goroutines and channels. It does not re-teach the primitives: channel directions, buffering and close are in Goroutines & Channels; select, non-blocking sends and timeouts are in select; how a context.Context is created, canceled and propagated is in context; sync.WaitGroup, Mutex, Once and atomics as primitives are in sync & atomic; the race detector and deadlock theory are in Race Conditions, the Race Detector, Deadlocks; token-bucket theory and HTTP middleware limiters are in Rate Limiting in Go; panic and recover mechanics are in Errors, Wrapping, Panic, Recover & Defer. Across processes, the same ideas become Competing Consumers, Backpressure & Flow Control and Idempotent Consumers.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
Why not just go f() for every item | Why it exists |
| 2010 to Go 1.27: what changed and when | Where it comes from |
| Fixed workers, jobs channel, results channel, closing results | Worker pool |
| Getting results back in input order | Result ordering |
| Per-job timeout, panic recovery, graceful drain | Job lifecycle |
chan struct{}, semaphore.Weighted | Bounded concurrency with semaphores |
errgroup: Go, TryGo, SetLimit, Wait, first error cancels | errgroup |
All errors, not just the first: errors.Join | Collecting every error |
| Stages, done channel, ctx cancellation, closing in order | Pipelines |
| Buffers, unbuffered channels, backpressure | Buffered stages and backpressure |
Fan-out, fan-in, Merge | Fan-out and fan-in |
| Static split, shared queue, work stealing | Distributing work |
Batches, chunks, slices.Chunk, iter.Seq sources | Batches and iterators |
x/time/rate, retry, idempotency inside workers | Rate limits and retries |
How many workers: NumCPU, GOMAXPROCS, IO-bound | Pool sizing |
| Goroutine per request vs pool | Goroutine per request |
| Goroutine leaks, queue depth, in-flight, histograms | Leaks and observability |
conc and other libraries | Libraries |
| Bad code and the fix, side by side | Go |
| Exact runtime, vet and race messages | Mechanics |
| Tested code for each classic problem | Solving the classic problems |
| Which shape for which situation | Choosing |
Laravel queue workers, Horizon, Concurrency::run | For PHP/Laravel developers |
| Pools per service, queues between services | In architecture |
| Run every bug yourself | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The shapes. Every row is unpacked in the concept catalogue.
| Shape | In plain words | Tiny example | Bounded? |
|---|---|---|---|
| Goroutine per item | Start one goroutine for each thing | for _, u := range urls { go fetch(u) } | No: n goroutines, n connections |
| Worker pool | N long-lived goroutines take jobs from one channel | for range n { go worker(jobs, results) } | Yes: N workers, queue of Q |
| Semaphore | Anyone may start, but only N hold a slot at once | sem <- struct{}{}; defer func() { <-sem }() | Yes: N in flight |
| Weighted semaphore | Slots have sizes; a big job takes many | sem.Acquire(ctx, fileMB) | Yes: total weight |
| errgroup + SetLimit | Semaphore + WaitGroup + first error cancels | g.SetLimit(8); g.Go(f); g.Wait() | Yes: N in flight |
| Pipeline | Stages connected by channels, each stage closes its output | sink(sq(gen(ctx, nums))) | Yes, by channel capacity |
| Fan-out | Several goroutines read the same input channel | c1, c2 := sq(in), sq(in) | N copies of a stage |
| Fan-in | One channel fed by several, closed when all are done | Merge(ctx, c1, c2) | — |
The tools and when they arrived.
| Tool | Package | What it gives you | Since |
|---|---|---|---|
go, chan, select, close | language | Goroutines and channels | Go 1.0 |
sync.WaitGroup | sync | Wait for N goroutines | Go 1.0 |
context.Context | context | Cancellation and deadlines across stages | Go 1.7 |
errgroup.Group | golang.org/x/sync/errgroup | WaitGroup + first error + ctx cancel | 2016 (x/sync) |
errgroup SetLimit, TryGo | same | Bounded concurrency, non-blocking start | May 2022 |
semaphore.Weighted | golang.org/x/sync/semaphore | Weighted, ctx-aware semaphore | 2017 (x/sync) |
rate.Limiter | golang.org/x/time/rate | Token bucket: events per second + burst | x/time |
errors.Join, context.WithCancelCause | errors, context | Many errors in one; cancel with a reason | Go 1.20 |
| per-iteration loop variables | language | go func() { use(i) }() in a loop is safe | Go 1.22 |
iter.Seq, range over func, slices.Chunk | iter, slices | Iterator sources, batches | Go 1.23 |
WaitGroup.Go, testing/synctest, vet waitgroup | sync, testing | Fewer Add/Done bugs, fake-clock tests | Go 1.25 |
container-aware GOMAXPROCS | runtime | Default respects the cgroup CPU limit | Go 1.25 (language version 1.25+) |
goroutineleak profile | runtime/pprof | Reports goroutines that can never wake | Go 1.26 experiment, Go 1.27 GA |
The bugs and their one-line fixes.
| Bug | Symptom | Fix |
|---|---|---|
| Results channel never read | Workers block, fatal error: all goroutines are asleep - deadlock! or a silent hang | Read until closed, or buffer to the exact count |
| Several workers close the results channel | panic: close of closed channel | Only the WaitGroup closer goroutine closes |
| Producer sends after close | panic: send on closed channel | The sender closes; nobody else |
Forgot wg.Wait() | Output silently missing | Wait before reading shared results |
wg.Add(1) inside the goroutine | Flaky: Wait returns early; vet: WaitGroup.Add called from inside new goroutine | Add before go (or wg.Go) |
| Early return on first error | Goroutine leak: senders block forever | ctx cancel + select on send, or errgroup |
| Append to a shared slice from workers | WARNING: DATA RACE, lost results | Write by index, or one collector goroutine |
SetLimit(0) | g.Go blocks forever | Negative means no limit; 0 admits nobody |
| Unbounded goroutines per request | Memory, file descriptors, downstream overload | Semaphore or pool; shed with TryGo |
Why it exists
Starting a goroutine costs a few kilobytes of stack and a function call, so the first instinct is to start one per item. That instinct is right for ten items and wrong for fifty thousand: each goroutine opens a connection, holds a buffer and competes for the same downstream database or API. Nothing in the language stops you from opening 50 000 sockets to a partner that allows 20 requests per second. The patterns on this page exist to put back three things that "just use go" removes: a bound (how many at once), an owner (who waits for them, who cancels them, who closes their channels), and a contract for results (order, errors, partial success). Effective Go makes exactly this point about a server that starts a goroutine per request: "the program can consume unlimited resources if the requests come in too fast."
Unbounded (go per item) | Bounded (pool, semaphore, errgroup) |
|---|---|
| Simplest code | A few more lines: limit, owner, closer |
| Memory O(items) | Memory O(workers + queue) |
| Downstream sees a spike of n connections | Downstream sees at most N |
| Errors: whoever reads first | Errors: first-error-cancels or all joined, by design |
| Cancellation: none unless you add it | ctx reaches every worker |
| Order: completion order | Order: by index when required |
| Leaks easy on early return | Every goroutine has an exit path |
The analogy we reuse on this page: a restaurant kitchen. Order tickets go on a rail (the jobs channel). A fixed number of cooks (the workers) take the next ticket when their hands are free. Finished plates go to the pass (the results channel), and the expeditor puts them back in table order (result ordering). When the rail is full the waiter cannot pin another ticket and must wait (backpressure). A big kitchen is a line of stations — prep, grill, plating — each handing plates to the next (pipeline stages); the slow grill gets three cooks (fan-out) whose plates meet at one counter (fan-in). The head chef can shout "stop" and every station drops what it is doing (ctx cancellation). At closing time no new tickets are taken, but every ticket on the rail is still cooked (graceful drain). A cook who cuts a finger is bandaged and keeps working instead of the kitchen burning down (panic recovery per job).
Three common misunderstandings, up front
- "More goroutines means more throughput." Only until you saturate the real bottleneck: CPU cores for CPU-bound work, the downstream's connection or rate limit for IO-bound work. Past that point extra goroutines add memory, contention and tail latency. The Go blog's MD5 example moves from one goroutine per file to "a fixed number of goroutines for reading files" for precisely this reason.
- "Goroutines are garbage collected when nobody needs them." They are not. The pipelines post: "Goroutines are not garbage collected; they must exit on their own." A goroutine blocked forever on a send nobody will receive is a leak, and so is everything its stack references.
- "errgroup returns all the errors."
Wait"returns the first non-nil error (if any)"; the others are dropped. If you need all of them, collect them yourself and useerrors.Join(see Collecting every error).
Where it comes from
The idea of processes connected by channels is older than Go (Hoare's CSP), but the Go idioms were written down in a small number of primary texts. Andrew Gerrand's Go Concurrency Patterns: Timing out, moving on (23 September 2010) showed the buffered-channel trick that lets a goroutine send and exit even if nobody receives, and a "first response wins" query across replicas. Effective Go described a buffered channel used "like a semaphore, for instance to limit throughput", and the alternative of "a fixed number of handle goroutines all reading from the request channel" — the two halves of this page. Sameer Ajmani's Pipelines and cancellation (13 March 2014) defined stages, fan-out ("Multiple functions can read from the same channel until that channel is closed"), fan-in, the done channel as a broadcast ("closing a channel... is effectively a broadcast signal to the senders"), and bounded parallelism. Go 1.7 (2016) moved context into the standard library, which replaced hand-made done channels in most new code.
golang.org/x/sync/errgroup was added on 13 July 2016; TryGo and SetLimit arrived on 7 May 2022; since 31 March 2023 WithContext cancels with context.WithCancelCause, so context.Cause(ctx) tells a task which error stopped the group. In 2025 errgroup briefly propagated panics through Wait (January) and then reverted it (20 June 2025); the current source explains why: propagating "delays panics arbitrarily", "turns f's panic stack into a mere value" and "risks deadlocks that hide the panic entirely". semaphore.Weighted lives in the same module.
In the language and runtime: Go 1.20 added errors.Join and context.WithCancelCause. Go 1.22 made loop variables per-iteration ("loop variables are created anew for each iteration"), which removed the most common pool bug of the previous decade. Go 1.23 added range-over-func iterators and slices.Chunk ("returns an iterator over consecutive sub-slices of up to n elements of a slice"). Go 1.24 shipped testing/synctest as an experiment. Go 1.25 added sync.WaitGroup.Go ("makes the common pattern of creating and counting goroutines more convenient"), the vet analyzer waitgroup that "reports misplaced calls to sync.WaitGroup.Add", graduated testing/synctest, and made the default GOMAXPROCS respect the cgroup CPU bandwidth limit. Go 1.26 introduced the experimental goroutineleak profile, and Go 1.27 made it generally available (and renamed the vet analyzer to waitgroupgo).
This page was checked against the Go specification as published on go.dev (language version go1.27, May 26, 2026), Effective Go, the Go Memory Model, the Go blog posts above, the release notes 1.22–1.27, go doc from Go 1.27.4, and the source of x/sync v0.19.0 and x/time v0.14.0. The snippet module declares go 1.24.0 and pins those two versions because later releases require Go 1.25/1.26; features newer than 1.24 (WaitGroup.Go, synctest, container-aware GOMAXPROCS) appear in prose only.
The concept catalogue
Each block: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, behaviour per option, and the fix. Full tested code is in Solving the classic problems.
Worker pool: fixed workers, jobs channel, results channel Must-know
In plain words: start N goroutines once; each loops "take a job, do it, hand in the result" until the jobs channel is closed. The number of workers is the concurrency limit.
Common misunderstanding: "Any worker can close the results channel when it finishes." With N workers there are N senders, and a channel must be closed once, after the last send. The safe rule is: the goroutine that knows all senders are done closes it — a separate closer goroutine that runs wg.Wait() then close(results).
Definition: a worker pool is a set of Workers goroutines for j := range jobs { results <- run(j) }, a sync.WaitGroup counting them (Add(N) before starting them), a jobs channel of capacity QueueSize closed by the single producer, and a results channel closed by one closer goroutine after wg.Wait(). Effective Go: "start a fixed number of handle goroutines all reading from the request channel. The number of goroutines limits the number of simultaneous calls to process."
producer jobs (cap 2) worker A worker B closer
1 Submit(j0) ─▶ [j0] <-jobs: j0
2 Submit(j1) ─▶ [j1] <-jobs: j1
3 Submit(j2), Submit(j3) [j2 j3] run j0 run j1
4 Submit(j4) blocks: queue full (backpressure)
5 [j3 j4] results <- r0; <-jobs: j2
6 Close() -> no more jobs; workers keep draining
7 [] ... results <- r4; range ends
8 range ends; Done Done wg.Wait returns
9 close(results)
10 consumer: for r := range results endsReal scenario: generating 200 000 invoice PDFs overnight with 8 workers so the CPU stays busy and the PDF library's memory stays bounded; resizing uploaded images with runtime.NumCPU() workers; a webhook sender with 32 workers against a partner that tolerates 32 open connections; a re-indexing job that pushes documents to a search cluster at a fixed concurrency.
| Option | Bound | Who closes results | Typical bug |
|---|---|---|---|
go per job, results via channel | none | Main after counting n receives | n goroutines, early-return leak |
| Pool, results closed by a worker | N | A worker (wrong) | panic: close of closed channel |
| Pool + closer goroutine | N | wg.Wait(); close(results) | Results never read → workers block |
| Pool, results collected by index | N | Closer | None if every index is written once |
| errgroup + SetLimit | N | No results channel; write out[i] | Forgetting the derived ctx |
Fix / how to use it: workerpool.Pool — Add(N) before the goroutines, closer goroutine, single producer calls Submit and Close, the consumer ranges over Results() to the end.
Result ordering: completion order, index, reorder buffer Must-know
In plain words: workers finish in whatever order their jobs take; if the caller needs output in input order, tag each job with its index and put results back by that index.
Common misunderstanding: "One results channel keeps the order of the jobs channel." It keeps the order of sends, which is completion order. A single slow first item makes it arrive last.
Definition: three strategies. (1) Unordered: consume results as they arrive — right for sums, sets and side effects. (2) Index into a pre-sized slice: out := make([]R, n); worker i writes out[i]; read after Wait — no mutex needed because every goroutine writes a distinct element, and Wait provides the happens-before edge. (3) Reorder buffer for streams: tag with a sequence number, keep early finishers in a map, emit while pending[next] exists — memory is bounded by items in flight, but one slow item blocks all output behind it (head-of-line blocking).
worker A worker B results channel out[] by index
1 start job 0 (slow) start job 1
2 done job 1 r1 [_, r1, _, _]
3 done job 2 r2 [_, r1, r2, _]
4 done job 3 r3 [_, r1, r2, r3]
5 done job 0 r0 [r0, r1, r2, r3]
-> channel order 1,2,3,0; index order 0,1,2,3Real scenario: a CSV export where line i must match row i; a search results page that queries three backends in parallel but must keep the ranking; a log shipper that must keep per-file line order; a price list where the response array must align with the request array.
| Strategy | Memory | Latency to first output | Good for |
|---|---|---|---|
| Arrival order | O(1) | Lowest | Aggregates, idempotent side effects |
out[i] = r after Wait | O(n) | After the whole batch | Finite batches, API responses |
| Reorder buffer | O(window) | Blocked by the slowest in-flight item | Streams that must stay ordered |
| Partition by key, one worker per key | O(1) per key | Per key | "Order per customer", like Kafka partitions |
Fix / how to use it: workerpool.CollectOrdered, after.LoadAll (index) and pipeline.OrderedMap (reorder buffer). When only per-key order matters, hash the key to a fixed worker, as Ordering & Partitioning does across a broker.
Job lifecycle: per-job timeout, panic recovery, graceful drain Must-know
In plain words: each job gets its own deadline, a panic inside a job becomes that job's error instead of killing the process, and shutting down means "stop taking new jobs, finish the queued ones".
Common misunderstanding: "recover in main protects my workers." recover only works in the goroutine that panics, in a deferred function. A panic in any worker without its own recover terminates the whole program (see Boundaries). A second one: "a timeout on the whole batch is enough" — one stuck item then consumes the entire budget of everyone behind it.
Definition: inside the worker, wrap each job in a function with defer func() { if v := recover(); v != nil { res.Err = &PanicError{v, debug.Stack()} } }(), derive context.WithTimeout(ctx, JobTimeout) per job and defer cancel(). Graceful drain: the producer closes the jobs channel; for range jobs keeps returning queued items until the buffer is empty, then ends; the closer closes results. Hard stop: cancel the pool ctx; workers report context.Canceled for queued jobs without running them.
job 7 on worker B
1 start := time.Now(); inFlight++
2 jctx, cancel := context.WithTimeout(poolCtx, 2s)
3 fn(jctx, payload) -> calls a partner API that hangs
4 2s later: jctx.Done() closes; the HTTP client returns "context deadline exceeded"
5 deferred: recover() == nil; Took = 2.0s; inFlight--; histogram.Observe(2.0s)
6 results <- Result{Index: 7, Err: context.DeadlineExceeded}
7 worker B takes job 8 (the pool keeps going)Real scenario: a malformed image makes a decoder panic on one upload out of a million; a partner API hangs on one request without a deadline; a Kubernetes pod receives SIGTERM and has 30 seconds (terminationGracePeriodSeconds) to finish the queued work; a nil map in rarely used code path panics once a week.
| Event | Without lifecycle code | With it |
|---|---|---|
| Job panics | Process exits with status 2 | *PanicError result, worker continues |
| Job hangs | Worker lost forever, pool shrinks | Deadline fires, worker freed |
| SIGTERM | Queued jobs lost or half-done | Close jobs, drain, then exit |
| Pool ctx canceled | Workers run every queued job anyway | Queued jobs reported as canceled |
| Job ignores ctx | Timeout cannot interrupt it | Still a leak: ctx is cooperative |
Fix / how to use it: Pool.run in the pool. Signal handling around it (signal.NotifyContext, shutdown order) is in OS Processes, Signals & Graceful Shutdown. Note that a context deadline is cooperative: code that never checks ctx cannot be interrupted.
Bounded concurrency with semaphores: chan struct{} and semaphore.Weighted Must-know
In plain words: a semaphore is a box of N tokens; take one before you start, give it back when you finish; when the box is empty you wait. A buffered chan struct{} of capacity N is such a box; semaphore.Weighted lets a job take several tokens at once.
Common misunderstanding: "Acquire inside the goroutine." If you start the goroutine first and acquire inside it, you still create n goroutines — they just wait. Effective Go fixes its own example for this reason: "Serve creates a new goroutine for every incoming request, even though only MaxOutstanding of them can run at any moment." Acquire before go.
Definition: the Go Memory Model: "The kth receive from a channel with capacity C is synchronized before the completion of the k+Cth send on that channel." It "allows a counting semaphore to be modeled by a buffered channel: the number of items in the channel corresponds to the number of active uses, the capacity of the channel corresponds to the maximum number of simultaneous uses, sending an item acquires the semaphore, and receiving an item releases the semaphore." semaphore.NewWeighted(n) provides Acquire(ctx, w) (blocks "until resources are available or ctx is done"; on failure "returns ctx.Err() and leaves the semaphore unchanged"), TryAcquire(w) and Release(w). Waiters are served FIFO: a large request at the head is not overtaken by small ones, to avoid starving it. A request larger than the total size can never succeed and waits until ctx is done.
sem = make(chan struct{}, 2)
1 loop: sem <- {} (1/2) go upload(a)
2 loop: sem <- {} (2/2) go upload(b)
3 loop: sem <- {} blocks: no goroutine for c exists yet
4 upload(a) ends: <-sem (1/2)
5 loop unblocks: go upload(c)
6 after the loop: wg.Wait() for b and cReal scenario: at most 10 concurrent connections to a legacy SOAP service; uploading files to S3 with a 512 MB in-flight memory budget where a 400 MB video takes 400 tokens; limiting concurrent ffmpeg processes to the number of cores; capping concurrent queries to a reporting replica below its max_connections.
| Tool | Weights | ctx-aware | Non-blocking try | Errors | Use when |
|---|---|---|---|---|---|
chan struct{} | 1 each | Only with select | select + default | none | Simple cap, no dependency |
semaphore.Weighted | any int64 | Acquire(ctx, n) | TryAcquire(n) | ctx.Err() | Jobs of different sizes, memory budgets |
errgroup.SetLimit | 1 each | via WithContext | TryGo | first error | Finite batches with errors |
| Worker pool | 1 each | yes | select on Submit | per-job results | Long-lived streams |
Fix / how to use it: bounded: WithChan, WithWeighted (clamps a weight larger than the budget, a real bug otherwise) and WithErrgroup.
errgroup: Go, TryGo, SetLimit, Wait, first error cancels Must-know
In plain words: an errgroup.Group is a WaitGroup that also remembers the first error, cancels a shared context when it happens, and can cap the number of running goroutines.
Common misunderstanding: "After the first error, the other goroutines stop." They stop only if they watch the derived ctx. errgroup cannot kill goroutines; it cancels the context and waits for every function to return. Using the parent ctx instead of the one WithContext returned silently disables cancellation. Another: "SetLimit(0) means unlimited" — the source says "A limit of zero will prevent any new goroutines from being added"; negative means no limit.
Definition: from the x/sync v0.19.0 source. "A Group is a collection of goroutines working on subtasks that are part of the same overall task. A Group should not be reused for different tasks. A zero Group is valid, has no limit on the number of active goroutines, and does not cancel on error." WithContext(ctx) returns a group and a derived ctx that "is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first." Go(f) "blocks until the new goroutine can be added without the number of goroutines in the group exceeding the configured limit." TryGo(f) starts f "only if the number of active goroutines in the group is currently below the configured limit" and reports whether it did. Wait() "blocks until all function calls from the Go method have returned, then returns the first non-nil error (if any) from them." SetLimit(n) must not be changed while goroutines are active; doing so panics with errgroup: modify limit while N goroutines in the group are still active. errgroup does not recover panics: a panicking f crashes the process as any goroutine would.
g, ctx := errgroup.WithContext(parent); g.SetLimit(3)
1 g.Go(fetch A) g.Go(fetch B) g.Go(fetch C) 3 active
2 g.Go(fetch D) blocks (limit 3)
3 B returns err "502 from pricing" -> errOnce stores it; cancel(ctx, err)
4 D starts (slot freed), sees ctx.Done() at once, returns ctx.Err()
5 A, C: HTTP client aborts: "context canceled"; they return
6 g.Wait() returns "502 from pricing" (the first error, not "context canceled")
7 context.Cause(ctx) == the 502 errorReal scenario: a product page that fetches price, stock and reviews in parallel and fails fast if price fails; a migration that copies 3 000 tables with at most 8 in parallel and stops on the first failure; a CLI that uploads a directory with SetLimit(16); an HTTP handler that sheds load with TryGo and returns 503 when all slots are busy.
| Method | Blocks? | Effect on error | Notes |
|---|---|---|---|
Go(f) | When at the limit | First error stored, ctx canceled | Call before Wait; never after Wait returns on a fresh task |
TryGo(f) | Never | Same | false = at the limit; your shedding path |
SetLimit(n) | — | — | n < 0 none; n == 0 nobody; set before Go |
Wait() | Until all return | Returns the first error | Also cancels the derived ctx |
WithContext | — | Derived ctx canceled with cause | context.Cause(ctx) = first error |
zero Group | — | Only remembers the first error | No cancel: good for "collect all" |
Fix / how to use it: after.LoadAll and errgroupx: always shadow ctx with the derived one, pass it into every call, return errors with context (fmt.Errorf("fetch %s: %w", id, err)).
Collecting every error with errors.Join Important
In plain words: sometimes you want every item attempted and a report of all failures — "37 of 5 000 emails failed, here they are" — not the first one only.
Common misunderstanding: "Use errgroup.WithContext and log the rest." First-error-cancels then aborts work you wanted done. Use a group without a context (or a WaitGroup), let each goroutine record its own error, and join them at the end.
Definition: allocate errs := make([]error, n), let goroutine i set errs[i], return errors.Join(errs...) after Wait. errors.Join (Go 1.20) discards nil values, returns nil if all are nil, and its text puts each error on its own line; errors.Is/errors.As look inside every joined error. A mutex-protected slice works too, but per-index slots need no lock and keep the item number.
1 tasks 0..4 run concurrently (zero errgroup.Group, SetLimit(2))
2 task 1 -> errs[1] = "task 1: card declined"
3 task 3 -> errs[3] = "task 3: timeout"
4 others -> nil; every goroutine returns nil to the group (never cancel)
5 Wait(); err := errors.Join(errs...)
6 err.Error() == "task 1: card declined\ntask 3: timeout"; errors.Is(err, errCard) == trueReal scenario: a nightly email campaign; validating every row of an uploaded spreadsheet; health checks of 40 dependencies on a status page; a bulk-delete API that returns per-item results (HTTP 207-style).
| Need | Tool |
|---|---|
| Stop at first failure | errgroup.WithContext |
| Every item attempted, all errors | zero Group or WaitGroup + errs[i] + errors.Join |
| Per-item status in the response | []Result{Index, Err} |
| Count failures only | atomic.Int64 |
Fix / how to use it: errgroupx.CollectAll. More on joined error trees in errors.Join.
Pipelines: stages, done channel, ctx cancellation, closing in order Must-know
In plain words: split the work into steps; each step is a goroutine (or several) that reads from the previous step's channel and writes to its own; when the input ends, the step closes its output so the next step's range ends too.
Common misunderstanding: "If the consumer stops reading, the pipeline cleans itself up." Every upstream goroutine stays blocked on its send forever. The pipelines post calls this "a resource leak" and gives the rule: downstream must be able to tell upstream to stop.
Definition: the guidelines from the Go blog: "stages close their outbound channels when all the send operations are done. stages keep receiving values from inbound channels until those channels are closed or the senders are unblocked." And: "Pipelines unblock senders either by ensuring there's enough buffer for all the values that are sent or by explicitly signalling senders when the receiver may abandon the channel." The signal was a done channel (done := make(chan struct{}); defer close(done)), because "a receive operation on a closed channel can always proceed immediately"; today it is ctx.Done(). Each send becomes select { case out <- v: case <-ctx.Done(): return }. The first stage is the source (producer), the last the sink (consumer). Shutdown happens in order: the source closes first, each stage closes after its input is drained.
source parse enrich sink
1 out <- line1 ─▶ out <- rec1 ─▶ out <- rec1+ ─▶ write rec1+
2 out <- line2 ─▶ out <- rec2 ─▶ enrich fails: sink decides to stop
3 sink: cancel() -> ctx.Done() closes for every stage
4 source: select picks ctx.Done(), returns, close(out)
5 parse: blocked send to enrich -> select picks ctx.Done(), returns, close(out)
6 enrich: returns, close(out)
7 no goroutine left; runtime.NumGoroutine() back to baselineReal scenario: ETL: read a 20 GB CSV, parse, validate, enrich from a cache, batch-insert into PostgreSQL; log processing: tail, parse, filter, ship; image processing: download, decode, resize, encode, upload; a crawler: fetch, extract links, dedupe, enqueue.
| Stage property | Choice | Effect |
|---|---|---|
Who closes out | The stage that sends, via defer close(out) | Downstream range ends cleanly |
| Cancellation | ctx in every send and blocking receive | Early exit without leaks |
| Errors | Error channel, result struct with Err, or errgroup around stages | Fail fast or per-item |
| Output type | Receive-only <-chan T return | Callers cannot close or send |
| Source | iter.Seq[T], slice, file, DB cursor | Any iterator becomes a stage |
Fix / how to use it: pipeline: Source, Map, FanOut, Merge, OrderedMap, each with one send helper that selects on ctx.
Buffered stages and backpressure Important
In plain words: an unbuffered channel makes the fast step wait for the slow step at every item — that waiting is backpressure. A buffer lets the fast step run ahead by up to its capacity, which smooths bursts but does not make the slow step faster.
Common misunderstanding: "Bigger buffers fix slow pipelines." In steady state throughput is set by the slowest stage; a buffer only absorbs short bursts and adds latency and memory. A buffer sized to "never block" is an unbounded queue in disguise and hides overload until memory runs out.
Definition: for a channel of capacity C, a sender blocks when C values are waiting. With C = 0 every send waits for a receiver ("Unbuffered channels combine communication — the exchange of a value — with synchronization", Effective Go). Throughput of a pipeline ≈ min over stages of (workers in stage ÷ time per item). Buffers between stages decouple jitter; fan-out on the slow stage raises its throughput. Backpressure propagates upstream stage by stage until the source blocks — the desired behaviour when the source is a broker (stop fetching) and the wrong one when the source is an HTTP handler that holds a client (then shed instead, with TryGo).
source (1 ms/item) ch cap 0 slow stage (10 ms/item)
1 send v1 ─▶ received at once work v1 (10 ms)
2 send v2: blocks (nobody receiving)
3 ...10 ms... done v1, receive v2
4 source paced at 1 item / 10 ms -> backpressure reached the source
with cap 100: source runs 100 items ahead, then is paced the same wayReal scenario: a Kafka consumer that must stop polling when the database writer falls behind; an upload proxy that must not buffer 10 GB in memory; a metrics agent that drops samples (non-blocking send) rather than block the hot path; a scraper whose parse stage is 10× slower than fetch.
| Choice | Smooths bursts | Memory | Throughput | Overload signal |
|---|---|---|---|---|
| Unbuffered | No | Minimal | Slowest stage | Immediate |
| Small buffer (≈ workers) | Yes | Small | Slowest stage | Short delay |
| Huge buffer | Yes | Large | Slowest stage | Very late (OOM) |
| Fan-out the slow stage | — | +workers | Raised | — |
| Non-blocking send + drop | — | Minimal | Source never waits | Drop counter |
Fix / how to use it: keep buffers small and named (buf parameter in pipeline.Source/Map); measure each stage; fan out the slow one. Test with TestUnbufferedStageAppliesBackpressure. Across services see Backpressure & Flow Control.
Fan-out and fan-in: Merge with a WaitGroup Must-know
In plain words: fan-out is several goroutines reading the same channel (they compete for items); fan-in is one channel collecting the outputs of several and closing when all of them are done.
Common misunderstanding: "Fan-out sends each item to every reader." A channel delivers each value to exactly one receiver. Broadcasting to all readers needs one channel per reader (or closing a channel, which only broadcasts "done"). Another: "close the merged channel when the first input closes" — then values from the others are lost or sent on a closed channel.
Definition: the Go blog: fan-out — "Multiple functions can read from the same channel until that channel is closed... This provides a way to distribute work amongst a group of workers to parallelize CPU use and I/O." Fan-in — "A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that's closed when all the inputs are closed." Merge starts one forwarding goroutine per input, a WaitGroup counts them, and an extra goroutine closes out after wg.Wait(). This is the general answer to multiple senders close: when a channel has several senders, none of them closes it; the coordinator that knows all are finished does.
in ─▶ sq#1 ─┐
in ─▶ sq#2 ─┼─▶ Merge: forwarder#1, #2, #3 ─▶ out
in ─▶ sq#3 ─┘ wg.Add(3)
1 sq#2 input ends -> close(c2) -> forwarder#2 range ends -> wg.Done (2 left)
2 sq#1, sq#3 end -> wg.Done, wg.Done (0 left)
3 closer: wg.Wait() returns -> close(out) -> sink's range endsReal scenario: querying 5 shards in parallel and merging rows; three parser goroutines behind one file reader; scatter-gather to several pricing providers; consuming from three Kafka partitions into one in-process stream.
| Variant | Output order | Close rule |
|---|---|---|
Merge | Interleaved, arrival order | Closer after wg.Wait() |
OrderedMap | Input order (sequence numbers) | Reorder goroutine closes after merge ends |
| First response wins | One value | No close; buffered channel of 1 so losers do not block |
| Per-key routing | Per-key order | One channel per worker, closed by the router |
Fix / how to use it: pipeline.FanOut + pipeline.Merge; for "first answer wins" see the timing-out blog pattern and select.
Distributing work: static split, shared queue, work stealing Important
In plain words: you can deal the cards up front (worker w gets items w, w+N, ...), or put them in a pile everyone draws from. Dealing is cheaper; the pile adapts when some items are much slower.
Common misunderstanding: "Splitting the slice into N equal parts is the fastest." Only when items cost the same. With skew, the worker that drew the expensive items finishes last while the others are idle; total time is the slowest worker's sum.
Definition: static split — partition indices in advance (contiguous ranges or striding); no coordination, best cache locality, sensitive to skew. Shared queue — every worker receives from one channel; dynamic balancing at the cost of one channel operation per item. Work stealing — each worker has its own deque and idle workers steal from others' tails; the Go scheduler itself balances goroutines across Ps this way, so you rarely build it — a shared channel plus the scheduler covers almost every application case.
16 items, 4 workers; items 0,4,8,12 cost 15 ms, the rest 1 ms
static (stride 4): worker 0 = 0,4,8,12 -> 60 ms; workers 1-3 = 4 ms each, then idle
shared queue: worker 0 takes 0 (15 ms); others drain the cheap items and the
other slow ones in parallel -> about 20-25 ms
measured on the host by TestSharedQueueBeatsStaticSplitUnderSkew: static=65-68ms shared=24msReal scenario: thumbnailing a directory where a few files are 50× larger; computing statistics per customer where one customer has 80% of the rows; matrix tiles of uniform size (static wins); crawling where some hosts are slow.
| Strategy | Coordination | Skew tolerance | Locality | Use |
|---|---|---|---|---|
| Static contiguous ranges | None | Poor | Best | Uniform numeric work |
| Static striding | None | Poor | Good | Uniform, interleaved |
| Shared channel | 1 chan op per item | Good | Fair | Default for IO and mixed costs |
| Chunked shared queue | 1 op per chunk | Good | Good | Many tiny items |
| Work stealing (runtime) | Per-P deques | Best | Good | Done for you by the scheduler |
Fix / how to use it: batch.StaticSplit vs batch.SharedQueue; for many tiny items send chunks through the channel to cut per-item overhead.
Batches and iterators: chunk, slices.Chunk, iter.Seq Important
In plain words: many systems prefer 500 rows in one call over 500 calls; split the input into chunks and run a few chunks concurrently. Iterators (iter.Seq) let any data source feed a pipeline without loading everything into memory.
Common misunderstanding: "A chunk is a copy." slices.Chunk yields sub-slices of the original backing array. They are clipped ("All sub-slices are clipped to have no capacity beyond the length"), so append on one allocates instead of overwriting the next chunk, but writing chunk[0] = x modifies the original slice.
Definition: func Chunk[Slice ~[]E, E any](s Slice, n int) iter.Seq[Slice] — "returns an iterator over consecutive sub-slices of up to n elements of s. All but the last sub-slice will have size n... If s is empty, the sequence is empty... Chunk panics if n is less than 1." iter.Seq[V] is func(yield func(V) bool); since Go 1.23 for v := range seq calls it, and yield returns false when the loop body breaks, which is how a source learns to stop. Per-item timeout bounds one element; per-batch timeout bounds one bulk call; an overall deadline bounds the run; combine them as nested contexts — a child deadline is never later than its parent.
rows = 1 050, size = 500, par = 2
1 Chunk yields rows[0:500] -> g.Go(insert, 5 s budget)
2 Chunk yields rows[500:1000]-> g.Go(insert, 5 s budget)
3 Chunk yields rows[1000:1050] -> g.Go blocks (limit 2) until one batch ends
4 batch 2 exceeds 5 s -> "context deadline exceeded" -> group ctx canceled
5 Wait returns "batch at row 500 (500 rows): context deadline exceeded"Real scenario: multi-row INSERT or COPY into PostgreSQL in 1 000-row batches; SQS SendMessageBatch (up to 10 messages per call); Elasticsearch _bulk; sending push notifications in groups of 500; paging through an API with an iter.Seq that fetches the next page lazily.
| Timeout scope | Protects against | Cost |
|---|---|---|
| Per item | One slow element | Needs per-item ctx; many timers |
| Per batch | One stuck bulk call | Fails the whole batch |
| Overall | Endless runs | Last items may never start |
| Item + overall (nested) | Both | Slightly more code |
Fix / how to use it: batch.InChunks and batch.PerItemThenBatch; pipeline.Source takes any iter.Seq, e.g. slices.Values(ids) or a cursor. Range-over-func is covered in Functions and Generics.
Rate limits and retries inside workers: x/time/rate, idempotency Important
In plain words: concurrency (how many at once) and rate (how many per second) are different limits. A pool of 8 can still send 2 000 requests per second if each takes 4 ms. Put a shared token bucket in front of every call, and retry only transient failures, with the same idempotency key each time.
Common misunderstanding: "One limiter per worker." Eight workers with their own 10/s limiters send 80/s. The limiter must be shared. And "retrying is always safe" — retrying a non-idempotent call (charge a card) without an idempotency key can charge twice.
Definition: rate.NewLimiter(r, b) "implements a 'token bucket' of size b, initially full and refilled at rate r tokens per second"; it "is safe for simultaneous use by multiple goroutines". Wait(ctx) "blocks until lim permits n events to happen", returns an error "if n exceeds the Limiter's burst size, the Context is canceled, or the expected wait time exceeds the Context's Deadline" (texts: rate: Wait(n=%d) exceeds limiter's burst %d, rate: Wait(n=%d) would exceed context deadline). Allow() is the non-blocking check, Reserve() returns a delay. A retry loop: spend a token per attempt, classify the error (retry only transient: 429, 503, timeouts), back off exponentially with jitter, respect ctx, cap attempts, reuse the job's idempotency key.
worker 3, charge idem-07
1 lim.Wait(ctx) -> token
2 POST /charges Idempotency-Key: idem-07 -> 503
3 sleep 1 ms * 2^0 with jitter
4 lim.Wait(ctx) -> token
5 POST /charges Idempotency-Key: idem-07 -> 503
6 sleep 2 ms with jitter; lim.Wait; POST ... idem-07 -> 201
partner saw 3 requests with one key -> one chargeReal scenario: a partner API with a 100 requests/second quota; sending SMS through a provider that bans you for bursts; Stripe-style idempotency keys on payment retries; GitHub API secondary rate limits that answer 403/429.
| Problem | Tool | Note |
|---|---|---|
| Too many at once | Pool / semaphore / SetLimit | Concurrency cap |
| Too many per second | Shared rate.Limiter, Wait(ctx) | Rate cap |
| Transient failure | Retry with capped exponential backoff + jitter | Only idempotent ops |
| Duplicate side effects on retry | Idempotency key per job | Partner or inbox deduplicates |
| Many processes share a quota | Distributed limiter (Redis) | See system-design page |
Fix / how to use it: ratelimited.Run. Algorithms and HTTP middleware: Rate Limiting in Go and Rate Limiting; backoff and jitter: Retry, Backoff & Delayed Delivery; keys: API Idempotency.
Pool sizing: NumCPU, GOMAXPROCS, CPU-bound vs IO-bound Must-know
In plain words: CPU-bound work cannot go faster than the number of cores Go may use, so start with that many workers. IO-bound work mostly waits, so more workers help — until the thing you wait on (database, API, disk) is saturated. Then measure.
Common misunderstanding: "runtime.NumCPU() is the right number in a container." NumCPU "returns the number of logical CPUs usable by the current process" — on a 64-core node with a 2-CPU limit that is still 64 (or the affinity mask). Since Go 1.25, the default GOMAXPROCS considers the cgroup CPU limit, but go doc runtime.GOMAXPROCS notes "GODEBUG=containermaxprocs=0 is default for language version 1.24 and below" — a module with go 1.24 in go.mod keeps the old default. Use runtime.GOMAXPROCS(0) (which reads without changing) for CPU-bound pools.
Definition: for CPU-bound work, workers ≈ GOMAXPROCS(0); more only adds scheduling. For IO-bound work, Little's law gives a starting point: concurrency ≈ throughput × latency (200 requests/s × 50 ms = 10 in flight). Then cap by the downstream's limits: database max_connections and sql.DB.SetMaxOpenConns, the partner's quota, file descriptor limits. Validate with a benchmark or load test and watch latency percentiles, not just throughput.
IO-bound: target 400 req/s, p50 latency 25 ms
1 Little: 400 * 0.025 = 10 in flight -> start with 10-16 workers
2 measure: 16 workers -> 610 req/s, p99 40 ms
3 32 workers -> 640 req/s, p99 180 ms (downstream saturated)
4 choose 16: past the knee, latency grows, throughput does notReal scenario: an image resizer on a 4-CPU pod with GOMAXPROCS 4; a crawler with 200 workers bounded by per-host limits; a database exporter whose 50 workers exhausted a pool of 20 connections, so 30 just waited inside database/sql; a pod throttled by CFS quota because a Go 1.24 module used 32 workers on a 2-CPU limit.
| Workload | Start with | Bounded by | Watch |
|---|---|---|---|
| CPU-bound (hashing, image, JSON) | runtime.GOMAXPROCS(0) | Cores | CPU usage, throttling |
| IO-bound HTTP calls | Little's law estimate | Partner quota, connections | p99 latency, 429s |
| Database writes | ≤ SetMaxOpenConns | DB connections, locks | Wait count, lock waits |
| Mixed pipeline | Per stage | Slowest stage | Queue depth per stage |
| Memory-heavy jobs | Memory budget / job size | RAM | RSS, GC pauses |
Fix / how to use it: make the worker count a config value, default it from runtime.GOMAXPROCS(0) for CPU work, benchmark with go test -bench (see Testing & Benchmarking), and connection-pool math in Connection Pooling.
Goroutine per request vs a pool Important
In plain words: net/http already runs each request in its own goroutine, and that is fine because the number of requests is bounded by connections. What needs a bound is the work a request fans out to, and background work that arrives faster than it is processed.
Common misunderstanding: "Go servers need a worker pool for requests." The standard server's goroutine-per-connection model is the intended design; replacing it with a pool adds a queue and head-of-line blocking. Bound the expensive resource instead (a semaphore around the PDF renderer, a DB pool), and shed load early (TryGo → 503).
Definition: goroutine per request: cheap, simple, unbounded unless the listener or a middleware limits it. Pool: fixed cost, bounded, adds queueing delay. The hybrid most services use: goroutine per request + a process-wide semaphore or pool around the scarce resource + per-request errgroup for its fan-out.
1 1 000 requests/s, each needs a 200 ms PDF render (CPU-bound, 4 cores)
2 per request, unbounded: 200 renders at once, each 50x slower, timeouts everywhere
3 semaphore(4) around render: 4 run, others wait up to their ctx deadline
4 TryAcquire fails and queue > 2 s -> 503 Retry-After: the client backs offReal scenario: an HTML-to-PDF endpoint; an API that calls three microservices per request (errgroup per request); a webhook receiver that must answer in 200 ms (enqueue, process in a background pool); a file-upload handler limited by memory.
| Model | Bound | Latency under overload | Use |
|---|---|---|---|
| Goroutine per request | Connections | Degrades for everyone | Default for handlers |
| + semaphore on the scarce resource | N for that resource | Wait or shed at the semaphore | CPU-heavy or connection-limited calls |
| + background pool | Workers + queue | Request returns fast; work later | Webhooks, emails, thumbnails |
| Pool instead of per-request | N | Queueing at the door | Rarely right in Go |
Fix / how to use it: errgroupx.Shedder for TryGo load shedding; Load Shedding for the system view.
Leaks and observability: goroutine leak, queue depth, in-flight, latency histogram Must-know
In plain words: a leaked goroutine is one that can never finish. You find leaks with tests that compare goroutine counts and with the goroutineleak profile; you find overload by exporting three numbers from every pool: queue depth, in-flight, and a latency histogram.
Common misunderstanding: "If memory is fine, there is no leak." Leaks grow slowly — 100 goroutines per failed batch is invisible for days. And "average latency is enough": averages hide the slow tail that a histogram shows.
Definition: Go Code Review Comments: "Goroutines can leak by blocking on channel sends or receives: the garbage collector will not terminate a goroutine even if the channels it is blocked on are unreachable." Go 1.27: "A leaked goroutine is a goroutine blocked on some concurrency primitive (channels, sync.Mutex, sync.Cond, etc) that cannot possibly become unblocked"; the goroutineleak profile (runtime/pprof, endpoint /debug/pprof/goroutineleak) finds them through GC reachability. Queue depth = len(jobs); in-flight = an atomic counter around each job; latency histogram = cumulative buckets (le="0.01", le="0.1"...) per job, plus counters for completed, failed, panicked, timed-out. Little's law ties them: in-flight ≈ throughput × latency.
dashboard during an incident
1 queue_depth: 0 -> 950 (cap 1000) in 2 min -> workers cannot keep up
2 in_flight: 16/16 constant -> pool saturated
3 job_seconds p99: 0.08 s -> 4.1 s -> downstream slow, not us
4 action: shed new work (Submit with short ctx -> 503), not more workersReal scenario: a leak that added 100 goroutines per failed batch (lab step 4); a queue that silently grew because a downstream got slower; a histogram showing that 1% of jobs hit the 30 s timeout; runtime.NumGoroutine() exported as a gauge revealing a slow climb after each deploy.
| Signal | How | Meaning when high |
|---|---|---|
| Queue depth | len(jobs) gauge | Arrival rate > service rate |
| In-flight | atomic counter | At limit = saturated |
| Latency histogram | buckets per job | Tail latency, timeouts |
go_goroutines | runtime.NumGoroutine() | Steady climb = leak |
goroutineleak profile | pprof, Go 1.27 | Exact leaked stacks |
| Errors by kind | counters: timeout, panic, failed | Retry storms, bugs |
Fix / how to use it: workerpool.Pool exposes QueueDepth, InFlight, Latency; the tests call noLeak after cancellation. Wire them to Prometheus or OpenTelemetry as in Observability: Logs, Metrics, Traces. For tests with fake time, testing/synctest (Go 1.25) runs a test in a "bubble" where the clock advances when every goroutine is blocked.
Libraries: conc and friends Good to know
In plain words: github.com/sourcegraph/conc packages the patterns on this page with panic handling built in; you can use it, but you should understand the stdlib versions first.
Common misunderstanding: "A library removes the need to think about ownership." It enforces one owner per goroutine, but you still choose limits, ordering and error policy.
Definition: from its README: goals "Make it harder to leak goroutines" and "Handle panics gracefully"; "In conc, the owner of a goroutine is always a conc.WaitGroup". conc.WaitGroup is "a safer version of sync.WaitGroup" (it catches panics and re-panics in Wait), pool.New() with p.WithMaxGoroutines() "configures the maximum number of goroutines in the pool", pool.NewWithResults[T]() collects results, and stream.Stream processes "an ordered stream of tasks in parallel with serial callbacks". This is the opposite choice from errgroup, which deliberately does not propagate panics.
1 p := pool.New().WithMaxGoroutines(8).WithErrors()
2 for _, id := range ids { p.Go(func() error { return fetch(id) }) }
3 err := p.Wait() // all errors combined; a panic in fetch re-panics hereReal scenario: a team that wants panics surfaced at the spawner; an ordered stream of callbacks without writing a reorder buffer.
| Need | stdlib / x/sync | conc |
|---|---|---|
| Wait for goroutines | sync.WaitGroup | conc.WaitGroup (catches panics) |
| Limit + errors | errgroup.SetLimit | pool.New().WithMaxGoroutines(n).WithErrors() |
| Ordered parallel stream | reorder buffer | stream.Stream |
| Panic propagation | none (crash) | re-panic in Wait |
Fix / how to use it: prefer stdlib + x/sync for library code (fewer dependencies); conc is reasonable in applications. Not used in this page's snippets.
Go
Before
One goroutine per id, no limit, no cancellation after the first error, results in completion order. It compiles and its happy-path test passes.
// Package before loads many products concurrently the naive way: one
// goroutine per id, no limit, no cancellation, results in arrival order.
// It compiles and its happy-path test passes; the design is what is wrong.
package before
import (
"context"
"fmt"
)
// Product is what the catalogue service returns for one id.
type Product struct {
ID string
Price int
}
// Fetcher talks to a slow dependency (HTTP API, database, object store).
type Fetcher interface {
Fetch(ctx context.Context, id string) (Product, error)
}
type result struct {
p Product
err error
}
// LoadAll starts len(ids) goroutines at once. With 50 000 ids it opens
// 50 000 connections to the dependency, ignores ctx after the first error
// (the other fetches keep running), and returns products in completion order,
// not in the order of ids.
func LoadAll(ctx context.Context, f Fetcher, ids []string) ([]Product, error) {
ch := make(chan result, len(ids)) // buffered: nobody leaks, but memory is O(n)
for _, id := range ids {
go func() {
p, err := f.Fetch(ctx, id)
ch <- result{p, err}
}()
}
out := make([]Product, 0, len(ids))
for range ids {
r := <-ch
if r.err != nil {
return nil, fmt.Errorf("load products: %w", r.err) // others still run
}
out = append(out, r.p)
}
return out, nil
}After
The same API with errgroup.WithContext, SetLimit, the derived ctx passed into every fetch, and out[i] so the output order equals the input order. The test proves the cap (peak ≤ 4), the order, and that the first error is returned and cancels the rest.
// Package after loads many products with bounded concurrency: errgroup with
// SetLimit, a derived context that is canceled on the first error, and
// results written by index so the output order equals the input order.
package after
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
)
// Product is what the catalogue service returns for one id.
type Product struct {
ID string
Price int
}
// Fetcher talks to a slow dependency (HTTP API, database, object store).
type Fetcher interface {
Fetch(ctx context.Context, id string) (Product, error)
}
// LoadAll runs at most limit fetches at a time. The first error cancels ctx
// for every other fetch, Wait returns that error, and out[i] belongs to ids[i].
func LoadAll(ctx context.Context, f Fetcher, ids []string, limit int) ([]Product, error) {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(limit) // Go blocks while limit goroutines are active
out := make([]Product, len(ids))
for i, id := range ids {
g.Go(func() error {
p, err := f.Fetch(ctx, id)
if err != nil {
return fmt.Errorf("fetch %s: %w", id, err)
}
out[i] = p // each goroutine owns one index: no mutex, no race
return nil
})
}
if err := g.Wait(); err != nil {
return nil, fmt.Errorf("load products: %w", err)
}
return out, nil
}package after
import (
"context"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
)
type fakeFetcher struct {
inFlight, peak atomic.Int64
failOn string
canceled atomic.Int64
}
var errBoom = errors.New("boom")
func (f *fakeFetcher) Fetch(ctx context.Context, id string) (Product, error) {
n := f.inFlight.Add(1)
defer f.inFlight.Add(-1)
for {
p := f.peak.Load()
if n <= p || f.peak.CompareAndSwap(p, n) {
break
}
}
if id == f.failOn {
return Product{}, errBoom
}
select {
case <-time.After(2 * time.Millisecond):
return Product{ID: id, Price: len(id)}, nil
case <-ctx.Done():
f.canceled.Add(1)
return Product{}, ctx.Err()
}
}
func ids(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = fmt.Sprintf("p-%03d", i)
}
return out
}
func TestLoadAllKeepsOrderAndLimit(t *testing.T) {
f := &fakeFetcher{}
in := ids(40)
got, err := LoadAll(context.Background(), f, in, 4)
if err != nil {
t.Fatal(err)
}
for i, p := range got {
if p.ID != in[i] {
t.Fatalf("out[%d] = %s, want %s", i, p.ID, in[i])
}
}
if peak := f.peak.Load(); peak > 4 {
t.Fatalf("peak concurrency %d > limit 4", peak)
}
}
func TestFirstErrorCancelsTheRest(t *testing.T) {
f := &fakeFetcher{failOn: "p-002"}
_, err := LoadAll(context.Background(), f, ids(40), 4)
if !errors.Is(err, errBoom) {
t.Fatalf("err = %v, want errBoom in the chain", err)
}
if f.inFlight.Load() != 0 {
t.Fatal("Wait returned while fetches were still running")
}
}The Go angle
The standard library and x/ modules give you primitives, not a pool type, on purpose: the shape depends on lifetime and error policy. net/http's server starts a goroutine per connection and recovers handler panics; database/sql is itself a bounded pool (SetMaxOpenConns, SetMaxIdleConns), so a worker pool in front of it should not be larger than it; golang.org/x/sync/errgroup and semaphore are maintained by the Go team; golang.org/x/time/rate is the token bucket the ecosystem standardises on; golang.org/x/sync/singleflight deduplicates concurrent calls for the same key (cache stampedes). The runtime's scheduler multiplexes goroutines on GOMAXPROCS threads with work stealing, so you never need to pin workers to threads. And the race detector (go test -race) is the check every snippet here passes.
Mechanics
Runtime, vet and race messages, verbatim Must-know
All of these were produced on the host by the lab program and test files (Go 1.27.4, darwin/arm64, built with -trimpath).
| Message | Cause in a pool or pipeline | Exit |
|---|---|---|
fatal error: all goroutines are asleep - deadlock! | Send on an unbuffered results channel nobody reads, or Wait before anyone can finish | 2, not recoverable |
panic: close of closed channel | Two workers close the same channel | 2 |
panic: send on closed channel | Producer or worker sends after close | 2 |
panic: close of nil channel | Closing a channel that was never maked | 2 |
WARNING: DATA RACE … Found 4 data race(s) | Workers append to one slice | 66 under -race |
WaitGroup.Add called from inside new goroutine | vet waitgroup (1.25; waitgroupgo in 1.27) | vet fails |
call of worker copies lock value: sync.Mutex | Passing a Mutex/WaitGroup by value to a worker | vet fails |
context deadline exceeded | Per-job or per-batch timeout fired | error value |
context canceled | First error canceled the group, or shutdown | error value |
errgroup: modify limit while 3 goroutines in the group are still active | SetLimit during work | panic |
rate: Wait(n=5) exceeds limiter's burst 1 | WaitN larger than the burst | error value |
semaphore: released more than held | Release without matching Acquire | panic |
assignment to entry in nil map | Typical job panic caught by the per-job recover | *PanicError |
The spec states the channel rules behind three of them: "A send on a closed channel proceeds by causing a run-time panic", "Sending to or closing a closed channel causes a run-time panic. Closing the nil channel also causes a run-time panic." A receive from a closed channel never blocks; it yields the zero value, and v, ok := <-ch reports ok == false.
Happens-before: why out[i] needs no mutex
The Go Memory Model gives every pattern here its correctness. "A send on a channel is synchronized before the completion of the corresponding receive from that channel", so a result struct sent by a worker is fully visible to the collector. "The closing of a channel is synchronized before a receive that returns a zero value because the channel is closed", so a range that ends sees every earlier send. For WaitGroup.Go the docs say "the return from f 'synchronizes before' the return of any Wait call that it unblocks", and the same holds for Done/Wait: writes to out[i] before Done are visible after Wait. Two goroutines writing different slice elements do not race; two goroutines calling append on the same slice do, because append reads and writes the shared slice header.
How errgroup is built
The v0.19.0 Group is a sync.WaitGroup, a chan token semaphore (nil when there is no limit), a sync.Once for the first error, and the cancel func(error) from context.WithCancelCause. Go sends into sem (blocking at the limit), wg.Add(1), starts the goroutine, and in defer receives from sem and calls wg.Done(). On a non-nil error errOnce stores it and calls cancel(err). TryGo does the same but uses select { case sem <- token{}: default: return false }. Wait calls wg.Wait(), then cancel(g.err), then returns g.err. That is why the derived ctx is always canceled after Wait — do not keep using it afterwards.
How semaphore.Weighted orders waiters
Weighted holds size, cur and a FIFO list.List of waiters, each with a ready channel. Acquire succeeds at once if size-cur >= n and nobody is waiting; otherwise it queues and waits on ready or ctx.Done(). Release walks the queue from the front and wakes waiters while they fit; it stops at the first one that does not fit, even if a smaller one behind it would — the source explains this prevents a writer that needs all N tokens from starving behind endless readers. If a canceled waiter had already been granted tokens, it gives them back.
Shutdown order and closing rules
rule who why
1 close(jobs) the single producer only the sender knows there is no more input
2 workers: for range jobs ends each worker queue drained (graceful drain)
3 wg.Done() in defer each worker runs even if the job panicked
4 wg.Wait(); close(results) closer goroutine the only one that knows all senders finished
5 for range results ends consumer every result received
6 cancel() owner, via defer releases timers and ctx resourcesNever close a channel from the receiving side, never close a channel with several senders from one of them, and never use recover to hide a send on a closed channel: those are design errors.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| 50 000 concurrent calls | Bounded concurrency | errgroup.SetLimit, semaphore | Downstream sees ≤ N | Pick N |
| Long-lived stream of jobs | Worker pool | jobs/results channels + closer | Steady resource use | Ownership rules |
| Output must match input order | Index or reorder buffer | out[i], sequence numbers | Deterministic output | Memory or head-of-line blocking |
| One job panics | Per-job recover | defer recover in run | Process survives | Must still fix the bug |
| One job hangs | Per-job timeout | context.WithTimeout per job | Worker freed | Only cooperative code stops |
| Shutdown loses work | Graceful drain | Close jobs, drain, close results | Nothing lost | Needs a grace period |
| Stop on first error | errgroup + derived ctx | WithContext | Fast failure | Partial work wasted |
| Report all errors | Per-index errors + errors.Join | zero Group | Complete report | No early stop |
| Different job sizes | semaphore.Weighted | weight = MB, rows | Budget respected | FIFO can idle tokens |
| Overload at the door | Load shedding | TryGo → ErrBusy → 503 | Latency protected | Clients must retry |
| Multistep processing | Pipeline + fan-out | Source/Map/Merge | Each stage tuned | More goroutines to own |
| Early consumer exit leaks | ctx in every send | send helper | No leaks | One select per send |
| Skewed item costs | Shared queue | one channel | Balanced | Channel op per item |
| Partner quota | Shared token bucket | rate.Limiter.Wait | Never over quota | Adds waiting |
| Transient failures | Retry + backoff + idempotency key | withRetry | Fewer failures, no duplicates | Longer tail |
A production worker pool
Generic Pool[T, R] with Add(N) before start, closer goroutine, Submit that blocks for backpressure and honours ctx, per-job timeout and recover, CollectOrdered, and gauges. The tests check order, panic recovery, timeout, drain, cancellation without leaks, and queue depth/in-flight under backpressure.
// Package workerpool is a fixed-size worker pool: N goroutines read a jobs
// channel and write a results channel. It shows the pieces a production pool
// needs: a WaitGroup that closes results, a timeout per job, panic recovery
// per job, graceful drain on Close, and the three gauges worth exporting
// (queue depth, in-flight, latency histogram).
package workerpool
import (
"context"
"fmt"
"runtime/debug"
"sync"
"sync/atomic"
"time"
)
// Job carries its input position so results can be put back in order.
type Job[T any] struct {
Index int
Payload T
}
// Result is one finished job. Err is non-nil for failures, timeouts,
// cancellation and recovered panics (*PanicError).
type Result[R any] struct {
Index int
Value R
Err error
Took time.Duration
}
// PanicError is what a panicking job becomes: the worker survives, the
// stack is kept for the log.
type PanicError struct {
Value any
Stack []byte
}
func (e *PanicError) Error() string { return fmt.Sprintf("job panicked: %v", e.Value) }
// Config sizes the pool. QueueSize 0 means an unbuffered jobs channel:
// Submit then blocks until a worker is free (maximum backpressure).
type Config struct {
Workers int
QueueSize int
JobTimeout time.Duration // 0 = no per-job timeout
}
// Pool runs fn for every submitted job on Config.Workers goroutines.
//
// Ownership rule: exactly one goroutine (the producer) calls Submit and Close.
// The consumer must read Results until it is closed, or workers block.
type Pool[T, R any] struct {
cfg Config
fn func(context.Context, T) (R, error)
jobs chan Job[T]
results chan Result[R]
wg sync.WaitGroup
inFlight atomic.Int64
Latency *Histogram
}
// New starts the workers. ctx is the pool's lifetime: when it is canceled,
// queued jobs are reported with ctx.Err() instead of being run.
func New[T, R any](ctx context.Context, cfg Config, fn func(context.Context, T) (R, error)) *Pool[T, R] {
if cfg.Workers < 1 {
cfg.Workers = 1
}
p := &Pool[T, R]{
cfg: cfg,
fn: fn,
jobs: make(chan Job[T], cfg.QueueSize),
results: make(chan Result[R], cfg.Workers),
Latency: NewHistogram(time.Millisecond, 10*time.Millisecond, 100*time.Millisecond, time.Second),
}
p.wg.Add(cfg.Workers) // Add before the goroutines start, never inside them
for range cfg.Workers {
go p.worker(ctx)
}
go func() {
p.wg.Wait() // every worker has returned...
close(p.results) // ...so nobody can send any more: safe to close
}()
return p
}
// Submit enqueues a job. It blocks while the queue is full (backpressure) and
// returns ctx.Err() if the producer gives up first.
func (p *Pool[T, R]) Submit(ctx context.Context, j Job[T]) error {
select {
case p.jobs <- j:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Close stops accepting jobs. Workers finish everything already queued
// (graceful drain), then Results is closed.
func (p *Pool[T, R]) Close() { close(p.jobs) }
// Results is closed after Close once every queued job has a result.
func (p *Pool[T, R]) Results() <-chan Result[R] { return p.results }
// QueueDepth is the number of jobs waiting for a worker.
func (p *Pool[T, R]) QueueDepth() int { return len(p.jobs) }
// InFlight is the number of jobs a worker is executing right now.
func (p *Pool[T, R]) InFlight() int64 { return p.inFlight.Load() }
func (p *Pool[T, R]) worker(ctx context.Context) {
defer p.wg.Done()
for j := range p.jobs { // ends when Close closes jobs and the queue is empty
p.results <- p.run(ctx, j)
}
}
func (p *Pool[T, R]) run(ctx context.Context, j Job[T]) (res Result[R]) {
start := time.Now()
p.inFlight.Add(1)
defer func() {
if v := recover(); v != nil { // one bad job must not kill the process
res.Err = &PanicError{Value: v, Stack: debug.Stack()}
}
res.Index = j.Index
res.Took = time.Since(start)
p.inFlight.Add(-1)
p.Latency.Observe(res.Took)
}()
if err := ctx.Err(); err != nil { // pool canceled: report, do not run
return Result[R]{Err: err}
}
if p.cfg.JobTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, p.cfg.JobTimeout)
defer cancel()
}
v, err := p.fn(ctx, j.Payload)
return Result[R]{Value: v, Err: err}
}
// CollectOrdered reads results until the channel closes and returns them
// indexed by Job.Index, so out[i] is the result of the i-th submitted job.
func CollectOrdered[R any](results <-chan Result[R], n int) []Result[R] {
out := make([]Result[R], n)
for r := range results {
out[r.Index] = r
}
return out
}package workerpool
import (
"sync/atomic"
"time"
)
// Histogram is a minimal cumulative latency histogram with fixed upper
// bounds, the same shape Prometheus exports as _bucket{le="..."}.
type Histogram struct {
bounds []time.Duration
counts []atomic.Int64 // counts[i] = observations <= bounds[i]; last = +Inf
}
// NewHistogram creates buckets for the given ascending upper bounds.
func NewHistogram(bounds ...time.Duration) *Histogram {
return &Histogram{bounds: bounds, counts: make([]atomic.Int64, len(bounds)+1)}
}
// Observe records one duration.
func (h *Histogram) Observe(d time.Duration) {
for i, b := range h.bounds {
if d <= b {
h.counts[i].Add(1)
}
}
h.counts[len(h.bounds)].Add(1) // +Inf bucket counts everything
}
// Count returns the cumulative count for bucket i (len(bounds) = +Inf).
func (h *Histogram) Count(i int) int64 { return h.counts[i].Load() }package workerpool
import (
"context"
"errors"
"runtime"
"sync/atomic"
"testing"
"time"
)
func square(_ context.Context, n int) (int, error) { return n * n, nil }
func TestResultsInInputOrder(t *testing.T) {
p := New(context.Background(), Config{Workers: 4, QueueSize: 8}, square)
go func() {
for i := range 100 {
_ = p.Submit(context.Background(), Job[int]{Index: i, Payload: i})
}
p.Close()
}()
got := CollectOrdered(p.Results(), 100)
for i, r := range got {
if r.Err != nil || r.Value != i*i {
t.Fatalf("out[%d] = %+v", i, r)
}
}
}
func TestPanicIsRecoveredPerJob(t *testing.T) {
fn := func(_ context.Context, n int) (int, error) {
if n == 3 {
var m map[string]int
m["boom"] = 1 // assignment to entry in nil map
}
return n, nil
}
p := New(context.Background(), Config{Workers: 2}, fn)
go func() {
for i := range 6 {
_ = p.Submit(context.Background(), Job[int]{Index: i, Payload: i})
}
p.Close()
}()
got := CollectOrdered(p.Results(), 6)
var pe *PanicError
if !errors.As(got[3].Err, &pe) {
t.Fatalf("job 3 err = %v, want *PanicError", got[3].Err)
}
if got[5].Err != nil || got[5].Value != 5 {
t.Fatalf("worker died after the panic: %+v", got[5])
}
}
func TestPerJobTimeout(t *testing.T) {
slow := func(ctx context.Context, n int) (int, error) {
select {
case <-time.After(time.Duration(n) * 20 * time.Millisecond):
return n, nil
case <-ctx.Done():
return 0, ctx.Err()
}
}
p := New(context.Background(), Config{Workers: 2, JobTimeout: 30 * time.Millisecond}, slow)
go func() {
_ = p.Submit(context.Background(), Job[int]{Index: 0, Payload: 1}) // 20ms: ok
_ = p.Submit(context.Background(), Job[int]{Index: 1, Payload: 5}) // 100ms: timeout
p.Close()
}()
got := CollectOrdered(p.Results(), 2)
if got[0].Err != nil {
t.Fatalf("fast job: %v", got[0].Err)
}
if !errors.Is(got[1].Err, context.DeadlineExceeded) {
t.Fatalf("slow job err = %v, want context deadline exceeded", got[1].Err)
}
}
func TestGracefulDrainRunsEveryQueuedJob(t *testing.T) {
var ran atomic.Int64
fn := func(_ context.Context, n int) (int, error) {
time.Sleep(time.Millisecond)
ran.Add(1)
return n, nil
}
p := New(context.Background(), Config{Workers: 3, QueueSize: 50}, fn)
for i := range 50 {
if err := p.Submit(context.Background(), Job[int]{Index: i, Payload: i}); err != nil {
t.Fatal(err)
}
}
p.Close() // no new jobs; the 50 queued ones must still run
n := 0
for range p.Results() {
n++
}
if n != 50 || ran.Load() != 50 {
t.Fatalf("results=%d ran=%d, want 50/50", n, ran.Load())
}
if p.Latency.Count(4) != 50 {
t.Fatalf("histogram +Inf = %d, want 50", p.Latency.Count(4))
}
}
func TestCanceledPoolSkipsQueuedJobsAndExits(t *testing.T) {
before := runtime.NumGoroutine()
ctx, cancel := context.WithCancel(context.Background())
var ran atomic.Int64
fn := func(_ context.Context, n int) (int, error) { ran.Add(1); return n, nil }
p := New(ctx, Config{Workers: 2, QueueSize: 10}, fn)
cancel() // shut down before any job runs
for i := range 10 {
_ = p.Submit(context.Background(), Job[int]{Index: i, Payload: i})
}
p.Close()
for r := range p.Results() {
if !errors.Is(r.Err, context.Canceled) && r.Err != nil {
t.Fatalf("unexpected err %v", r.Err)
}
}
// All workers and the closer goroutine have exited: no goroutine leak.
deadline := time.Now().Add(time.Second)
for runtime.NumGoroutine() > before && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if g := runtime.NumGoroutine(); g > before {
t.Fatalf("goroutines: before=%d after=%d", before, g)
}
}
func TestBackpressureQueueDepth(t *testing.T) {
release := make(chan struct{})
fn := func(_ context.Context, n int) (int, error) { <-release; return n, nil }
p := New(context.Background(), Config{Workers: 1, QueueSize: 2}, fn)
for i := range 3 { // 1 in flight + 2 queued
_ = p.Submit(context.Background(), Job[int]{Index: i, Payload: i})
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if err := p.Submit(ctx, Job[int]{Index: 3}); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("4th Submit err = %v, want it to block until the deadline", err)
}
if p.QueueDepth() != 2 || p.InFlight() != 1 {
t.Fatalf("depth=%d inflight=%d, want 2/1", p.QueueDepth(), p.InFlight())
}
close(release)
p.Close()
for range p.Results() {
}
}Three semaphores
// Package bounded shows three ways to cap how many operations run at once
// without a long-lived pool: a buffered chan struct{} as a counting
// semaphore, semaphore.Weighted for jobs of different sizes, and
// errgroup.SetLimit when you also want first-error cancellation.
package bounded
import (
"context"
"sync"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
// WithChan runs fn for every item, at most limit at a time. Acquire happens
// in the loop, BEFORE the goroutine starts, so at most limit goroutines exist.
func WithChan(items []int, limit int, fn func(int)) {
sem := make(chan struct{}, limit)
var wg sync.WaitGroup
for _, it := range items {
sem <- struct{}{} // acquire: blocks while limit goroutines hold a slot
wg.Add(1)
go func() {
defer wg.Done()
defer func() { <-sem }() // release
fn(it)
}()
}
wg.Wait()
}
// Upload is a file with a size; big files take more of the budget.
type Upload struct {
Name string
MB int64
}
// WithWeighted keeps the total MB being uploaded at once under budgetMB.
// Acquire respects ctx: a canceled caller stops waiting and gets ctx.Err().
func WithWeighted(ctx context.Context, files []Upload, budgetMB int64, fn func(Upload)) error {
sem := semaphore.NewWeighted(budgetMB)
var wg sync.WaitGroup
for _, f := range files {
w := min(f.MB, budgetMB) // a file larger than the budget would wait forever
if err := sem.Acquire(ctx, w); err != nil {
wg.Wait()
return err
}
wg.Add(1)
go func() {
defer wg.Done()
defer sem.Release(w)
fn(f)
}()
}
wg.Wait()
return nil
}
// WithErrgroup is the same cap as WithChan plus error propagation: the first
// error cancels ctx and is returned by Wait.
func WithErrgroup(ctx context.Context, items []int, limit int, fn func(context.Context, int) error) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(limit)
for _, it := range items {
if ctx.Err() != nil {
break // stop scheduling new work once something failed
}
g.Go(func() error { return fn(ctx, it) })
}
return g.Wait()
}package bounded
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
)
// gauge tracks the current and maximum number of concurrent calls.
type gauge struct{ cur, peak atomic.Int64 }
func (g *gauge) enter(n int64) {
c := g.cur.Add(n)
for {
p := g.peak.Load()
if c <= p || g.peak.CompareAndSwap(p, c) {
return
}
}
}
func (g *gauge) leave(n int64) { g.cur.Add(-n) }
func seq(n int) []int {
s := make([]int, n)
for i := range s {
s[i] = i
}
return s
}
func TestWithChanNeverExceedsLimit(t *testing.T) {
var g gauge
WithChan(seq(64), 5, func(int) {
g.enter(1)
defer g.leave(1)
time.Sleep(time.Millisecond)
})
if p := g.peak.Load(); p > 5 || p < 2 {
t.Fatalf("peak = %d, want 2..5", p)
}
}
func TestWithWeightedRespectsBudget(t *testing.T) {
var g gauge
files := []Upload{{"a", 60}, {"b", 30}, {"c", 50}, {"d", 10}, {"e", 90}, {"f", 400}}
err := WithWeighted(context.Background(), files, 100, func(u Upload) {
w := min(u.MB, 100)
g.enter(w)
defer g.leave(w)
time.Sleep(2 * time.Millisecond)
})
if err != nil {
t.Fatal(err)
}
if p := g.peak.Load(); p > 100 {
t.Fatalf("peak MB in flight = %d > 100", p)
}
}
func TestWithWeightedCanceled(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
files := []Upload{{"big", 100}, {"next", 1}}
err := WithWeighted(ctx, files, 100, func(u Upload) {
if u.Name == "big" {
time.Sleep(50 * time.Millisecond) // holds the whole budget past the deadline
}
})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want context deadline exceeded", err)
}
}
func TestWithErrgroupFirstErrorStopsScheduling(t *testing.T) {
var started atomic.Int64
boom := errors.New("boom")
err := WithErrgroup(context.Background(), seq(1000), 4, func(ctx context.Context, i int) error {
started.Add(1)
if i == 10 {
return boom
}
select {
case <-time.After(time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
})
if !errors.Is(err, boom) {
t.Fatalf("err = %v, want boom (the FIRST error, not context canceled)", err)
}
if s := started.Load(); s >= 1000 {
t.Fatalf("started %d of 1000 items after the failure", s)
}
}errgroup: fail fast, collect all, shed load
// Package errgroupx shows the three ways to use errgroup: fail fast (first
// error cancels the rest), collect every error with errors.Join, and TryGo
// to shed work when the group is at its limit.
package errgroupx
import (
"context"
"errors"
"fmt"
"golang.org/x/sync/errgroup"
)
// Task is one unit of work.
type Task func(ctx context.Context) error
// FailFast runs every task; the first non-nil error cancels ctx for the
// others and is the only error returned. context.Cause(ctx) inside a task
// tells it why it was canceled. limit < 0 means no limit; limit 0 makes
// every Go call block forever (SetLimit(0) admits no goroutine).
func FailFast(ctx context.Context, limit int, tasks ...Task) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(limit)
for _, t := range tasks {
g.Go(func() error { return t(ctx) })
}
return g.Wait()
}
// CollectAll runs every task to completion and returns all failures joined.
// No WithContext: one failure must not cancel the others. Each goroutine
// writes only its own slot, so no mutex is needed.
func CollectAll(ctx context.Context, limit int, tasks ...Task) error {
var g errgroup.Group // zero Group: no limit, no cancel on error
g.SetLimit(limit)
errs := make([]error, len(tasks))
for i, t := range tasks {
g.Go(func() error {
if err := t(ctx); err != nil {
errs[i] = fmt.Errorf("task %d: %w", i, err)
}
return nil // never stop the group
})
}
_ = g.Wait()
return errors.Join(errs...) // nil if every slot is nil
}
// ErrBusy is returned by Offer when every slot is taken.
var ErrBusy = errors.New("busy: concurrency limit reached")
// Shedder accepts work only while fewer than limit tasks are running.
type Shedder struct{ g errgroup.Group }
// NewShedder creates a group with a fixed limit.
func NewShedder(limit int) *Shedder {
s := &Shedder{}
s.g.SetLimit(limit)
return s
}
// Offer starts t if a slot is free, otherwise returns ErrBusy immediately
// (TryGo never blocks). Use it where a caller can retry later or get a 503.
func (s *Shedder) Offer(ctx context.Context, t Task) error {
if !s.g.TryGo(func() error { return t(ctx) }) {
return ErrBusy
}
return nil
}
// Wait waits for every accepted task.
func (s *Shedder) Wait() error { return s.g.Wait() }package errgroupx
import (
"context"
"errors"
"strings"
"sync/atomic"
"testing"
"time"
)
var errCard = errors.New("card declined")
func waitOrCancel(d time.Duration) Task {
return func(ctx context.Context) error {
select {
case <-time.After(d):
return nil
case <-ctx.Done():
return context.Cause(ctx) // why: the first task's error
}
}
}
func TestFailFastReturnsFirstErrorAndCancels(t *testing.T) {
var sawCause atomic.Bool
slow := func(ctx context.Context) error {
err := waitOrCancel(time.Second)(ctx)
if errors.Is(err, errCard) {
sawCause.Store(true)
}
return err
}
start := time.Now()
err := FailFast(context.Background(), -1, slow, slow, // -1 = no limit; 0 would block Go forever
func(context.Context) error { return errCard })
if !errors.Is(err, errCard) {
t.Fatalf("err = %v", err)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatal("slow tasks were not canceled")
}
if !sawCause.Load() {
t.Fatal("context.Cause did not carry the first error")
}
}
func TestCollectAllJoinsEveryError(t *testing.T) {
errTimeout := errors.New("timeout")
err := CollectAll(context.Background(), 2,
func(context.Context) error { return nil },
func(context.Context) error { return errCard },
func(context.Context) error { return errTimeout },
)
if !errors.Is(err, errCard) || !errors.Is(err, errTimeout) {
t.Fatalf("missing an error: %v", err)
}
if got := strings.Count(err.Error(), "\n") + 1; got != 2 {
t.Fatalf("joined %d errors, want 2:\n%v", got, err)
}
if err := CollectAll(context.Background(), 2, func(context.Context) error { return nil }); err != nil {
t.Fatalf("all ok must be nil, got %v", err)
}
}
func TestTryGoShedsLoad(t *testing.T) {
s := NewShedder(2)
release := make(chan struct{})
hold := func(context.Context) error { <-release; return nil }
if s.Offer(context.Background(), hold) != nil || s.Offer(context.Background(), hold) != nil {
t.Fatal("first two offers must be accepted")
}
if err := s.Offer(context.Background(), hold); !errors.Is(err, ErrBusy) {
t.Fatalf("third offer err = %v, want ErrBusy", err)
}
close(release)
if err := s.Wait(); err != nil {
t.Fatal(err)
}
}Pipelines, fan-out, fan-in, ordered map
// Package pipeline builds channel pipelines: a source fed by an iter.Seq,
// stages that each own and close their output channel, fan-out to N
// goroutines, fan-in with Merge, and an order-preserving parallel map.
// Every send also selects on ctx.Done(), so canceling ctx stops every stage
// and no goroutine is left blocked (the Go blog's "done channel" rule, with
// context instead of a bare chan struct{}).
package pipeline
import (
"context"
"iter"
"sync"
)
// send delivers v unless ctx is canceled first. It is the only way stages
// write, which is what makes the whole pipeline cancelable.
func send[T any](ctx context.Context, out chan<- T, v T) bool {
select {
case out <- v:
return true
case <-ctx.Done():
return false
}
}
// Source turns any iterator (slices.Values, maps.Keys, a DB cursor wrapped
// as iter.Seq) into the first stage. buf is the channel capacity.
func Source[T any](ctx context.Context, seq iter.Seq[T], buf int) <-chan T {
out := make(chan T, buf)
go func() {
defer close(out) // the stage that sends is the stage that closes
for v := range seq {
if !send(ctx, out, v) {
return
}
}
}()
return out
}
// Map is one stage run by one goroutine.
func Map[T, R any](ctx context.Context, in <-chan T, buf int, fn func(T) R) <-chan R {
out := make(chan R, buf)
go func() {
defer close(out)
for v := range in {
if !send(ctx, out, fn(v)) {
return
}
}
}()
return out
}
// FanOut starts n copies of the same stage reading from one input channel.
// Each copy has its own output; recombine them with Merge.
func FanOut[T, R any](ctx context.Context, in <-chan T, n int, fn func(T) R) []<-chan R {
outs := make([]<-chan R, n)
for i := range outs {
outs[i] = Map(ctx, in, 0, fn)
}
return outs
}
// Merge is fan-in: one output channel closed after every input is drained.
// The WaitGroup counts inputs; only the extra goroutine closes out, because
// a channel with several senders must be closed by someone who knows they
// are all done.
func Merge[T any](ctx context.Context, ins ...<-chan T) <-chan T {
out := make(chan T)
var wg sync.WaitGroup
wg.Add(len(ins))
for _, in := range ins {
go func() {
defer wg.Done()
for v := range in {
if !send(ctx, out, v) {
return
}
}
}()
}
go func() {
wg.Wait()
close(out)
}()
return out
}
type indexed[T any] struct {
i int
v T
}
// OrderedMap runs fn on n goroutines but emits results in input order: each
// value is tagged with its sequence number and a reorder buffer holds
// early finishers until the next expected index arrives. The buffer is
// bounded by the number of values in flight (about n plus channel slack).
func OrderedMap[T, R any](ctx context.Context, in <-chan T, n int, fn func(T) R) <-chan R {
tagged := make(chan indexed[T])
go func() {
defer close(tagged)
i := 0
for v := range in {
if !send(ctx, tagged, indexed[T]{i, v}) {
return
}
i++
}
}()
parts := FanOut(ctx, tagged, n, func(x indexed[T]) indexed[R] {
return indexed[R]{x.i, fn(x.v)}
})
merged := Merge(ctx, parts...)
out := make(chan R)
go func() {
defer close(out)
pending := map[int]R{}
next := 0
for r := range merged {
pending[r.i] = r.v
for v, ok := pending[next]; ok; v, ok = pending[next] {
delete(pending, next)
if !send(ctx, out, v) {
return
}
next++
}
}
}()
return out
}package pipeline
import (
"context"
"runtime"
"slices"
"sync/atomic"
"testing"
"time"
)
func noLeak(t *testing.T, before int) {
t.Helper()
deadline := time.Now().Add(time.Second)
for runtime.NumGoroutine() > before && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if g := runtime.NumGoroutine(); g > before {
buf := make([]byte, 1<<16)
t.Fatalf("goroutine leak: before=%d after=%d\n%s", before, g, buf[:runtime.Stack(buf, true)])
}
}
func TestFanOutFanInSum(t *testing.T) {
ctx := context.Background()
src := Source(ctx, slices.Values(seq(1, 100)), 0)
sq := FanOut(ctx, src, 4, func(n int) int { return n * n })
sum := 0
for v := range Merge(ctx, sq...) {
sum += v
}
if sum != 338350 { // 1^2 + ... + 100^2
t.Fatalf("sum = %d", sum)
}
}
func TestOrderedMapPreservesOrder(t *testing.T) {
ctx := context.Background()
in := Source(ctx, slices.Values(seq(0, 199)), 0)
slowEvens := func(n int) int {
if n%2 == 0 {
time.Sleep(200 * time.Microsecond) // evens finish later than odds
}
return n
}
got := slices.Collect(func(yield func(int) bool) {
for v := range OrderedMap(ctx, in, 8, slowEvens) {
if !yield(v) {
return
}
}
})
if !slices.Equal(got, seq(0, 199)) {
t.Fatalf("order broken: first values %v", got[:10])
}
}
func TestEarlyStopCancelsEveryStage(t *testing.T) {
before := runtime.NumGoroutine()
ctx, cancel := context.WithCancel(context.Background())
infinite := func(yield func(int) bool) {
for i := 0; ; i++ {
if !yield(i) {
return
}
}
}
src := Source(ctx, infinite, 16)
out := Merge(ctx, FanOut(ctx, src, 4, func(n int) int { return n })...)
for range 10 {
<-out // the consumer wants only ten values
}
cancel() // without this every stage stays blocked on a send forever
noLeak(t, before)
}
func TestUnbufferedStageAppliesBackpressure(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var produced atomic.Int64
counting := func(yield func(int) bool) {
for i := 0; ; i++ {
produced.Add(1)
if !yield(i) {
return
}
}
}
out := Map(ctx, Source(ctx, counting, 0), 0, func(n int) int { return n })
<-out
time.Sleep(20 * time.Millisecond) // give the producer every chance to run ahead
// One value consumed; at most a handful can be held by the blocked
// goroutines (one per stage plus one in hand): the producer is throttled.
if p := produced.Load(); p > 5 {
t.Fatalf("producer ran ahead: %d values produced for 1 consumed", p)
}
}
func seq(from, to int) []int {
s := make([]int, 0, to-from+1)
for i := from; i <= to; i++ {
s = append(s, i)
}
return s
}Batches, timeouts and work distribution
// Package batch covers splitting work: slices.Chunk for batches with a
// timeout per batch or per item, and static split versus a shared queue
// (dynamic balancing, the cheap cousin of work stealing).
package batch
import (
"context"
"fmt"
"slices"
"sync"
"time"
"golang.org/x/sync/errgroup"
)
// InsertFunc writes one batch, e.g. a multi-row INSERT or a bulk API call.
type InsertFunc func(ctx context.Context, rows []int) error
// InChunks writes rows in batches of size, at most par batches at once, with
// a deadline per batch. A slow batch fails alone; the others keep their
// own budget. slices.Chunk (Go 1.23) yields sub-slices that share the
// backing array and are clipped, so appending to one cannot clobber the next.
func InChunks(ctx context.Context, rows []int, size, par int, perBatch time.Duration, insert InsertFunc) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(par)
n := 0
for chunk := range slices.Chunk(rows, size) {
first := n
n += len(chunk)
g.Go(func() error {
bctx, cancel := context.WithTimeout(ctx, perBatch)
defer cancel()
if err := insert(bctx, chunk); err != nil {
return fmt.Errorf("batch at row %d (%d rows): %w", first, len(chunk), err)
}
return nil
})
}
return g.Wait()
}
// PerItemThenBatch gives every item its own deadline and the whole call an
// overall one: item budgets stop one slow item from eating the batch budget;
// the batch budget bounds the total no matter how many items there are.
func PerItemThenBatch(ctx context.Context, items []int, perItem, total time.Duration, fn func(context.Context, int) error) []error {
ctx, cancel := context.WithTimeout(ctx, total)
defer cancel()
errs := make([]error, len(items))
for i, it := range items {
ictx, icancel := context.WithTimeout(ctx, perItem) // never later than ctx
errs[i] = fn(ictx, it)
icancel()
}
return errs
}
// StaticSplit gives worker w the items w, w+n, w+2n... up front. Zero
// coordination, but if the costs are skewed one worker finishes last while
// the others sit idle.
func StaticSplit(costs []time.Duration, n int) time.Duration {
start := time.Now()
var wg sync.WaitGroup
wg.Add(n)
for w := range n {
go func() {
defer wg.Done()
for i := w; i < len(costs); i += n {
time.Sleep(costs[i])
}
}()
}
wg.Wait()
return time.Since(start)
}
// SharedQueue lets idle workers pull the next item from one channel, so a
// long item delays only its own worker. The Go scheduler itself balances
// goroutines across Ps by work stealing; this is the same idea one level up.
func SharedQueue(costs []time.Duration, n int) time.Duration {
start := time.Now()
q := make(chan time.Duration)
var wg sync.WaitGroup
wg.Add(n)
for range n {
go func() {
defer wg.Done()
for c := range q {
time.Sleep(c)
}
}()
}
for _, c := range costs {
q <- c
}
close(q)
wg.Wait()
return time.Since(start)
}package batch
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
)
func TestInChunksSizesAndCoverage(t *testing.T) {
rows := make([]int, 1050)
for i := range rows {
rows[i] = i
}
var mu sync.Mutex
var sizes []int
seen := 0
err := InChunks(context.Background(), rows, 500, 2, time.Second, func(_ context.Context, b []int) error {
if cap(b) != len(b) {
t.Errorf("chunk not clipped: len=%d cap=%d", len(b), cap(b))
}
mu.Lock()
sizes = append(sizes, len(b))
seen += len(b)
mu.Unlock()
return nil
})
if err != nil {
t.Fatal(err)
}
slices.Sort(sizes)
if !slices.Equal(sizes, []int{50, 500, 500}) || seen != 1050 {
t.Fatalf("sizes=%v seen=%d", sizes, seen)
}
}
func TestInChunksPerBatchTimeout(t *testing.T) {
rows := make([]int, 30)
err := InChunks(context.Background(), rows, 10, 3, 20*time.Millisecond, func(ctx context.Context, b []int) error {
<-ctx.Done() // simulate a stuck bulk insert
return ctx.Err()
})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
}
func TestPerItemBudget(t *testing.T) {
sleepy := func(ctx context.Context, n int) error {
select {
case <-time.After(time.Duration(n) * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
errs := PerItemThenBatch(context.Background(), []int{1, 200, 1}, 30*time.Millisecond, time.Second, sleepy)
if errs[0] != nil || errs[2] != nil || !errors.Is(errs[1], context.DeadlineExceeded) {
t.Fatalf("errs = %v: only the slow item should time out", errs)
}
}
func TestSharedQueueBeatsStaticSplitUnderSkew(t *testing.T) {
// 4 workers, 16 items; items 0,4,8,12 are slow and all land on worker 0
// with a static split.
costs := make([]time.Duration, 16)
for i := range costs {
costs[i] = time.Millisecond
if i%4 == 0 {
costs[i] = 15 * time.Millisecond
}
}
static := StaticSplit(costs, 4)
shared := SharedQueue(costs, 4)
t.Logf("static=%v shared=%v", static.Round(time.Millisecond), shared.Round(time.Millisecond))
if shared >= static {
t.Fatalf("shared queue (%v) should finish before static split (%v)", shared, static)
}
}Rate limit, retry and idempotency inside a pool
// Package ratelimited is a worker pool that calls a rate-limited partner
// API: N workers share one token bucket (x/time/rate), each job retries
// transient failures with capped exponential backoff and jitter, and every
// attempt carries the same idempotency key so the partner can deduplicate.
package ratelimited
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"sync"
"time"
"golang.org/x/time/rate"
)
// ErrTransient marks failures worth retrying (HTTP 429/503, timeouts).
var ErrTransient = errors.New("transient")
// Charge is one payment request. Key is the idempotency key, fixed per job.
type Charge struct {
Key string
Amount int
}
// API is the partner: Do must be idempotent per Charge.Key.
type API interface {
Do(ctx context.Context, c Charge) error
}
// Config: Workers = concurrency, PerSecond/Burst = the partner's quota,
// Attempts = max tries per job, BaseBackoff = first retry delay.
type Config struct {
Workers int
PerSecond float64
Burst int
Attempts int
BaseBackoff time.Duration
}
// Run processes every charge and returns one error per charge (nil = ok).
// Concurrency and rate are separate knobs: Workers caps how many calls are
// open at once, the limiter caps how many start per second.
func Run(ctx context.Context, cfg Config, api API, charges []Charge) []error {
lim := rate.NewLimiter(rate.Limit(cfg.PerSecond), cfg.Burst) // shared by all workers
errs := make([]error, len(charges))
idx := make(chan int)
var wg sync.WaitGroup
wg.Add(cfg.Workers)
for range cfg.Workers {
go func() {
defer wg.Done()
for i := range idx {
errs[i] = withRetry(ctx, cfg, lim, func(ctx context.Context) error {
return api.Do(ctx, charges[i])
})
}
}()
}
for i := range charges {
select {
case idx <- i:
case <-ctx.Done():
errs[i] = ctx.Err()
}
}
close(idx)
wg.Wait()
return errs
}
func withRetry(ctx context.Context, cfg Config, lim *rate.Limiter, call func(context.Context) error) error {
var err error
for attempt := range cfg.Attempts {
if werr := lim.Wait(ctx); werr != nil { // every attempt spends a token
return fmt.Errorf("rate wait: %w", werr)
}
if err = call(ctx); err == nil || !errors.Is(err, ErrTransient) {
return err // success or permanent failure: do not retry
}
if attempt == cfg.Attempts-1 {
break
}
backoff := cfg.BaseBackoff << attempt // 1x, 2x, 4x...
backoff = backoff/2 + rand.N(backoff/2+1) // jitter: [b/2, b]
t := time.NewTimer(backoff)
select {
case <-t.C:
case <-ctx.Done():
t.Stop()
return ctx.Err()
}
}
return fmt.Errorf("gave up after %d attempts: %w", cfg.Attempts, err)
}package ratelimited
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
)
type flaky struct {
mu sync.Mutex
attempts map[string]int // per idempotency key
failN int // first failN attempts per key fail transiently
declined string
}
func (f *flaky) Do(_ context.Context, c Charge) error {
f.mu.Lock()
defer f.mu.Unlock()
f.attempts[c.Key]++
if c.Key == f.declined {
return errors.New("card declined") // permanent
}
if f.attempts[c.Key] <= f.failN {
return fmt.Errorf("503 from partner: %w", ErrTransient)
}
return nil
}
func charges(n int) []Charge {
out := make([]Charge, n)
for i := range out {
out[i] = Charge{Key: fmt.Sprintf("idem-%02d", i), Amount: 100}
}
return out
}
func TestRetriesTransientWithSameKey(t *testing.T) {
api := &flaky{attempts: map[string]int{}, failN: 2, declined: "idem-03"}
cfg := Config{Workers: 4, PerSecond: 1000, Burst: 10, Attempts: 4, BaseBackoff: time.Millisecond}
errs := Run(context.Background(), cfg, api, charges(8))
for i, err := range errs {
if i == 3 {
if err == nil || errors.Is(err, ErrTransient) {
t.Fatalf("declined card must fail permanently, got %v", err)
}
if api.attempts["idem-03"] != 1 {
t.Fatalf("permanent error retried %d times", api.attempts["idem-03"])
}
continue
}
if err != nil {
t.Fatalf("charge %d: %v", i, err)
}
if got := api.attempts[fmt.Sprintf("idem-%02d", i)]; got != 3 {
t.Fatalf("charge %d: %d attempts with its key, want 3", i, got)
}
}
}
func TestLimiterCapsRate(t *testing.T) {
api := &flaky{attempts: map[string]int{}}
cfg := Config{Workers: 8, PerSecond: 100, Burst: 1, Attempts: 1}
start := time.Now()
errs := Run(context.Background(), cfg, api, charges(21))
took := time.Since(start)
for _, err := range errs {
if err != nil {
t.Fatal(err)
}
}
// 21 calls at 100/s with burst 1: the first is free, 20 wait 10ms each.
if took < 180*time.Millisecond {
t.Fatalf("21 calls took %v; the limiter did not throttle 8 workers", took)
}
}
func TestGiveUpWrapsLastError(t *testing.T) {
api := &flaky{attempts: map[string]int{}, failN: 100}
cfg := Config{Workers: 1, PerSecond: 1000, Burst: 1, Attempts: 3, BaseBackoff: time.Millisecond}
errs := Run(context.Background(), cfg, api, charges(1))
if !errors.Is(errs[0], ErrTransient) || api.attempts["idem-00"] != 3 {
t.Fatalf("err=%v attempts=%d", errs[0], api.attempts["idem-00"])
}
}Retry decisions inside workers
| Error in a job | Meaning | Retry inside the worker? |
|---|---|---|
context.DeadlineExceeded from the per-job ctx | This attempt was too slow | Yes, if idempotent, with backoff and a fresh per-attempt budget |
context.Canceled from the pool ctx | Shutdown or first error | No: stop now |
HTTP 429 / 503, Retry-After | Partner overloaded | Yes, honour Retry-After, keep the limiter |
| HTTP 400 / 422, validation | Deterministic | No |
*PanicError | Bug | No: record, alert |
| SQLSTATE 40001 / 40P01 | Serialization failure / deadlock | Yes, the whole transaction |
rate: Wait(n=...) would exceed context deadline | Not enough budget left | No: fail fast |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| 3–5 independent calls per request | errgroup.WithContext, no limit | Per-call timeouts | Simple fan-out, fail fast |
| Finite batch of 10 000 items, stop on error | errgroup + SetLimit(n) | out[i], wrap errors with the id | Bounded, ordered, cancelable |
| Finite batch, report every failure | zero errgroup.Group + SetLimit | errors.Join | Every item attempted |
| Continuous stream (consumer, webhook sender) | Worker pool | Queue depth, in-flight, histogram, drain | Long-lived, observable |
| Multistep ETL | Pipeline | Fan-out only the slowest stage | Stages tuned separately |
| Jobs with very different sizes | semaphore.Weighted | Clamp weights to the budget | Memory budget |
| Partner quota | Pool + shared rate.Limiter | Retry + idempotency key | Rate and concurrency both capped |
| CPU-bound transform | Workers = GOMAXPROCS(0) | Chunk tiny items | No oversubscription |
| Overloaded HTTP endpoint | Semaphore + TryGo/TryAcquire | 503 + Retry-After | Protects latency |
| Order per key only | Hash key → fixed worker | One channel per worker | Per-key order, parallel overall |
| Work must survive restarts | Durable queue (broker, Horizon) | Competing consumers | In-memory channels die with the process |
| Tests of timing code | testing/synctest (Go 1.25+) | Fake clock | Fast, deterministic |
For PHP/Laravel developers
PHP-FPM gives you "one process per request" and Laravel gives you process pools rather than goroutine pools. A queue worker is a long-lived process (php artisan queue:work) that takes one job at a time; the docs: "To assign multiple workers to a queue and process jobs concurrently, you should simply start multiple queue:work processes", for example with Supervisor's numprocs. Horizon supervises those processes for Redis queues and offers balancing strategies "auto, simple, and false"; auto "adjusts the number of worker processes per queue based on the current workload of the queue" between minProcesses and maxProcesses. Concurrency::run is Laravel's errgroup-like call: it serializes closures "to a hidden Artisan CLI command, which unserializes the closures and invokes it within its own PHP process", with drivers process (default), fork and sync, and a timeout: argument; Concurrency::defer runs closures after the response is sent.
| Laravel | Go | Note |
|---|---|---|
queue:work process | One worker goroutine | Go worker costs KBs, a PHP worker MBs |
Supervisor numprocs=8 | Config{Workers: 8} | Same knob: fixed workers |
Horizon balance => 'auto', maxProcesses | Resizing a pool from queue depth | Go pools are usually fixed; autoscale pods instead |
| Redis queue | jobs channel | The Redis queue survives a crash; a channel does not |
--timeout=30 | context.WithTimeout per job | Laravel kills the process (PCNTL); Go cancels cooperatively |
--tries=3, #[Tries(5)], backoff | Retry loop in the worker | Same classification rule |
RateLimited job middleware | Shared rate.Limiter | Laravel's is shared via cache/Redis |
--max-jobs, --max-time | Rarely needed | Go has no per-request memory growth to reset |
Concurrency::run([...]) | errgroup.Group + Wait | Go runs closures in goroutines, no serialization |
Concurrency::defer([...]) | Background pool / goroutine after response | Must be owned and drained on shutdown |
failed_jobs table | Results with Err → DLQ | See Dead-Letter Queue |
<?php
// Laravel 13: three independent slow calls, each in a child PHP process.
use Illuminate\Support\Facades\Concurrency;
[$price, $stock, $reviews] = Concurrency::run([
fn () => Pricing::for($sku),
fn () => Inventory::available($sku),
fn () => Reviews::summary($sku),
]);The Go version is g, ctx := errgroup.WithContext(ctx) with three g.Go calls writing three variables and one g.Wait(); it runs in one process in microseconds of overhead, and the first error cancels the other two calls, which Concurrency::run does not do. Queue internals are in Laravel Queue Internals.
In architecture: from a single process to a distributed system
Monolith: one process, one database
In one process, a worker pool is the in-memory queue between the HTTP layer and slow work, and every pool must be sized against the shared database pool. The simplest correct setup: handlers stay goroutine-per-request; a process-wide pool of 8 workers sends emails and renders thumbnails; sql.DB.SetMaxOpenConns(20) is larger than the sum of workers that touch the database. Because a channel is lost on crash, any job that must not be lost is first written to a table and the pool reads from it, which is also how you get a persistent queue depth:
-- A durable job table the in-process pool drains; SKIP LOCKED lets N workers
-- (or N processes) claim different rows without waiting for each other.
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
kind text NOT NULL,
payload jsonb NOT NULL,
idem_key text NOT NULL UNIQUE, -- retries reuse the key
attempts int NOT NULL DEFAULT 0,
run_after timestamptz NOT NULL DEFAULT now(),
locked_at timestamptz
);
-- One worker claims a batch of 50:
UPDATE jobs SET locked_at = now(), attempts = attempts + 1
WHERE id IN (
SELECT id FROM jobs
WHERE locked_at IS NULL AND run_after <= now()
ORDER BY id
LIMIT 50
FOR UPDATE SKIP LOCKED
)
RETURNING id, kind, payload, idem_key;
-- Queue depth for the dashboard:
SELECT count(*) FROM jobs WHERE locked_at IS NULL AND run_after <= now();Modular monolith and multiple databases
Each module owns its pools and their limits, so one module's burst cannot starve another: billing has 4 workers against its own database, catalog has 16 against its search cluster. Pools are constructed in main, injected into modules, and shut down in reverse order (stop HTTP, close module pools, wait for drain, close databases). A shared "global pool" for every module is the in-process version of a noisy neighbour; give each a budget, like a bulkhead (Bulkhead & Graceful Degradation).
Microservices
Across services, the jobs channel becomes a broker queue and the workers become consumer processes — Competing Consumers. Inside each consumer process a Go worker pool still decides how many messages are processed at once, and that number must agree with the broker's prefetch (RabbitMQ prefetch_count, Kafka max.poll.records, SQS batch size): prefetch 50 with 8 workers means up to 42 messages wait in memory, which is fine, but prefetch 1 000 hides backpressure and lengthens redelivery after a crash. Flow: orders publishes OrderPlaced → notifications consumer with prefetch 32 → pool of 16 workers → each worker calls the SMS provider through a shared rate.Limiter (quota 50/s) with the event id as idempotency key → ack after success, nack to a retry queue on transient errors, dead-letter on permanent ones. Per request, an API gateway uses errgroup to fan out to pricing, stock and reviews with a 300 ms budget propagated as gRPC deadlines.
Distributed data: replicas, caches, queues and multi-region
Pools amplify load on shared data. Fifty pods × 16 workers = 800 concurrent queries; the database sees that, not "16". Size per-pod pools from a global budget (connections ÷ pods), and prefer read replicas for read-heavy fan-out — while remembering replica lag: a worker that writes and then reads its own row through a replica may not see it. Cache stampedes are a fan-out problem: 800 workers missing the same key at once should collapse into one load (singleflight). For multi-region batch jobs, a static split by region or shard key keeps data local; a shared global queue balances better but crosses regions. Ordering guarantees end at the process boundary: per-key order across many consumers needs partitioning by key in the broker.
Scaling path: 1×, 10×, 100×
At 1× an errgroup with SetLimit and one process-wide pool are enough; size from GOMAXPROCS(0) or a Little's-law estimate. At 10× pools need metrics (queue depth, in-flight, latency histogram, errors by kind), load shedding at the door (TryGo → 503), a durable job table or broker for work that must survive deploys, and a global rate limiter shared by all pods (Redis). At 100× the design is a distributed one: autoscaling consumers on queue depth or lag (the role Horizon's auto strategy plays for PHP), partitioned queues for per-key order, per-tenant budgets so one tenant cannot fill every worker, and continuous leak detection (goroutineleak profile in staging, go_goroutines alerts in production).
Lab
All commands run from docs/snippets/go/worker-pools-pipelines. Steps 1–5 were run on the host (Go 1.27.4, darwin/arm64, -trimpath) and the output below is real. Step 6 needs a running HTTP service and is expected, not run.
1. Tests with the race detector.
go vet ./... && go test -race -count=1 ./...ok academy/worker-pools-pipelines/after
ok academy/worker-pools-pipelines/batch
ok academy/worker-pools-pipelines/before
ok academy/worker-pools-pipelines/bounded
ok academy/worker-pools-pipelines/errgroupx
? academy/worker-pools-pipelines/labbugs [no test files]
ok academy/worker-pools-pipelines/pipeline
ok academy/worker-pools-pipelines/ratelimited
ok academy/worker-pools-pipelines/workerpool2. Static split vs shared queue under skew.
go test -run SharedQueue -v ./batch=== RUN TestSharedQueueBeatsStaticSplitUnderSkew
batch_test.go:77: static=68ms shared=24ms
--- PASS: TestSharedQueueBeatsStaticSplitUnderSkew (0.09s)
PASS
ok academy/worker-pools-pipelines/batch 0.523sThe numbers move by a few milliseconds between runs (65–68 ms static); the ratio does not.
3. Every classic bug, one at a time. The program:
// Command labbugs reproduces the classic worker-pool bugs one at a time so
// the lab can show the exact runtime messages. Every case is a bug on
// purpose; run with -case=<name>.
package main
import (
"flag"
"fmt"
"os"
"runtime"
"sync"
"time"
)
func main() {
c := flag.String("case", "", "deadlock|closetwice|sendclosed|closenil|nowait|leak|race")
flag.Parse()
switch *c {
case "deadlock":
// Unbuffered results channel, nobody receiving yet: the only
// goroutine blocks on its own send.
results := make(chan int)
results <- 1
fmt.Println(<-results)
case "closetwice":
// Two producers each "politely" close the shared channel.
ch := make(chan int, 2)
var wg, sent sync.WaitGroup
sent.Add(2)
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
ch <- i
sent.Done()
sent.Wait() // both values are in the buffer
close(ch) // the second close panics
}()
}
wg.Wait()
case "sendclosed":
// The consumer closes the jobs channel while a producer still sends.
jobs := make(chan int, 1)
close(jobs)
jobs <- 1
case "closenil":
var jobs chan int // never made
close(jobs)
case "nowait":
// main returns before the workers finish: output is lost silently.
var mu sync.Mutex
done := 0
for range 4 {
go func() {
time.Sleep(10 * time.Millisecond)
mu.Lock()
done++
mu.Unlock()
}()
}
mu.Lock()
fmt.Printf("finished jobs seen by main: %d of 4\n", done)
mu.Unlock()
case "leak":
// Return on the first error while senders on an unbuffered channel
// are still blocked (the Go 1.26 release-notes example).
for round := range 3 {
_ = firstError(100)
fmt.Printf("after round %d: %d goroutines\n", round+1, runtime.NumGoroutine())
}
case "race":
// Many workers append to one slice without a lock.
var out []int
var wg sync.WaitGroup
for i := range 100 {
wg.Add(1)
go func() {
defer wg.Done()
out = append(out, i)
}()
}
wg.Wait()
fmt.Println("len:", len(out), "(should be 100)")
default:
flag.Usage()
os.Exit(2)
}
}
func firstError(n int) error {
ch := make(chan error) // unbuffered
for i := range n {
go func() {
if i == 0 {
ch <- fmt.Errorf("item %d failed", i) // fails fast
return
}
time.Sleep(time.Millisecond) // the others are slower
ch <- nil
}()
}
for range n {
if err := <-ch; err != nil {
return err // the other senders block forever
}
}
return nil
}go build -trimpath -o /tmp/labbugs ./labbugs
for c in deadlock closetwice sendclosed closenil nowait leak; do
echo "--- $c"; /tmp/labbugs -case=$c; echo "exit=$?"; done--- deadlock
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
academy/worker-pools-pipelines/labbugs/main.go:23 +0x2b8
exit=2
--- closetwice
panic: close of closed channel
goroutine 19 [running]:
main.main.func1()
academy/worker-pools-pipelines/labbugs/main.go:37 +0x74
created by main.main in goroutine 1
academy/worker-pools-pipelines/labbugs/main.go:32 +0x32c
exit=2
--- sendclosed
panic: send on closed channel
goroutine 1 [running]:
main.main()
academy/worker-pools-pipelines/labbugs/main.go:45 +0x244
exit=2
--- closenil
panic: close of nil channel
goroutine 1 [running]:
main.main()
academy/worker-pools-pipelines/labbugs/main.go:48 +0x310
exit=2
--- nowait
finished jobs seen by main: 0 of 4
exit=0
--- leak
after round 1: 100 goroutines
after round 2: 199 goroutines
after round 3: 299 goroutines
exit=0nowait exits 0 with wrong output — the most dangerous kind of bug. leak grows by 99 goroutines per call: the 99 senders blocked on an unbuffered channel nobody reads after the early return.
4. The race detector on a shared slice.
go build -race -trimpath -o /tmp/labbugs-race ./labbugs && /tmp/labbugs-race -case=race; echo "exit=$?"==================
WARNING: DATA RACE
Read at 0x00c000010018 by goroutine 7:
main.main.func3()
academy/worker-pools-pipelines/labbugs/main.go:76 +0x74
Previous write at 0x00c000010018 by goroutine 6:
main.main.func3()
academy/worker-pools-pipelines/labbugs/main.go:76 +0xd8
...
==================
len: 65 (should be 100)
Found 4 data race(s)
exit=665. vet catches a misplaced Add and a copied lock. A separate throw-away module (vet would fail the snippet module on purpose otherwise):
for i := range 3 {
go func() {
wg.Add(1) // misplaced: Wait may run before this
defer wg.Done()
fmt.Println(i)
}()
}
wg.Wait()
var mu sync.Mutex
worker(mu) // func worker(mu sync.Mutex)main.go:12:10: WaitGroup.Add called from inside new goroutine
main.go:19:9: call of worker copies lock value: sync.Mutex
main.go:22:16: worker passes lock by value: sync.Mutex6. Find a leak in a running service (expected, not run). Build with Go 1.27, import net/http/pprof, run the leaky handler under load, then:
curl -s localhost:6060/debug/pprof/goroutineleak?debug=1 | head -20goroutineleak profile: total 99
99 @ 0x... 0x... 0x...
# 0x... main.firstError.func1+0x... /app/main.go:93Expected shape only: one stack with a count equal to the leaked senders, pointing at the blocked ch <- nil.
Common misconceptions
| Belief | Reality |
|---|---|
| More goroutines always means more throughput | Throughput stops at the bottleneck (cores, connections, quota); more adds latency and memory |
| Goroutines are garbage collected when unreachable | They must exit on their own; blocked ones leak with everything they reference |
| One results channel keeps the input order | It keeps completion order; use indices or a reorder buffer |
| Any worker may close the results channel | With multiple senders, close from a closer goroutine after wg.Wait() |
| errgroup returns all errors | Wait returns the first; join the rest yourself |
| errgroup stops the other goroutines | It cancels the derived ctx; functions stop only if they watch it |
SetLimit(0) means unlimited | 0 admits nobody (Go blocks forever); negative is unlimited |
A recover in main protects workers | recover only works in the panicking goroutine |
| Bigger buffers make pipelines faster | Buffers smooth bursts; the slowest stage sets throughput |
runtime.NumCPU() respects container limits | It reports usable logical CPUs; use GOMAXPROCS(0) (container-aware from language version 1.25) |
| Go servers need a pool for requests | Goroutine per request is the design; bound the scarce resource instead |
| One rate limiter per worker caps the rate | N limiters allow N× the rate; share one |
| Retries are always safe | Only for idempotent operations or with an idempotency key |
| Fan-out sends each value to every reader | Each value goes to exactly one receiver |
| A per-batch timeout is enough | One slow item can consume the batch budget; add per-item deadlines |
Cheat sheet
| Topic | Remember |
|---|---|
| Worker pool | wg.Add(N) before go; workers for j := range jobs; closer wg.Wait(); close(results) |
| Who closes | The single sender closes; with multiple senders a coordinator closes; receivers never close |
| Ordering | Arrival order by default; out[i] for batches; reorder buffer for streams |
| Job lifecycle | Per-job WithTimeout + defer cancel(), per-job recover, close jobs to drain |
| Semaphore | make(chan struct{}, N); acquire before go; semaphore.Weighted for sizes |
| errgroup | g, ctx := errgroup.WithContext(ctx); use the new ctx; SetLimit(n); Wait = first error |
| TryGo | Non-blocking start; false → shed (503) |
| All errors | zero Group, errs[i], errors.Join(errs...) |
| Pipeline | Each stage defer close(out); every send select with ctx.Done() |
| Backpressure | Unbuffered or small buffers; fan out the slowest stage |
| Fan-in | One forwarder per input + WaitGroup + closer |
| Distribution | Shared channel beats static split under skew; chunk tiny items |
| Batches | slices.Chunk(s, n) (1.23), clipped sub-slices, n < 1 panics |
| Rate | One shared rate.NewLimiter(r, b); Wait(ctx) per attempt |
| Retry | Transient only, backoff + jitter, cap attempts, same idempotency key |
| Sizing | CPU-bound: GOMAXPROCS(0); IO-bound: throughput × latency, then measure |
| Observe | Queue depth, in-flight, latency histogram, go_goroutines, goroutineleak (1.27) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A pool has 8 workers and one results channel. Each worker calls close(results) when its range jobs loop ends. What happens, and what is the fix? Must-know
Answer
Answer: The second worker to finish panics with panic: close of closed channel (and any worker still sending after the first close panics with send on closed channel). With multiple senders, none of them may close. Add a closer goroutine: go func() { wg.Wait(); close(results) }(). See Worker pool.
2 — Why does after.LoadAll write out[i] = p from many goroutines without a mutex, and why is that not a data race? Good to know
Answer
Answer: Each goroutine writes a different element, so there is no conflicting access to the same memory location; the slice header itself is not modified. g.Wait() returns only after every function has returned, which synchronizes the writes before the caller's reads. append on a shared slice would race, because it reads and writes the shared header. See Happens-before.
3 — You use g, ctx := errgroup.WithContext(parent) but pass parent into each fetch. What changes? Must-know
Answer
Answer: Nothing is canceled on the first error: the other fetches run to completion against a context that is never canceled. Wait still returns the first error, but only after the slowest fetch finishes. Always pass the derived ctx.
4 — g.SetLimit(0) followed by g.Go(f). What happens? Important
Answer
Answer: Go blocks forever: "A limit of zero will prevent any new goroutines from being added." Use a negative value (or no SetLimit) for no limit. The page's FailFast test originally hung for exactly this reason.
5 — A function starts one goroutine per item that sends its error on an unbuffered channel and returns on the first non-nil error. What is the bug and two fixes? Important
Answer
Answer: A goroutine leak: after the early return, the remaining senders block forever (the lab's leak case grows by 99 goroutines per call). Fixes: buffer the channel to len(items) so every send completes; or pass a ctx, cancel it on return and select on ctx.Done() in every send; or use errgroup.WithContext.
6 — Your pipeline has a 1 ms source, a 10 ms parse stage and a 2 ms sink. Where do you add goroutines and what throughput do you expect with 5 parsers? Must-know
Answer
Answer: Fan out the parse stage. One parser gives about 100 items/s; five give about 500 items/s; the sink (2 ms, about 500 items/s) is then the next bottleneck. Buffers do not change the steady-state throughput.
7 — You need to upload files totalling 3 GB with at most 512 MB in memory at once; sizes vary from 1 MB to 400 MB. Which primitive, and what edge case do you guard? Important
Answer
Answer: semaphore.NewWeighted(512) with Acquire(ctx, sizeMB). Guard files larger than the budget: a weight above the total size can never be acquired and waits until ctx is done; clamp it (as WithWeighted does) or reject it.
8 — Eight workers each create rate.NewLimiter(10, 1) for a partner limited to 10 requests per second. What rate does the partner see? Important
Answer
Answer: Up to 80 requests per second: each limiter is independent. Create one limiter and share it across workers (it is safe for concurrent use); across pods, use a distributed limiter.
9 — A CPU-bound pool uses runtime.NumCPU() workers in a pod with a 2-CPU limit on a 32-core node, and the module says go 1.24. What goes wrong? Important
Answer
Answer: NumCPU reports the node's usable logical CPUs (32), and with language version 1.24 the default GOMAXPROCS is not container-aware, so 32 threads compete for 2 CPUs of quota and get throttled. Use runtime.GOMAXPROCS(0) and either upgrade the go line to 1.25+ or set GOMAXPROCS explicitly.
10 — When is a reorder buffer the wrong choice for ordering? Good to know
Answer
Answer: When one item can be very slow: everything behind it is held (head-of-line blocking) and memory grows with the window. If only per-key order matters, route each key to a fixed worker instead; if order matters only at the end, write results by index after Wait.
11 — What does a graceful drain do differently from canceling the pool's context? Important
Answer
Answer: Drain: the producer closes the jobs channel; workers finish every queued job, then exit; results are complete. Cancel: queued jobs are reported with context.Canceled without running, and running jobs see ctx done. A shutdown usually drains first and cancels when the grace period runs out.
12 — Name the three metrics every pool should export and what a rising queue depth with constant in-flight at the limit means. Important
Answer
Answer: Queue depth, in-flight and a latency histogram. Queue rising while in-flight sits at the worker count means the pool is saturated: arrivals exceed service rate. Check the latency histogram: if job latency rose, the downstream is slow (shed load, do not add workers); if it is flat, add workers or instances.
Glossary
| Term | Meaning |
|---|---|
| worker pool | A fixed number of goroutines processing jobs from a shared channel |
| fixed workers | The pool size; the concurrency limit of a pool |
| jobs channel | The channel workers receive from; closed by the single producer |
| results channel | The channel workers send results to; closed by the closer after wg.Wait() |
| close results | The closer goroutine's close(results) once all workers returned |
| WaitGroup | sync.WaitGroup: counts goroutines; Add before go, Done in defer, Wait |
| result ordering | Which order results come out: arrival, by index, or reordered |
| preserve order | Tag with an index; write out[i] or use a reorder buffer |
| reorder buffer | Map of early results held until the next expected index arrives |
| head-of-line blocking | One slow item delays all output queued behind it |
| per-job timeout | context.WithTimeout derived for each job |
| panic recovery | recover in a deferred call per job, turning a panic into a *PanicError |
| graceful drain | Stop accepting, finish queued jobs, then close results |
| bounded concurrency | A hard cap on operations in flight |
| semaphore | N tokens; acquire before work, release after |
| chan struct{} | Buffered channel of empty structs used as a counting semaphore |
| semaphore.Weighted | x/sync semaphore with weights, ctx-aware Acquire, FIFO waiters |
| errgroup | x/sync Group: WaitGroup + first error + optional ctx cancel + limit |
| Go (errgroup) | Starts f in a goroutine, blocking at the limit |
| TryGo | Starts f only if under the limit; reports whether it did |
| SetLimit | Caps active goroutines; negative = none, 0 = nobody |
| Wait (errgroup) | Waits for all; returns the first non-nil error; cancels the derived ctx |
| first error cancels | WithContext's ctx is canceled on the first non-nil error |
| context.Cause | Returns the error a WithCancelCause ctx was canceled with |
| errors.Join | Combines errors into one; nil if all nil; Is/As see each |
| pipeline | Stages connected by channels |
| stage | A group of goroutines running the same function between two channels |
| source / sink | First stage (producer) / last stage (consumer) |
| done channel | A channel closed to broadcast "stop"; superseded by ctx.Done() |
| cancellation | Signalling every stage to stop; via ctx |
| buffered stage | A stage whose output channel has capacity > 0 |
| backpressure | A slow consumer slowing the producer by blocking its sends |
| unbuffered deadlock | A send on an unbuffered channel with no receiver ever: all goroutines are asleep |
| fan-out | Several goroutines reading the same channel |
| fan-in | Merging several channels into one |
| merge | The fan-in function: forwarders + WaitGroup + closer |
| multiple senders close | Rule: with several senders, a coordinator closes, never a sender |
| static split | Assigning items to workers up front |
| work stealing | Idle workers take work from busy ones' queues; the Go scheduler does it for goroutines |
| shared queue | One channel all workers draw from; dynamic balancing |
| batch | A group of items processed in one call |
| chunk | A sub-slice of fixed size |
| slices.Chunk | Go 1.23 iterator over clipped sub-slices of up to n elements |
| iter.Seq | func(yield func(V) bool); a range-able iterator (Go 1.23) |
| rate limiting | Capping events per unit of time |
| x/time/rate | Go token-bucket package: NewLimiter, Wait, Allow, Reserve |
| retry | Re-running a failed attempt, for transient errors only |
| idempotency | Repeating an operation has the effect of doing it once; via idempotency keys |
| pool sizing | Choosing the worker count from the bottleneck and measurement |
| NumCPU | Logical CPUs usable by the process at start-up |
| GOMAXPROCS | Max OS threads running Go code at once; container-aware default since 1.25 |
| CPU-bound | Limited by computation; workers ≈ cores |
| IO-bound | Limited by waiting; workers ≈ throughput × latency |
| Little's law | Items in flight = arrival rate × time in system |
| goroutine per request | net/http's model: one goroutine per connection/request |
| load shedding | Rejecting work early (503) when at capacity |
| goroutine leak | A goroutine that can never exit |
| goroutineleak profile | Go 1.27 pprof profile listing goroutines blocked forever |
| queue depth | Jobs waiting: len(jobs) |
| in-flight | Jobs currently executing |
| latency histogram | Bucketed distribution of job durations |
| conc | github.com/sourcegraph/conc: pools and WaitGroups with panic handling |
| testing/synctest | Go 1.25 package: tests in a bubble with a fake clock |
| Horizon | Laravel's supervisor and dashboard for Redis queue worker processes |
| Concurrency::run | Laravel facade running closures in child PHP processes |
References
- Go specification (language version go1.27): Channel types, Send statements, Close, For statements with range clause
- The Go Memory Model (Channel communication, the counting-semaphore rule)
- Effective Go (Concurrency: Share by communicating, Channels, Parallelization); Go FAQ; Go Code Review Comments (Goroutine Lifetimes, Synchronous Functions)
- Go blog: Go Concurrency Patterns: Timing out, moving on (2010), Go Concurrency Patterns: Pipelines and cancellation (2014), Go Concurrency Patterns: Context (2014), Range Over Function Types (2024); Rob Pike, Go Concurrency Patterns (talk slides) (2012)
- Release notes: Go 1.22, Go 1.23, Go 1.24, Go 1.25, Go 1.26, Go 1.27
- Standard library source and docs (pkg.go.dev returned 403 to the fetcher, so the same doc comments were read from source and
go docin Go 1.27.4): sync/waitgroup.go, slices/iter.go;go doc slices.Chunk,go doc sync.WaitGroup.Go,go doc runtime.NumCPU,go doc runtime.GOMAXPROCS,go doc iter.Seq,go doc context.Cause - golang.org/x/sync v0.19.0: errgroup/errgroup.go (v0.19.0 raw), semaphore/semaphore.go, errgroup commit history
- golang.org/x/time v0.14.0: rate/rate.go (v0.14.0 raw)
- sourcegraph/conc (README)
- Laravel 13: Concurrency, Queues, Horizon