Thuta Learning
Go
AdvancedProgrammingBeginner

Select, Pipelines & Worker Pools

GoLesson 2140 min

What you'll walk away with

  • Explain how select chooses among the cases that are ready
  • Write a timeout with time.After and a non-blocking receive with default
  • Build a pipeline where each stage owns and closes its own output channel
  • Write a worker pool: N workers, one jobs channel, results closed after a WaitGroup
  • Carry job IDs so results can be put back in input order

Explain it simply

Select and worker pools in plain language

select is like a switch for channels. You write 'if a value arrives on this channel do this, if the timer fires first do that', and it runs whichever case is ready first. A worker pool is a fixed-size team of goroutines that keeps taking jobs from one queue until the queue is empty.

Picture the counters at a bank. The bank does not open a new counter for every customer; three clerks call the next person from one queue. Customers may leave in a different order than they arrived, but each holds a ticket number, so nobody's paperwork gets mixed up.

Problem → Why → Solution

The problem: one goroutine per job

Starting one goroutine per input, as in the previous lesson, works well for ten items. The day a hundred thousand items arrive, it tries to open a hundred thousand database connections at once, the server hits its connection limit and requests fail. At the same time, goroutines pile up because they wait on a slow dependency with no time limit.

unbounded.go
for _, id := range userIDs { // 100,000 IDs
	go func() {
		row := db.QueryRow("SELECT ...", id) // 100,000 queries at once
		results <- scan(row)                 // waits forever if nobody reads
	}()
}

Why limits and timeouts matter

Goroutines are cheap, but the database connections, file handles and API quota they use are not. A worker pool limits the number of goroutines to N and lets the remaining jobs wait in a channel. select lets a goroutine wait for 'a value or a timeout, whichever comes first', so a slow dependency can no longer hold it hostage forever.

Core concept: select, pipelines and worker pools

In a select statement each case is one channel send or receive. If no case is ready, select blocks until one is. If several are ready at the same moment, it picks one at random rather than in written order, so one busy channel cannot starve another. Add a default case and select no longer waits: when nothing is ready, default runs immediately.

Timeouts are simple: time.After(d) returns a channel that delivers a value after d, so adding it as a case turns the wait into 'a result or a timeout'. Because a case on a nil channel is never ready, you can also switch a finished channel to nil to disable its case inside a select loop.

A pipeline is a chain of stages connected by channels: each stage reads from its input channel, does some work and sends to its output channel. There is one rule: every stage owns its output channel and closes it when its input is closed. Then the first stage's close travels down the chain, and the final range stops naturally.

In a worker pool, N goroutines range over a single jobs channel. Each job goes to exactly one worker, and closing jobs ends every worker's loop. No single worker may close results, because the others may still be sending, so a separate goroutine calls close(results) after wg.Wait(). Workers finish in no particular order, so give every job an ID and put each result back in place by that ID.

The jobs channel also gives you backpressure for free. When every worker is busy, the feeder's next send blocks, so the queue can never grow faster than the workers drain it; even a buffered jobs channel only lets the feeder run a few jobs ahead. That is the real difference from one goroutine per job: memory and connection use stay bounded no matter how many inputs arrive.

The three owners in a worker pool
  1. Feeder sends jobs, then closes jobs
  2. N workers range over jobs
  3. Closer: wg.Wait, then close results
  4. main puts results back by ID

Every channel has exactly one closer: the feeder owns jobs, the closer owns results, and workers close nothing.

General pattern

go
select {
case v := <-in:            // a value arrived
	use(v)
case out <- next:          // the receiver took our value
case <-time.After(limit):  // nothing happened in time
	handleTimeout()
default:                   // optional: do not wait at all
}

for range n { wg.Add(1); go worker(jobs, results, &wg) }
go func() { wg.Wait(); close(results) }()

Each case in a select is one channel operation, and default is optional. The two lines below are the skeleton of a worker pool: start N workers, and close results only after all of them are done.

Worked example: one worker with jobs and results channels

This is the smallest form of a worker pool: one worker reads jobs and sends squares to results. With a single worker and FIFO channels the output is always 4, 9, 16 in that order. Add more workers and that guarantee disappears, which is why the deeper section below shows a pool that restores order by ID. Notice also that both channels have a buffer of 3: main sends every job before reading any result, so without the buffers this would deadlock.

go
package main

import "fmt"

func worker(jobs <-chan int, results chan<- int) {
    for job := range jobs { results <- job * job }
}

func main() {
    jobs, results := make(chan int, 3), make(chan int, 3)
    go worker(jobs, results)
    for _, job := range []int{2, 3, 4} { jobs <- job }
    close(jobs)
    for range 3 { fmt.Println(<-results) }
}

Code breakdown

  1. Direction typesfunc worker(jobs <-chan int, results chan<- int) {

    worker may only receive from jobs and only send to results; an accidental close(jobs) here would be rejected by the compiler.

  2. Range until jobs closesfor job := range jobs { results <- job * job }

    Takes one job at a time until jobs is closed and drained. With more workers, all of them would take from this one channel.

  3. Buffers sized to the workjobs, results := make(chan int, 3), make(chan int, 3)

    main sends all three jobs before it reads anything, so the buffers are required. Unbuffered, the worker would block sending its first result while main blocks sending the second job, and each would wait for the other forever.

  4. Feeder closes jobsclose(jobs)

    main sent the jobs, so main closes jobs. That lets the worker's range finish, so the goroutine does not leak.

  5. Receive exactly threefor range 3 { fmt.Println(<-results) }

    Ranging over an integer works since Go 1.22. The count is known exactly, so main reads three times; with many workers, closing results and ranging over it is safer.

You should see
4
9
16

select: timeouts and non-blocking checks

The program below waits for two lookups with an 80ms timeout. The 10ms lookup arrives in time; the 200ms one reaches the timeout case. The buffer of 1 on slowLookup's channel matters: even when nobody reads after a timeout, the goroutine can drop its value into the buffer and exit, so it does not leak.

select.go
package main

import (
	"fmt"
	"time"
)

func slowLookup(d time.Duration) <-chan string {
	out := make(chan string, 1) // buffered so the sender never leaks
	go func() {
		time.Sleep(d)
		out <- fmt.Sprint("answer after ", d)
	}()
	return out
}

func main() {
	for _, d := range []time.Duration{10 * time.Millisecond, 200 * time.Millisecond} {
		select {
		case v := <-slowLookup(d):
			fmt.Println("got:", v)
		case <-time.After(80 * time.Millisecond):
			fmt.Println("timed out waiting", d)
		}
	}

	ready := make(chan int, 1)
	select {
	case v := <-ready:
		fmt.Println("value", v)
	default: // runs immediately when no case is ready
		fmt.Println("nothing ready, moving on")
	}
}

The output is got: answer after 10ms, timed out waiting 200ms and nothing ready, moving on. The ready channel holds no value, so the default case runs at once. Production code usually uses a context deadline instead of time.After, which is the topic of the next lesson.

Pipelines: chaining stages with channels

generate and square are stages, and both return a receive-only channel. Each stage has a single goroutine, so values arrive in order. Watch the cascade of closes: generate finishes and closes, square's range ends and square closes, then main's range ends.

pipeline.go
package main

import "fmt"

// generate is stage 1: it owns out and closes it.
func generate(nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			out <- n
		}
	}()
	return out
}

// square is stage 2: it reads until in closes, then closes its own 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
}

func main() {
	total := 0
	for v := range square(generate(1, 2, 3, 4)) {
		fmt.Println(v)
		total += v
	}
	fmt.Println("total:", total)
}

A three-worker pool with results by ID

In this pool three workers share one jobs channel. A feeder goroutine sends the jobs and closes jobs, and a closer goroutine closes results after wg.Wait(). Results may arrive in a different order on every run, but main stores each one at r.ID, so it always prints [4 9 16 25 36].

pool.go
package main

import (
	"fmt"
	"sync"
)

type Job struct{ ID, N int }
type Result struct{ ID, Square int }

func worker(jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
	defer wg.Done()
	for j := range jobs {
		results <- Result{ID: j.ID, Square: j.N * j.N}
	}
}

func main() {
	inputs := []int{2, 3, 4, 5, 6}
	jobs := make(chan Job)
	results := make(chan Result)

	var wg sync.WaitGroup
	for range 3 { // three workers share one jobs channel
		wg.Add(1)
		go worker(jobs, results, &wg)
	}
	go func() { // feeder: owns jobs, so it closes jobs
		for i, n := range inputs {
			jobs <- Job{ID: i, N: n}
		}
		close(jobs)
	}()
	go func() { // closer: results is closed once every worker is done
		wg.Wait()
		close(results)
	}()

	squares := make([]int, len(inputs))
	for r := range results { // arrival order varies; the ID does not
		squares[r.ID] = r.Square
	}
	fmt.Println(squares)
}

In real projects

In real projects

Worker pools and select are everywhere in backend services, especially where an external resource must not be overwhelmed. The number of workers is tuned to a real limit, such as the number of CPU cores or the database connection limit.

  • Image or video processing: for CPU-heavy work the number of workers is set from runtime.NumCPU(), and the remaining uploads queue up in a channel.
  • Rate-limited APIs: if a partner API allows only five concurrent requests, a pool of five workers can never exceed that limit.
  • Queue consumers: a service reading from Kafka or SQS has one goroutine feeding messages into a jobs channel while workers process them and use select to watch for a shutdown signal at the same time.

Common mistakes

Common mistakes with select and worker pools

Closing results inside a worker

If a worker calls close(results) when its own loop ends, workers that are still busy panic with send on closed channel. Workers should only defer wg.Done(); the close belongs to a single goroutine that runs after wg.Wait().

Calling wg.Wait() in main before reading results

If results is unbuffered and main calls wg.Wait() before reading, workers block while sending results and never reach Done, so the program deadlocks. Put Wait and close in their own goroutine and let main start ranging over results right away.

Spinning the CPU with select and default in a loop

Writing for { select { case v := <-ch: ...; default: } } makes default run instantly whenever the channel is empty, and the loop burns a whole CPU core. If you want to wait, remove default; it belongs only where you really mean 'do something else instead of waiting'.

Best practices

Best practices

  • Size the pool from a real limit (CPU, connections, API quota) rather than a guess.
  • Give every job an ID or index and restore order by it when order matters.
  • Put an error field in the result type; one failing job should not stop the whole pool.
  • Control shutdown with a context: workers should also wait on ctx.Done() inside their select.

Mini challenge

Mini challenge: a pool that turns titles into slugs

Write a pool of three workers that turns article titles into slugs: lowercase, trim the outer spaces and replace inner spaces with -. Print the slugs in input order.

  • Both Job and Result carry an ID
  • A feeder goroutine sends the jobs and closes jobs
  • A separate goroutine closes results after wg.Wait()
  • main stores each slug at its ID and prints them in order
slugs.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type Job struct {
	ID   int
	Name string
}

type Result struct {
	ID   int
	Slug string
}

func slugify(s string) string {
	// TODO: lowercase, trim spaces, replace " " with "-"
	return s
}

func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
	// TODO: defer Done, range over jobs, send a Result for each job
}

func main() {
	titles := []string{"Hello World", " Go Channels ", "Worker Pools", "Select Statement"}
	// TODO: make jobs and results, start 3 workers
	// TODO: feeder goroutine (send + close jobs)
	// TODO: closer goroutine (wg.Wait, then close results)
	// TODO: range results into a slice by ID, then print "ID slug" lines
	_ = titles
	fmt.Println("todo")
}

Expected: Although three workers run, every run prints 0 hello-world, 1 go-channels, 2 worker-pools, 3 select-statement and processed: 4 in that order.

Show hint

Chaining strings.TrimSpace, strings.ToLower and strings.ReplaceAll is all slugify needs. In main, create slugs := make([]string, len(titles)) and fill it with slugs[r.ID] = r.Slug.

Show solution
slugs.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type Job struct {
	ID   int
	Name string
}

type Result struct {
	ID   int
	Slug string
}

func slugify(s string) string {
	return strings.ReplaceAll(strings.ToLower(strings.TrimSpace(s)), " ", "-")
}

func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
	defer wg.Done()
	for j := range jobs {
		results <- Result{ID: j.ID, Slug: slugify(j.Name)}
	}
}

func main() {
	titles := []string{"Hello World", " Go Channels ", "Worker Pools", "Select Statement"}
	jobs := make(chan Job)
	results := make(chan Result)

	var wg sync.WaitGroup
	for w := 1; w <= 3; w++ {
		wg.Add(1)
		go worker(w, jobs, results, &wg)
	}
	go func() {
		defer close(jobs)
		for i, t := range titles {
			jobs <- Job{ID: i, Name: t}
		}
	}()
	go func() {
		wg.Wait()
		close(results)
	}()

	slugs := make([]string, len(titles))
	for r := range results {
		slugs[r.ID] = r.Slug
	}
	for i, s := range slugs {
		fmt.Printf("%d %s\n", i, s)
	}
	fmt.Println("processed:", len(slugs))
}

Quick quiz 1 / 3

A select has case <-a: and case <-b:, and both a and b already hold a value. Which case runs?

Quick quiz 2 / 3

Three workers send to an unbuffered results channel. main calls wg.Wait(), then close(results), then ranges over results. What happens?

Quick quiz 3 / 3

What does adding a default case to a select change?

What to remember

  • select runs whichever channel case is ready and picks randomly when several are.
  • time.After gives a timeout and default gives a non-blocking check; default inside a loop can spin the CPU.
  • Each pipeline stage owns its output and closes it when its input closes.
  • Worker pool: N workers range over jobs, the feeder closes jobs, the closer closes results after wg.Wait.
  • With several workers result order is not guaranteed, so restore it by ID.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.