StackPractices
intermediate By Mathias Paulenko

Concurrent Patterns with Go Goroutines and Channels

Build concurrent systems in Go using goroutines, channels, select statements, worker pools, fan-out/fan-in, pipelines, context cancellation, and rate limiting with tickers.

Overview

Go’s concurrency model rests on two primitives: goroutines, which are lightweight threads multiplexed onto OS threads by the runtime, and channels, which are typed conduits that let those goroutines communicate without shared memory. The select statement multiplexes channel operations, and context carries cancellation signals across API boundaries.

This recipe walks through the patterns you’ll actually reach for: basic goroutines with sync.WaitGroup, worker pools, fan-out/fan-in, multi-stage pipelines, context cancellation, rate limiting with tickers, and error-aware fan-out with errgroup. Each example is a complete program you can run with go run. If you want the deeper theory behind the model (the CSP paper that inspired it and how the scheduler maps goroutines to threads), check the Complete Guide to Go Concurrency and the CSP communication recipe.

When to Use This

Reach for these patterns when you’re:

  • Calling several APIs or processing items in parallel and want a bounded number of workers
  • Building a producer-consumer pipeline with more than one stage
  • Rate-limiting outbound calls (third-party APIs, database writes, disk I/O)
  • Running background workers that need graceful shutdown on a signal or deadline

If your task is a single background job with no coordination, a plain go func() plus a done channel is enough; don’t build a worker pool for three tasks.

Prerequisites

  • Go 1.21+

Solution

1. Basic Goroutines and Channels

package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
	defer wg.Done()
	for job := range jobs {
		fmt.Printf("Worker %d processing job %d\n", id, job)
		time.Sleep(time.Second) // Simulate work
		results <- job * 2
	}
}

func main() {
	jobs := make(chan int, 100)
	results := make(chan int, 100)

	var wg sync.WaitGroup

	// Start 3 workers
	for w := 1; w <= 3; w++ {
		wg.Add(1)
		go worker(w, jobs, results, &wg)
	}

	// Send 5 jobs
	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)

	// Wait for all workers to finish
	go func() {
		wg.Wait()
		close(results)
	}()

	// Collect results
	for r := range results {
		fmt.Printf("Result: %d\n", r)
	}
}

2. Worker Pool Pattern

package main

import (
	"fmt"
	"sync"
)

type Job struct {
	ID    int
	Input string
}

type Result struct {
	JobID  int
	Output string
	Err    error
}

func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
	defer wg.Done()
	for job := range jobs {
		// Process job
		output, err := process(job.Input)
		results <- Result{
			JobID:  job.ID,
			Output: output,
			Err:    err,
		}
	}
}

func process(input string) (string, error) {
	return "processed:" + input, nil
}

func runWorkerPool(numWorkers, numJobs int) []Result {
	jobs := make(chan Job, numJobs)
	results := make(chan Result, numJobs)
	var wg sync.WaitGroup

	// Launch workers
	for w := 0; w < numWorkers; w++ {
		wg.Add(1)
		go worker(w, jobs, results, &wg)
	}

	// Send jobs
	for j := 0; j < numJobs; j++ {
		jobs <- Job{ID: j, Input: fmt.Sprintf("task-%d", j)}
	}
	close(jobs)

	// Wait and collect
	go func() {
		wg.Wait()
		close(results)
	}()

	var allResults []Result
	for r := range results {
		allResults = append(allResults, r)
	}
	return allResults
}

func main() {
	results := runWorkerPool(5, 20)
	fmt.Printf("Processed %d jobs\n", len(results))
}

3. Fan-Out / Fan-In

package main

import (
	"fmt"
	"sync"
)

// Fan-out: distribute work to multiple goroutines
// Fan-in: merge results from multiple goroutines into one channel

func producer(start, end int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for i := start; i <= end; i++ {
			out <- i
		}
	}()
	return out
}

func square(in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for n := range in {
			out <- n * n
		}
	}()
	return out
}

// Fan-in: merge multiple channels into one
func merge(channels ...<-chan int) <-chan int {
	var wg sync.WaitGroup
	out := make(chan int)

	output := func(c <-chan int) {
		defer wg.Done()
		for n := range c {
			out <- n
		}
	}

	wg.Add(len(channels))
	for _, c := range channels {
		go output(c)
	}

	go func() {
		wg.Wait()
		close(out)
	}()

	return out
}

func main() {
	// Fan-out: 4 workers processing the same input
	input := producer(1, 100)

	squared1 := square(input)
	squared2 := square(input)
	squared3 := square(input)
	squared4 := square(input)

	// Fan-in: merge all squared outputs
	for result := range merge(squared1, squared2, squared3, squared4) {
		fmt.Printf("Result: %d\n", result)
	}
}

4. Pipeline Pattern

package main

import "fmt"

// Multi-stage pipeline: generate → filter → transform → collect

func generate(nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			out <- n
		}
	}()
	return out
}

func filter(in <-chan int, predicate func(int) bool) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for n := range in {
			if predicate(n) {
				out <- n
			}
		}
	}()
	return out
}

func transform(in <-chan int, fn func(int) int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for n := range in {
			out <- fn(n)
		}
	}()
	return out
}

func main() {
	// Pipeline: generate → filter even → square → print
	nums := generate(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
	evens := filter(nums, func(n int) bool { return n%2 == 0 })
	squared := transform(evens, func(n int) int { return n * n })

	for result := range squared {
		fmt.Printf("Even squared: %d\n", result)
	}
}

5. Context Cancellation and Timeout

package main

import (
	"context"
	"fmt"
	"time"
)

func workerWithCtx(ctx context.Context, id int) error {
	for {
		select {
		case <-ctx.Done():
			fmt.Printf("Worker %d cancelled: %v\n", id, ctx.Err())
			return ctx.Err()
		default:
			// Simulate work
			time.Sleep(500 * time.Millisecond)
			fmt.Printf("Worker %d working...\n", id)
		}
	}
}

func main() {
	// Timeout context: cancels after 2 seconds
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	// Start 3 workers
	done := make(chan struct{})
	go func() {
		workerWithCtx(ctx, 1)
		workerWithCtx(ctx, 2)
		workerWithCtx(ctx, 3)
		close(done)
	}()

	select {
	case <-done:
		fmt.Println("All workers done")
	case <-ctx.Done():
		fmt.Println("Context cancelled:", ctx.Err())
	}
}

6. Rate Limiting with Ticker

package main

import (
	"fmt"
	"time"
)

func rateLimitedWorker(id int, rate <-chan time.Time) {
	for t := range rate {
		fmt.Printf("Worker %d ticked at %v\n", id, t)
		// Do rate-limited work here
	}
}

func main() {
	// 5 operations per second
	ticker := time.NewTicker(200 * time.Millisecond)
	defer ticker.Stop()

	// Run for 2 seconds
	timeout := time.After(2 * time.Second)

	go rateLimitedWorker(1, ticker.C)

	select {
	case <-timeout:
		fmt.Println("Time's up!")
	}
}

7. Select with Multiple Channels

package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(100 * time.Millisecond)
	defer ticker.Stop()
	tick := ticker.C
	boom := time.After(500 * time.Millisecond)

	for {
		select {
		case <-tick:
			fmt.Println("tick.")
		case <-boom:
			fmt.Println("BOOM!")
			return
		default:
			fmt.Println("    .")
			time.Sleep(50 * time.Millisecond)
		}
	}
}

8. Error Group (errgroup)

package main

import (
	"fmt"
	"net/http"
	"golang.org/x/sync/errgroup"
)

func fetchURL(url string) error {
	resp, err := http.Get(url)
	if err != nil {
		return fmt.Errorf("fetch %s: %w", url, err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf("fetch %s: status %d", url, resp.StatusCode)
	}
	return nil
}

func main() {
	urls := []string{
		"https://api.example.com/users",
		"https://api.example.com/orders",
		"https://api.example.com/products",
	}

	var g errgroup.Group

	for _, url := range urls {
		url := url // Capture loop variable
		g.Go(func() error {
			return fetchURL(url)
		})
	}

	// Wait for all goroutines: returns first error
	if err := g.Wait(); err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		fmt.Println("All fetches succeeded")
	}
}

How It Works

Goroutines and the scheduler

Goroutines are cheap threads the Go runtime schedules onto a small pool of OS threads (an M:N scheduler). Each goroutine starts with ~2KB of stack that grows and shrinks as needed, so spawning a thousand workers is routine while spawning a thousand OS threads is not. The runtime also detects blocked goroutines: when one waits on a channel or a mutex, the scheduler parks it and runs another on that OS thread. That’s why code full of time.Sleep or channel waits still saturates the CPU when real work is available.

There’s no controlling which goroutine runs when. If two goroutines write to the same variable without a channel, mutex, or atomic, you have a data race; run go test -race or go run -race to catch them.

Channels: sync vs buffered

An unbuffered channel synchronizes the two sides: the send blocks until a receiver is ready, and the receive blocks until a sender arrives. That’s a rendezvous, useful when you want a guarantee that the value was picked up. A buffered channel has a fixed queue: sends block only when the buffer is full, receives only when it’s empty. Buffers decouple producers and consumers that run at different speeds, but they don’t make a slow consumer faster; they just let the queue absorb bursts.

Closing a channel tells receivers “no more values coming”. Ranging over a channel exits the loop on close; a manual receive returns ok = false. Only the sender should close: a send on a closed channel panics, and closing it a second time panics too.

select, context, and cancellation

select waits on several channel operations at once and runs the first one that’s ready; ties are broken at random, which prevents starvation. The default case turns it into a non-blocking check, handy for “drain what arrived so far” loops.

context.Context is Go’s agreed way to say “stop now” across API boundaries. WithCancel gives you a cancel() to call; WithTimeout and WithDeadline cancel on their own. Workers honor it by checking ctx.Done() inside their loop: a goroutine that never checks the context can’t be cancelled. HTTP handlers, database drivers, and most libraries already accept a context, so pass it down instead of inventing your own done channel.

Worker pools and fan-out/fan-in

The worker pool in example 2 is the workhorse pattern: N workers read jobs from one channel, write results to another. It fans out work while bounding concurrency to N goroutines, no matter how many jobs arrive. Fan-out/fan-in (example 3) is the generalization: one source channel feeds several stage goroutines, and a merge function collapses their outputs into one channel so downstream code sees a single stream.

flowchart diagram: Producer<br>sends jobs

The pipeline in example 4 chains stages where each function takes <-chan and returns <-chan. Stages are independent, so you can reorder, drop, or insert a filter without touching the others. The important detail: every stage closes its output when the input closes, which lets the range loops terminate cleanly end to end.

errgroup and when to prefer it

errgroup wraps a sync.WaitGroup plus an error slot and an optional derived context. g.Wait() returns the first error; errgroup.WithContext gives you a context that’s cancelled as soon as one goroutine fails, so the rest can stop early instead of finishing doomed work. Reach for it whenever a fan-out can fail: a plain WaitGroup only tells you “all done”, never “something broke”.

Where leaks come from

A goroutine that blocks on a channel nobody writes to (or reads from) never exits: it just leaks memory and a scheduler slot forever. Classic causes: a worker waiting on jobs that nobody closes, a sender writing to results with no receiver, a select with no default in a for loop once the inputs are gone. The fix is always the same three things: the sender closes its output, workers check ctx.Done(), and the consumer drains results until the channel closes. time.Tick has a quieter version of this bug: the ticker underneath can’t be stopped, which is why example 7 uses NewTicker and defer ticker.Stop().

Variants

Bounded Parallelism with Semaphore

func boundedParallel(urls []string, maxConcurrent int) []error {
	sem := make(chan struct{}, maxConcurrent)
	errs := make([]error, len(urls))
	var wg sync.WaitGroup

	for i, url := range urls {
		wg.Add(1)
		go func(idx int, u string) {
			defer wg.Done()
			sem <- struct{}{}        // Acquire
			defer func() { <-sem }() // Release
			errs[idx] = fetchURL(u)
		}(i, url)
	}

	wg.Wait()
	return errs
}

Done Channel for Cancellation

func worker(done <-chan struct{}, jobs <-chan Job) {
	for {
		select {
		case <-done:
			return
		case job := <-jobs:
			process(job)
		}
	}
}

// Cancel by closing the done channel
done := make(chan struct{})
go worker(done, jobs)
// ... later
close(done) // Signals all workers to stop

Tee Pattern (Split Channel)

func tee[T any](in <-chan T) (<-chan T, <-chan T) {
	out1 := make(chan T)
	out2 := make(chan T)
	go func() {
		defer close(out1)
		defer close(out2)
		for val := range in {
			out1 <- val
			out2 <- val
		}
	}()
	return out1, out2
}

Best Practices

  • Close channels from the sender side: whoever writes gets to close. A send on a closed channel panics, so receivers never get the honor.
  • Prefer context over hand-rolled done channels: context.Context propagates cancellation, deadlines, and timeouts through one standard type. HTTP servers, database drivers, and errgroup all speak it.
  • Check ctx.Done() inside loops: a goroutine that can’t see the context can’t be stopped. Pair it with select so cancellation doesn’t wait behind a slow channel op.
  • Size buffered channels to the burst, not the total: the buffer absorbs spikes between producers and consumers. If you size it to every job, you’re just delaying the block.
  • Use errgroup when a fan-out can fail: it returns the first error and cancels the rest via context, so a dead API call doesn’t leave four siblings grinding.
  • Give every goroutine a way out: a closed input channel, a cancelled context, or a finished range. Anything else is a leak waiting for a memory profile to find it.

Common Mistakes

  • Closing a channel from the receiver: a send on a closed channel panics. Only the sender closes it, after the last send.
  • Not capturing loop variables: for _, url := range urls { go func() { fetch(url) }() } shares one url across goroutines on Go < 1.22, so they all fetch the last value. Shadow it (url := url) or pass it as an argument. Go 1.22+ gives each iteration its own variable, but the shadowing habit costs nothing.
  • Goroutine leaks: a goroutine reading a channel nobody writes to (or writing one nobody reads) lives forever. Every goroutine needs a termination path: closed channel, cancelled context, or completed range.
  • Using time.Tick for cancellable work: time.Tick gives you a channel whose underlying ticker can’t ever be stopped, and in a program that stays up it quietly leaks. Use time.NewTicker and defer ticker.Stop(); time.Tick is only fine in programs that exit anyway.
  • Unbuffered channels where you need decoupling: an unbuffered send parks until a receiver turns up. When your producer shouldn’t sit around waiting on a slow consumer, reach for a buffered channel instead.
  • Ignoring the ok from a receive: for v := range ch handles close for you, but v, ok := <-ch doesn’t: ok goes false once the channel is closed and drained.

See Also

Frequently Asked Questions

How many goroutines can I run at once?

Millions, in theory; each starts with about 2KB of stack, so 100,000 goroutines cost roughly 200MB. The scheduler handles them fine; your practical ceiling is memory and what the goroutines actually do, not a hard goroutine limit.

Should I use buffered or unbuffered channels?

Unbuffered when you want a rendezvous: the send blocks until the receive happens, so you know the value was picked up. Buffered when you want decoupling: the producer keeps working while the queue absorbs the backlog. If you're not sure, start unbuffered; the synchronization usually prevents more bugs than it costs.

What's the difference between context.WithCancel and context.WithTimeout?

WithCancel hands you a cancel() function you call yourself: a user disconnect, a shutdown signal, a first result coming back. WithTimeout cancels automatically when the duration expires. Reach for WithTimeout on anything with a deadline (API calls, DB queries) and WithCancel when cancellation is a program decision.

How do I wait for all goroutines to finish?

sync.WaitGroup: wg.Add(1) before each go, wg.Done() (usually via defer) inside the goroutine, wg.Wait() in the parent. If you also need the first error, or want one failure to cancel the rest, use errgroup.Group instead.

WaitGroup or errgroup: which should I pick?

Pick WaitGroup when all you care about is that everything finished. errgroup when failure matters: Wait() returns the first error, and errgroup.WithContext cancels the sibling goroutines so they stop early instead of finishing doomed work. Fetching N URLs? errgroup. Waiting for N background loaders that can't fail? WaitGroup is simpler.

What happens if I send on a closed channel?

It panics: "send on closed channel". The fix is discipline, not code: only the sender closes, and only after the last send. If several goroutines could close the same channel, serialize the close with sync.Once or funnel sends through one owner goroutine.

What's the difference between time.Tick and time.NewTicker?

Same tick stream, different cleanup. time.Tick leaks the underlying ticker; it runs until the process exits, so it's only safe in short-lived programs. time.NewTicker gives you Stop(), which is almost always what you want in a server or worker.