Chapter 20: Go
Go is the language this curriculum reaches for when a service has to be simple to read, cheap to run, and correct under concurrency. Its design is deliberately small: a garbage collector so you never write free, structural interfaces so types satisfy contracts without declaring it, goroutines and channels so concurrent code reads like sequential code, and explicit error values so every failure path is visible in the source. The exercises in this chapter are chosen to make you lean on each of those choices until you can say why Go made it.
Concepts from other sections (7)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- goroutine: a function running concurrently, scheduled by the Go runtime. Read more: 1.6 Go: packages, interfaces, goroutines, channels, context, net/http, testing
- Condition variable: a primitive that lets a thread sleep until another thread signals that shared state may have changed. Read more: 18.7 Thread pool
- Worker pool: stateless processes that long-poll a durable queue, execute tasks, and report results; because all state lives in the queue or engine, workers can crash, deploy, and autoscale freely. Read more: Chapter 7: Durable Orchestration and Workers in Systems Engineering
- Fan-in / fan-out: the number of inputs feeding one output, and the number of outputs fed by one input. Read more: 13.4 Variance propagation and initialization in Mathematics
- graceful shutdown: stop accepting, let in-flight work finish within a bound, then exit 0. Read more: 1.9 Async Rust and tokio: futures, tasks, channels, cancellation, hyper
- Token bucket: a counter capped at that refills at per minute and admits a request when it holds the request’s cost. Read more: 10.2 Rate Limiting: RPM Token Buckets and TPM Reserve/Settle in Software Engineering
- RPC: a remote call presented as a local function call through a generated stub. Read more: Chapter 3: RPC and Protocols in Systems Engineering
The chapter is a set of exercise briefs rather than worked solutions. Each brief names a classic system to build and the language features it forces you to use. Several of them are the same problem that a section of AI Engineering or Algorithms solves in full, and for those the brief links to that section, so you can reason through your own design first and then compare it with a complete, tested one.
Learning objectives
- Describe Go’s memory model, type system, error handling, and concurrency primitives, and say what each trades away.
- Apply the core Go idioms (accept interfaces, return structs; explicit error checks;
contextpropagation;defercleanup) when designing a small system.- Choose between channels and
syncprimitives for a given concurrency problem and justify the choice.- Reason through the design of each exercise before reading the matching worked solution elsewhere in the books.
Before you begin
Section titled “Before you begin”You should be comfortable writing a small Go program, running go test, and reading a function signature with channels in it. If you are not, read Go: packages, interfaces, goroutines, channels, context, net/http, testing in Programming and Algorithms first. The concurrency exercises also assume the vocabulary of locks, condition variables, and cancellation that the systems chapters of the books build up.
The language in brief
Section titled “The language in brief”Go manages memory with a garbage collector. Values are stack-allocated by default, and the compiler’s escape analysis moves them to the heap only when a reference outlives the function. You get pointers, but no pointer arithmetic, so the class of bugs that the C chapter spends its time on simply cannot be written.
The type system is static and structural. An interface is satisfied implicitly: any type with the right method set implements it, with no implements clause. Generics arrived in Go 1.18 and are constrained by interfaces, such as cmp.Ordered for types that support <.
Errors are ordinary values of the error interface, returned alongside results. There are no exceptions. You inspect wrapped errors with errors.Is and errors.As, and the price of that visibility is the familiar if err != nil after every call that can fail.
Concurrency is built into the language: goroutines are cheap threads scheduled by the runtime, channels pass values between them, select waits on several channel operations at once, the sync package supplies mutexes, wait groups, and sync.Once, and context.Context carries cancellation and deadlines across call chains. The toolchain is go build, go test, and go vet, with dependencies declared in go.mod. The exercises target Go 1.22 or later.
Idioms to practise
Section titled “Idioms to practise”These are the habits the exercises reward. Each one is short to state and takes practice to apply well.
- Accept interfaces, return structs. Callers can pass anything that fits, and you keep the freedom to add methods to what you return.
if err != nil. Check every error explicitly, at the point it happens.- Table-driven tests with the
testingpackage: one slice of cases, one loop. - Thread
context.Contextthrough every call chain that can block or be cancelled. - Give channels a direction in function signatures (
chan<-,<-chan) so the compiler enforces who sends and who receives. - Embed for composition instead of reaching for inheritance.
deferfor cleanup. Deferred calls run in last-in, first-out order when the function returns.
In this chapter
Section titled “In this chapter”The briefs are listed below, ordered by concept rather than by difficulty, so choose by the difficulty rating (1 is easiest, 5 hardest) rather than by number. Worked Go solutions for these exercises have not been written yet; where a full solution of the same problem exists elsewhere in the books, the last column links to it.
| # | Exercise | Concepts | Difficulty (1-5) | Worked elsewhere |
|---|---|---|---|---|
| 01 | Concurrent web crawler | Goroutines, channels, sync.WaitGroup, rate limiting | 3 | RAG Ingest: Crawler, Chunker, Embedder, and Store |
| 02 | In-memory key-value store | sync.RWMutex, interfaces, HTTP handler | 2 | Response cache: LRU, TTL, singleflight, and tenant-scoped keys |
| 03 | Worker pool | Bounded concurrency, context cancellation | 3 | The task protocol and workers |
| 04 | Generic sorted set | Generics, type constraints, cmp.Ordered | 3 | Durable timers |
| 05 | Log-structured storage | io.Reader/Writer, binary encoding, file I/O | 4 | The append-only event log |
| 06 | Pub/sub message broker | Channels, fan-out, select, graceful shutdown | 3 | The task queue |
| 07 | Rate limiter (token bucket) | time.Ticker, atomic operations, middleware | 2 | Rate Limiting: RPM Token Buckets and TPM Reserve/Settle |
| 08 | Raft consensus (simplified) | State machines, RPC, leader election | 5 | Raft high availability for the durable log |
| 09 | Dependency injection container | Reflection, interfaces, sync.Once | 3 | |
| 10 | gRPC service and client | Protocol buffers, streaming, interceptors | 4 | The task protocol and workers |
All of the linked sections are in AI Engineering, where the problem is solved as part of a larger platform rather than in isolation. Read the brief, sketch your own design, and only then open the worked version.
Key terms
Section titled “Key terms”- Escape analysis: a compiler pass that keeps a value on the stack unless a reference to it can outlive the function, in which case the value is moved to the heap; Go and the JVM use it to reduce garbage-collector work.
- Errors as values: reporting failure by returning an ordinary error value alongside the result, as Go’s
errorinterface does, instead of throwing an exception; every failure path is then an explicit check such asif err != nil. - Accept interfaces, return structs: the Go guideline to take parameters as small interfaces, so callers can pass anything that fits, and to return concrete types, so methods can be added later without breaking callers.
- Table-driven test: a test written as a slice of input and expected-output cases run by one loop, so adding a case is one line; the standard style of Go’s
testingpackage. - Deferred call: a function call scheduled with Go’s
deferto run when the surrounding function returns; deferred calls run in last-in, first-out order, which makes them the place for cleanup.
Further reading
Section titled “Further reading”- A Tour of Go: free and interactive.
- Effective Go: free, and essential reading.
- Go standard library: the API documentation.
- Go Blog: official articles.
- The Go Programming Language by Donovan and Kernighan: the comprehensive book.