Security in Go from cryptography to the supply chain: using AES-GCM and Argon2id from the crypto packages correctly, signing, verifying, and rotating JWTs with golang-jwt/v5, OAuth2/OIDC flows with golang.org/x/oauth2 and go-oidc including PKCE, secrets management with Vault and SOPS beyond the env-var pitfalls — and the supply chain locked down with govulncheck, GOPRIVATE, and SBOMs.
Imagine a price comparison service: for every search, twelve merchant APIs must be queried, and each response takes roughly 250 milliseconds. Asking them one after another costs about three seconds per search — an eternity for users, and all the while the code spends its time not computing but waiting on I/O. Go was built for exactly this class of problems: we start twelve queries almost simultaneously and process each answer the moment it arrives. Total duration shrinks to that of the single slowest response.
Concurrency is Go's signature feature — no other aspect shapes the language and its ecosystem as much. This module lays the foundation in five lessons: today goroutines, then channels, select with context.Context, the sync package, and finally worker pools and pipelines. If you worked through the concurrent AI pipelines with errgroup in Module 4, you will now get to know those building blocks up close.
go Statement: One Word, Its Own ExecutionYou start a goroutine by simply prefixing a function call with the go keyword. That's all — no thread creation, no executor, no async/await. From that moment the function runs alongside the calling code; the runtime takes care of when and where it actually gets processor time.
package main
import (
"fmt"
"time"
)
func greet(name string) {
fmt.Println("Hello from", name)
}
func main() {
go greet("Alpha") // starts and runs alongside main
go greet("Beta")
fmt.Println("main continues immediately")
// shortcut: Sleep just for this demo. Real synchronization
// arrives with channels (Lesson 32) and WaitGroup (Lesson 34).
time.Sleep(50 * time.Millisecond)
// → main continues immediately
// → Hello from Alpha
// → Hello from Beta (the order of these two is not guaranteed)
}
Note the output order: main prints first, even though the goroutines were launched long before. The scheduler decides freely when each goroutine receives processor time — concurrency deliberately means the ordering is undetermined.
Goroutines Are Not Operating-System Threads
A goroutine is a runtime-managed execution with a tiny starting stack of just a few kilobytes that grows on demand. The runtime schedules goroutines M:N onto a handful of OS threads — which is why a Go program can comfortably carry hundreds of thousands of goroutines where real threads would long have hit memory limits. Rob Pike's saying captures it: concurrency is not parallelism — concurrency is a way to structure a program; parallelism is merely one possible way to execute it.
Go models scheduling with three building blocks: G (goroutine), M (machine, an OS thread), and P (processor, an execution context with a local run queue). A goroutine only runs when its G is bound to an M that holds a P. GOMAXPROCS determines how many Ps — and therefore how many goroutines genuinely compute in parallel — exist; the default is the number of CPU cores, and on Linux containers since Go 1.25 it also respects cgroup CPU limits.
Until Go 1.13, a tight loop that never hit a synchronization point could starve other goroutines on the same P. Since Go 1.14 the scheduler actively preempts such goroutines (asynchronous preemption). For everyday work this means: we may treat goroutines as cheap and fairly scheduled — the runtime handles the details.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("CPUs visible:", runtime.NumCPU())
fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0)) // 0 = read only, don't set
fmt.Println("goroutines alive:", runtime.NumGoroutine())
// → CPUs visible: 12
// → GOMAXPROCS: 12
// → goroutines alive: 1
}
Concurrency has a dark side: a goroutine that never ends is never cleaned up. The classic case is a pattern we already touched with errgroup in Module 4 — "take the first result". Launch two queries, use the faster one, discard the slower one. Sounds harmless, but it has a catch worth looking at closely:
func fetch(source string, duration time.Duration) string {
time.Sleep(duration) // simulated network latency
return source + ":hit"
}
func firstResult() string {
ch := make(chan string) // unbuffered
go func() { ch <- fetch("cache", 15*time.Millisecond) }()
go func() { ch <- fetch("database", 3*time.Second) }()
return <-ch // only the winner is ever received
}
func main() {
start := time.Now()
fmt.Println(firstResult())
fmt.Println("elapsed:", time.Since(start).Round(time.Millisecond))
fmt.Println("goroutines afterwards:", runtime.NumGoroutine())
// → cache:hit
// → elapsed: 16ms
// → goroutines afterwards: 2 (main + the losing database query)
}
Here's the problem: the loser sleeps for three seconds, then tries to deliver its result into a channel nobody reads anymore — and blocks on that forever. The goroutine leaks. In a one-shot program you won't notice, because process exit cleans everything up. In a server that runs this code per request, the goroutine count grows with every request, dragging memory and file handles up with it. You can find leaks with runtime.NumGoroutine() in tests (the count must return to its baseline afterwards) or with net/http/pprof on a live process.
The clean fix — cancellation via context.Context — arrives in Lesson 33; it will heal exactly this pattern.
⚠ Common mistake:
go f()does not start "background work that will eventually finish and whose result will be waiting for you". Whenmainreturns, the runtime terminates the entire process immediately — running goroutines are killed without comment, finished or not. Atime.Sleepin the main program is not synchronization, just a coincidence that usually works out on fast machines.
Check: What happens to still-running goroutines when
mainreturns?Answer: The program ends immediately — unfinished goroutines die with it
There is no waiting for children: when main returns, the runtime tears down the whole process along with every goroutine. Goroutines are not OS threads that the kernel would keep alive on its own — if you depend on a result, you must synchronize explicitly (channel, WaitGroup, or select).
Takeaways:
go f() launches a function as a goroutine: a few KB of stack, managed by the runtime, in any quantity.GOMAXPROCS caps true parallelism.runtime.NumGoroutine() and resolve blocked senders with context (Lesson 33).A ticket shop on the night of an event: a hundred requests pour in in parallel, all aiming at one of the last hundred seats. The naive implementation — every goroutine touching the same variable — is the shortest path into data chaos. Let's look at the mechanism on a bare counter; every available-- in the ticket shop looks exactly like this:
counter := 0 // ten goroutines increment it 1000 times each — expected: 10000
for i := 0; i < 10; i++ {
go func() {
for j := 0; j < 1000; j++ {
counter++ // read-modify-write: NOT an atomic step
}
}()
}
time.Sleep(100 * time.Millisecond) // shortcut: demo only
fmt.Println("counted:", counter)
// → counted: 9768 (expected: 10000 — often the result looks correct,
// which is exactly why such a bug survives test runs;
// `go run -race` reports it plainly: WARNING: DATA RACE)
An increment like counter++ looks atomic but is three steps: read, increment, write back. Two goroutines read the same value, both write their result back, one update vanishes without a trace — in the ticket shop that means the very last ticket is sold twice. The insidious part is the camouflage: on many runs the result happens to be correct, so the race rarely shows up in tests. The race detector (go test -race ./...) on the other hand flags such accesses on the very first concurrent access. Go offers two honest ways out: protection via locks (Lesson 34) — or the more elegant one we follow today: state belongs to exactly one goroutine, everyone else asks over channels. The Go proverb says it: "Don't communicate by sharing memory; share memory by communicating."
A channel is a typed conduit through which goroutines exchange values. The unbuffered variant is strict: a send blocks until a receiver is simultaneously ready — and vice versa. Send and receive form a true synchronization point; at the moment of handover, both sides are guaranteed to be on the same page.
package main
import "fmt"
func main() {
numbers := make(chan int) // unbuffered: no space to park
go func() {
for i := 1; i <= 3; i++ {
fmt.Println("sent: ", i)
numbers <- i // waits until the other side receives
}
close(numbers) // the sender closes — this ends the range loop below
}()
for n := range numbers {
fmt.Println("received:", n)
}
// → sent: 1
// → received: 1
// → sent: 2
// → received: 2
// → sent: 3
// → received: 3
// (a typical run — only "sent i" before "received i" is guaranteed,
// not the strict alternation of lines)
}
The output shows the rendezvous — and at the same time its limits: for every value sent appears before received, but that is all. An output like sent: 2 before received: 1 is perfectly legal too, because after each handover both sides run in parallel again; only the moment of handover itself is synchronized. Strictly speaking, the channel handover even establishes a happens-before relationship — everything the sender wrote before the handover is guaranteed visible to the receiver after it. And close is the polite way to signal: "nothing more is coming." A range loop then ends cleanly; a single receive reports the end through its second return value (value, open := ... with open == false).
With a capacity, the channel becomes a buffered FIFO: sending blocks only when the buffer is full; receiving only when it is empty. That decouples the two sides in time — exactly what we needed in Module 4, when workers wrote their results into a channel buffered with len(texts).
buffer := make(chan string, 2) // space for two values
buffer <- "first" // fits into the buffer, no receiver needed
buffer <- "second" // buffer is now full
fmt.Println("occupied:", len(buffer), "of", cap(buffer))
// → occupied: 2 of 2
fmt.Println(<-buffer) // FIFO: first in, first out
fmt.Println(<-buffer)
// → first
// → second
Ownership Instead of Locks
The channel idea replaces locks with ownership rules: a value handed over a channel changes hands. Only the receiving goroutine may touch it — no mutex needed, and data races are ruled out structurally, not merely prevented by discipline. Buffer size is a design tool in that respect: capacity 0 enforces a rendezvous, capacity n absorbs bursts and decouples timing.
Back to our ticket shop. Instead of a hundred goroutines touching the same variable, exactly one goroutine owns the seat count. Everyone else sends requests over a channel and receives the answer over their own reply channel — a pattern you will find all over Go source code:
type request struct {
count int
reply chan bool
}
func seatManager(requests chan request) {
available := 100 // ONLY this goroutine touches available
for r := range requests {
ok := r.count <= available
if ok {
available -= r.count
}
r.reply <- ok
}
}
func main() {
requests := make(chan request)
go seatManager(requests)
buy := func(n int) bool {
r := request{count: n, reply: make(chan bool)}
requests <- r
return <-r.reply
}
fmt.Println(buy(60), buy(60), buy(20))
// → true false true
}
No lock, no flag — and still no double sale can happen, because every decision runs serialized through the single manager. To be honest: for a plain counter, a sync.Mutex from Lesson 34 would be less ceremony. Channels pay off when ownership is transferred, when multiple parties must coordinate, or when a pipeline emerges — the latter we will see big in Lesson 35.
⚠ Common mistake:
closeis exclusively the sender's job. Closing from the receiving side, closing a second time, or sending on an already closed channel earns you a panic — and in production it usually detonates far from the actual culprit. The receiver detects the end of a channel safely via the second return value of a receive, or simply byrangeending.
Check: When does a send on an unbuffered channel return?
Answer: Only once a receiver has taken the value over at the same time
An unbuffered channel has no storage whatsoever — send and receive are a single, simultaneous handover. That is precisely what makes it a synchronization point: afterwards the sender knows for sure the receiver holds the value. Answering 'immediately' means you are thinking of buffered channels or Java-style queues.
Takeaways:
go test -race.close belongs to the sender; receivers detect the end via range or the second return value of a receive.An aggregator service queries two mirrors of the same data source for every search — sometimes one is faster, sometimes the other. But the user waits half a second at most, then wants to see a fallback. And when the user has long since closed the page, the remaining background fetches should stop burning resources for nothing. Both — "first one wins" and "cancel everyone" — we solve in this lesson with select and context.Context.
select: The Traffic Officer at the Junctionselect waits on several channel operations at once and executes exactly the case whose operation becomes ready first. The syntax resembles switch, but the semantics differ: the cases are not alternatives for one variable, they are competing events. The most important building block is time.After: it returns a channel that delivers exactly one value after the duration elapses — the perfect timer in a select world.
func fetch(name string, duration time.Duration) chan string {
ch := make(chan string, 1) // buffer 1: the result is never lost, however the race ends
go func() {
time.Sleep(duration)
ch <- name + ":OK"
}()
return ch
}
func main() {
mirrorA := fetch("mirror-a", 80*time.Millisecond)
mirrorB := fetch("mirror-b", 200*time.Millisecond)
select {
case a := <-mirrorA:
fmt.Println("winner:", a)
case b := <-mirrorB:
fmt.Println("winner:", b)
case <-time.After(500 * time.Millisecond):
fmt.Println("Timeout: both mirrors too slow")
}
// → winner: mirror-a:OK
}
Two details deserve attention. First: if several cases are ready at the same time, the runtime picks one pseudo-randomly — a fairness feature that prevents one dominant channel from starving the rest. Second: the losing fetch keeps running silently; only its buffer of 1 stops it from becoming the leak of Lesson 31, because its result can harmlessly slip into the buffered channel and die with it. If you want all participants to stop cleanly, you need more than a timeout — you need cancellation.
Done() Is a Broadcast
A closed channel is, for every receiver, instantly and permanently "ready": every receive on it returns immediately with the zero value. context.Context builds on exactly that: ctx.Done() returns a channel that is closed the moment the context is canceled or its deadline expires. A single close thereby wakes every goroutine waiting on Done() in a select — cancellation as an all-call instead of a cascade of individual signals.
context.Context: Cancellation as Part of the SignatureA context.Context carries three things through the call graph: a cancellation signal, a deadline, and request data (trace IDs, for example). The convention is identical across the whole Go ecosystem: ctx is a function's first argument, values are passed from the outside in, and contexts are never stored in structs. Contexts form a tree: context.Background() is the root, WithCancel and WithTimeout derive children, and a cancellation propagates to every descendant.
func worker(ctx context.Context, name string) chan string {
ch := make(chan string, 1)
go func() {
select {
case <-time.After(150 * time.Millisecond): // simulated work
ch <- name + ":done"
case <-ctx.Done(): // cancellation or deadline — an all-call to everyone waiting
ch <- name + " aborts: " + ctx.Err().Error()
}
}()
return ch
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel() // mandatory: releases timer and context entries immediately
fmt.Println(<-worker(ctx, "crawler"))
// → crawler aborts: context deadline exceeded
}
The worker has to cooperate for this: stopping concurrency in Go is always cooperation, never a forced kill. The worker checks — ideally in every blocking select and every loop iteration — whether the context is still alive, and cleans up on cancellation. ctx.Err() returns the reason (context.DeadlineExceeded or context.Canceled).
With that, the leak from Lesson 31 can be healed for real: the loser of the race receives the same context, notices the cancellation via ctx.Done(), and returns in an orderly fashion instead of waiting forever for a receiver. In Lesson 35 we will meet this interplay again inside the worker pool — and in practice half of Go's HTTP stack runs on it: http.NewRequestWithContext cancels network requests the moment the context ends.
⚠ Common mistake:
context.WithTimeoutandWithCancelreturn acancelfunction that belongs in adefer cancel()immediately — even if the deadline would "take care of it anyway". Withoutcancel, the context holds its timer and internal entries until natural expiry; on long-running servers those leaks add up across millions of requests.go vetreports a forgottencancelaslostcancel, by the way.
Check: In a
select, two cases are ready at the same time. What does the runtime do?Answer: It picks one of the ready cases pseudo-randomly
The uniform random choice among ready cases is deliberate: it makes select fair and stops the case written first from starving the others. Case order carries no priority in a select — if you need priorities, you must model them explicitly with nested selects and a targeted default.
Takeaways:
select waits on multiple channel operations and serves the first ready case; among several ready ones the runtime decides pseudo-randomly, and thus fairly.time.After delivers a one-shot timer channel — in a select, any wait becomes cancelable.context.Context carries cancellation, deadlines, and request data; convention: first argument, always passed down, never stored in structs.cancel from WithTimeout/WithCancel immediately via defer — otherwise timers and context entries leak until the deadline.ctx.Done() in every select and clean up on abort.A metrics service collects counters from two hundred endpoints: incremented on every request, read once per second for the dashboard. You could build that with an owning manager goroutine from Lesson 32 — but for a protected value, that is ceremony. Go never claimed locks were forbidden; the proverb merely recommends channels as the first tool. The sync package provides the three classics every Go toolbox contains: WaitGroup for waiting, Mutex for protected state, Once for one-time initialization.
sync.WaitGroup: A Counter for WaitingWe basically know the pattern already from errgroup in Module 4: Add(1) before every launch, defer Done() inside the goroutine, and the main program waits with Wait() until the counter falls back to zero. What's notable about WaitGroup is what it cannot do: it carries neither values nor errors — that stays with channels. Since Go 1.25, wg.Go(f) offers a shortcut that couples Add(1) and Done() automatically.
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
urls := []string{"go.dev", "pkg.go.dev", "blog.golang.org"}
hits := make([]string, len(urls))
var wg sync.WaitGroup
for i, url := range urls {
wg.Add(1) // BEFORE the launch — never inside the goroutine
go func(i int, url string) {
defer wg.Done()
hits[i] = strings.ToUpper(url) // each goroutine owns its index: no conflict
}(i, url)
}
wg.Wait() // blocks until the counter is back to zero
fmt.Println(hits)
// → [GO.DE PKG.GO.DE BLOG.GOLANG.ORG]
}
Incidentally: it is legal that every goroutine here writes into its own slice element — distinct memory locations, no conflict, no race. Explicitly passing i and url into the closure has no longer been required since Go 1.22 (loop variables are per iteration now), but it remains ubiquitous in older codebases and therefore readable.
sync.Mutex and sync.RWMutex: Locks for StateFor the metrics service, a Mutex is the honest answer: a lock guaranteeing that only one goroutine at a time enters the critical section. The rules are short: acquire as late as necessary, release as early as possible — and with several methods on the same state, one and the same lock protects them all. RWMutex refines this for read-heavy profiles: any number of readers in parallel, writers exclusive. Under write-heavy contention, however, RWMutex costs more than a plain Mutex — weigh it, don't reflex it.
type Counter struct {
mu sync.Mutex
values map[string]int
}
func (c *Counter) Inc(name string) {
c.mu.Lock()
defer c.mu.Unlock()
c.values[name]++
}
func (c *Counter) Snapshot() map[string]int {
c.mu.Lock()
defer c.mu.Unlock()
snapshot := make(map[string]int, len(c.values))
for k, v := range c.values {
snapshot[k] = v
}
return snapshot // a copy, not a reference: callers never see unprotected state
}
func main() {
c := &Counter{values: make(map[string]int)}
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c.Inc("requests")
}()
}
wg.Wait()
fmt.Println(c.Snapshot())
// → map[requests:100]
}
Note the Snapshot detail: it returns a copy, not a reference to the unprotected original — otherwise callers could bypass the lock perfectly and read unsynchronized afterwards. One more watchdog: a Mutex must not be copied after first use; structs containing locks are passed by pointer. go vet reliably flags violations with its copylocks rule.
sync.Once: Exactly Once, GuaranteedDatabase pools, configuration files, expensive computations — many things should be initialized on first use and never touched again. sync.Once encapsulates exactly that guarantee, thread-safe and without any ceremony:
var (
once sync.Once
pool *dbPool
)
func Pool() *dbPool {
once.Do(func() {
pool = &dbPool{connections: 20}
fmt.Println("pool initialized (this line appears exactly once)")
})
return pool
}
func main() {
Pool()
Pool() // the second call returns immediately without running the function again
}
// → pool initialized (this line appears exactly once)
Mutex for State, Channel for Ownership
Rule of thumb for the toolbox: a Mutex fits when several goroutines need access to the same protected state (cache, counters, registry). A channel fits when values — or the responsibility for them — are handed over (pipelines, task distribution, results). Neither is wrong — wrong only is hiding stateless data transfer behind locks, or needlessly cycling hot state through channels.
⚠ Common mistake:
wg.Add(1)belongs before thegostatement, never inside it. Otherwisewg.Wait()can observe the counter at zero before the first goroutine has even run itsAddcall — the program exits seemingly successful while work is silently missing. The bug is a genuine data race, flagged by the race detector, but it usually surfaces only under load.
Check: A hundred goroutines call
once.Do(f)simultaneously. What happens?Answer: Exactly one executes f; the others block until it finishes, then return
Once locks on the first Do call: one goroutine executes f, all concurrent callers block until it completes — and every later call returns at virtually no cost. Choosing 'every goroutine once' confuses Once with a per-goroutine flag; the guarantee is global and per Once instance.
Takeaways:
sync.WaitGroup: Add(1) before the go statement, defer Done() inside, Wait() in the main program — shorter as of Go 1.25 with wg.Go(f).sync.Mutex protects shared state; defer mu.Unlock() right after Lock() keeps critical sections short and panic-safe.RWMutex pays off for read-heavy access; under write load a plain Mutex is often faster.go vet copylocks) and never hand out references to protected data — return copies.sync.Once initializes exactly once even under concurrent callers — the idiomatic tool for lazy init.An image service takes in a nightly batch: 10,000 uploads, every picture needs a thumbnail. One goroutine per image? "Goroutines are cheap" — yes, but the work behind them is not: 10,000 concurrent disk reads, 10,000 open encoders, plus a downstream system that falls over beyond 50 parallel requests. The solution is a worker pool of fixed size: many tasks, few workers, one channel as the conveyor belt between them. And once we have conveyor belts, we can chain them into stages — a pipeline with fan-out and fan-in.
The recipe has four ingredients: a jobs channel, a results channel, N goroutines working through jobs in a range loop, and a sync.WaitGroup reporting when all workers are done. Closing the channels follows the rules of Lesson 32: the feeder closes the jobs, and the results are closed only once the last worker has finished — hence the Wait before the close.
package main
import (
"fmt"
"sync"
)
func main() {
const numJobs = 6
const numWorkers = 2
jobs := make(chan int, numJobs) // buffer: the producer never blocks while feeding
results := make(chan string, numJobs) // buffer: workers never block while storing
var wg sync.WaitGroup
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
for job := range jobs { // loop ends as soon as jobs is closed
results <- fmt.Sprintf("worker %d finished job %d", id, job)
}
}(w)
}
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs) // all tasks distributed → the sender closes
wg.Wait()
close(results) // only now is it certain: no worker writes anymore
for r := range results {
fmt.Println(r)
}
// → worker 1 finished job 1
// → worker 2 finished job 2
// → worker 1 finished job 3
// → ... the job-to-worker mapping and order vary
}
The buffers are chosen deliberately: the jobs buffer of numJobs lets the feeder hand off every task without waiting for workers; the results buffer stops workers from blocking while wg.Wait() waits on them — the same deadlock trap we discussed in Module 4 with errgroup. In production you replace the fixed job count with a loop over the real tasks and add a select on ctx.Done() from Lesson 33 for a clean shutdown.
Backpressure Instead of Throttling
A bounded worker pool with bounded buffers automatically creates backpressure: when all workers are busy and the jobs buffer is full, the feeder blocks — the system slows the inflow instead of overloading itself. No rate limiter, no drop logic: the blocking semantics of channels from Lesson 32 is the throttle.
In long processing chains, the weakest stage is the bottleneck. Pipelines in Go consist of stages that each read one channel and write one channel — and every stage can itself be parallel. Two terms belong to that: fan-out means several instances of a stage read the same input channel (each task lands with exactly one); fan-in means a merger that collects the outputs of several instances back into a single channel.
func generate(values ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, v := range values {
out <- v
}
}()
return out
}
func double(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for v := range in {
out <- v * 2
}
}()
return out
}
// merge fans several sources back into one output channel (fan-in)
func merge(sources ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
for _, source := range sources {
wg.Add(1)
go func(source <-chan int) {
defer wg.Done()
for v := range source {
out <- v
}
}(source)
}
go func() {
wg.Wait() // wait until ALL sources are drained
close(out) // only then close the merged channel
}()
return out
}
func main() {
input := generate(1, 2, 3, 4, 5)
// Fan-out: two double stages share the same input
stageA := double(input)
stageB := double(input)
// Fan-in: one channel collects all results
for v := range merge(stageA, stageB) {
fmt.Print(v, " ")
}
fmt.Println()
// → 2 4 6 8 10 (every value doubled exactly once, order not fixed)
}
The interplay of every lesson in this module hides in these lines: goroutines as stages (31), channels with closing discipline as the handovers (32), select on ctx.Done() for cancellation in every stage (33), and WaitGroups as the pacemaker of fan-in (34). Exactly this pattern — multiplied by error handling with errgroup and rate limiting — was the concurrent AI pipeline in Module 4; now you understand each of its parts individually.
⚠ Common mistake: The merged channel in a fan-in may only be closed once every producer is truly finished — which is why, above, it happens only after
wg.Wait()in a dedicated goroutine. Acloseissued by one worker while another stage is still sending ends in the panic "send on closed channel"; and forgetting to close at all leaves the consumer'srangeloop hanging forever.
Check: Why a pool of two workers for 10,000 jobs instead of simply starting 10,000 goroutines?
Answer: Because the fixed size spares resources like connections, memory, and downstream limits, and creates backpressure
Goroutines themselves are cheap — expensive is the work they trigger: file handles, sockets, memory per task, and the tolerance of the systems behind them. A pool caps the true parallelism, and full buffers automatically slow the producer (backpressure). For pure CPU tasks, 10,000 goroutines would be feasible, but they would bound none of the resources behind them.
Takeaways:
go launches goroutines with a tiny stack, the M:N scheduler spreads them fairly — but when main returns they all die unfiltered, and blocked goroutines leak.close is exclusively the sender's business.select waits fairly on multiple channels, time.After provides timeouts, and context.Context turns cancellation into an all-call across the whole call tree — defer cancel() included.sync package covers what channels would overengineer: WaitGroup for waiting, Mutex for protected state, Once for one-time initialization.wg.Wait().Course navigation: ← Module 6 · All 20 modules · Module 8 →