
Why Go for agents, from the book’s evidence
Where Go’s standard tools did an agent’s work in the book’s code, with numbers, and what Go costs.
On the agent compass The whole loop, all four stagesVery little of an agent is machine learning. The model lives behind an HTTP API; the program you write sends requests, waits, runs tools, keeps a budget, and decides when to stop. That is the kind of program Go was built for, and the companion code, with its measurements, makes the case better than a list of language features would.
Below are the places where Go fits that job, most with numbers from recorded runs, and then the costs of choosing Go, since a fair comparison names both.
One value carries the deadline and the reason
Every call in the companion agent takes a ctx context.Context first.
It carries cancellation and deadlines through the HTTP request, the stream reader, and the go test command a tool starts, so a Ctrl-C reaches all of them without any of them knowing about the others.
A context can also carry why it was cancelled. That is used in three places, each of which needed the reason and not only the fact:
- Stop reasons. A cancelled run returns an error that holds both
context.Canceledand its cause, so a caller learns why the run ended as well as that it did. - Retries. If one model call runs out of its own time limit, try it again; if the caller’s whole deadline has passed, give up. Both fail with
context.DeadlineExceeded, so the call’s limit is set withcontext.WithTimeoutCauseto tell them apart. The classifier, the function that decides whether an error is worth retrying (Classifyinch12/agent/classify.go), checks the caller’s context first and retries only a timeout of the call’s own. - Shutdown. A platform stopping the service sends it SIGTERM, the signal that asks a process to exit, and kills the process after a grace period if it hasn’t. The service cancels the run with
ErrShutdownas the cause, and the loop saves its state on the way out.
Here is the shutdown, from the companion code:
// withShutdown returns a context that the first SIGINT or SIGTERM
// cancels with agent.ErrShutdown as its cause: the run stops, saves
// where it was, and the program exits. A second signal exits at once.
// stop releases the signals and ends the goroutine that waits for them.
func withShutdown(parent context.Context) (ctx context.Context,
stop func()) {
ctx, cancel := context.WithCancelCause(parent)
sigs := make(chan os.Signal, 2)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
done := make(chan struct{})
go func() {
select {
case <-sigs:
cancel(agent.ErrShutdown)
case <-done:
return
}
select {
case <-sigs:
os.Exit(130)
case <-done:
}
}()
return ctx, func() {
signal.Stop(sigs)
close(done)
cancel(nil)
}
}
Cancelling rather than waiting was a measured choice.
Kubernetes waits 30 seconds by default and docker stop waits 10.
Across recorded live runs, the median model call took 2.35 seconds, but 9 of 209 calls ran past 10 seconds and the slowest took 27.5, so waiting for the call in progress could have used up the whole grace period.
Goroutines, with tools that check them
Running a reply’s tool calls side by side is a few lines with sync.WaitGroup.Go: one goroutine per call, each writing only its own slot of the results slice.
The part worth having is the checking.
go test -race runs on every test in the companion code, so two goroutines writing the same variable at once (a data race) would fail a test run instead of waiting to be noticed in review.
A goroutine that waits forever on a channel nothing will ever use again is a leak, and Go 1.27’s goroutineleak profile finds such goroutines.
The companion code tests that profile with a fan-in (several goroutines sending their results into one channel) whose two senders leak on purpose, and a test that catches both.
The measurements also say where concurrency didn’t help. Replaying one recorded run’s 87 tool calls, the 60 read-only calls added up to about a seventh of a second, so running them in parallel saved milliseconds; the time went to model calls and to the two tools that compile code. And running 23 agents four at a time finished no sooner than one agent on the same batch (see measured mistakes). Goroutines make parallel work cheap to write and safe to check; whether it pays is a separate measurement.
The standard library covers the wire
As long as it calls the API with its own client, the companion code’s main module has no dependencies at all: net/http for the API, encoding/json/v2 for the format, bufio for the stream, testing and httptest for offline tests.
Every byte the agent sends is something you wrote and can print.
A recorded check put that to the test: the same request, the last one of a recorded run, encoded with the hand-written client and with OpenRouter’s Go SDK. The two came to 55,162 and 55,227 bytes, the same content spelled almost the same way. What writing the client yourself buys is sight of every byte it sends, so when a provider’s behavior changes you can tell whether your request changed too.
One static binary
The finished agent builds to one binary with nothing to install beside it, which suits both a command people download and a container that a platform starts and stops. The same task built three ways, for linux/amd64: 10.6 MB on the hand-written parts, and 25.4 MB and 29.3 MB on two agent frameworks. The comparison is careful about what that means: for a long-running server the difference rarely counts, and for a downloaded tool or a function started cold on each request it can.
Runtime speed rarely matters for an agent. The median model call in the recorded runs took 2.35 seconds while tools took milliseconds, so the case for Go rests on clarity, safety, and tooling, and raw speed hardly enters into it.
Fast builds, on every turn
A coding agent builds and tests code on most turns, so the toolchain’s speed is part of every run’s wall time.
In one recorded run’s trace, a single run_tests call, which builds the service and runs its tests with go test, took 4.8 seconds, while the read-only tools took milliseconds each.
Go compiles quickly and caches build results, so the second run of go test over unchanged packages is much faster than the first.
The infrastructure is already Go
Agents that operate infrastructure work in Go’s home territory. Kubernetes, Docker’s engine, Terraform, and Prometheus are written in Go, and AWS, Google Cloud, and Azure publish official Go SDKs. A tool that talks to those systems can call their own Go libraries instead of shelling out to a command-line tool and parsing its text.
A small language keeps the harness reviewable
The harness is the code that decides what the model may do: which tools exist, what they may touch, when a person must approve.
Go has 25 keywords (the Go specification lists them), one formatting style enforced by gofmt, and few ways to write the same thing.
That makes it practical for the people responsible for an agent’s safety to read all of its harness code.
What Go costs here
These belong in any argument for Go:
- A smaller agent ecosystem. Python has more agent libraries, and research code and provider examples often appear there first.
- You may build parts that exist elsewhere. This agent writes its own loop, client, and safety code; the version of the agent used for the framework comparison has 5,351 lines of loop, client, and safety code that a framework would partly replace (about 1,500 of them are safety code neither framework tested provides), and the comparison maps five Go frameworks against the parts you built.
- Some libraries trail a Go release. On Go 1.27, one framework’s JSON library warned at startup that it supported Go only up to 1.26 and fell back to
encoding/json. - Rust is a genuine alternative. Rust frees memory deterministically with no garbage collector and its compiler rejects data races before the program runs, where Go finds races at run time with the race detector; for an agent, which spends most of its time waiting on a model, those strengths matter less than they do for a latency-critical service, but a team already fluent in Rust loses little by staying there.
None of that argues against other languages. It says what Go makes cheap for an agent: carrying the reason a call stopped, running work side by side under a race checker, keeping every byte visible, and shipping one binary that stops on time. Whether those matter more than a larger ecosystem depends on your agent, and the ecosystem comparison is a place to start weighing it.
func withShutdown(parent context.Context) (ctx context.Context,
stop func())
withShutdown returns a context that the first SIGINT or SIGTERM cancels with agent.ErrShutdown as its cause: the run stops, saves where it was, and the program exits.
withShutdown returns a context that the first SIGINT or SIGTERM cancels with agent.ErrShutdown as its cause: the run stops, saves where it was, and the program exits. func withShutdown(parent context.Context) (ctx context.Context, stop func()). In ch15/durable.go, line 35.
var parent context.Context
var parent context.Context. In ch15/durable.go, line 35.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
var cancel context.CancelCauseFunc
var cancel context.CancelCauseFunc. In ch15/durable.go, line 37.
func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc].
WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc]. func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc). Documented at pkg.go.dev, context.WithCancelCause.
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only).
The make built-in function allocates and initializes an object of type slice, map, or chan (only). func make(t Type, size ...IntegerType) Type. Documented at pkg.go.dev, builtin.make.
package os ("os")
Package os provides a platform-independent interface to operating system functionality.
Package os provides a platform-independent interface to operating system functionality. package os ("os"). Documented at pkg.go.dev, os.
type Signal interface {
String() string
Signal() // to distinguish from other Stringers
}
A Signal represents an operating system signal.
A Signal represents an operating system signal. type Signal interface { String() string Signal() // to distinguish from other Stringers }. Documented at pkg.go.dev, os.Signal.
package signal ("os/signal")
Package signal implements access to incoming signals.
Package signal implements access to incoming signals. package signal ("os/signal"). Documented at pkg.go.dev, os/signal.
func Notify(c chan<- os.Signal, sig ...os.Signal)
Notify causes package signal to relay incoming signals to c.
Notify causes package signal to relay incoming signals to c. func Notify(c chan<- os.Signal, sig ...os.Signal). Documented at pkg.go.dev, os/signal.Notify.
var Interrupt Signal = syscall.SIGINT
var Interrupt Signal = syscall.SIGINT. Documented at pkg.go.dev, os.Interrupt.
package syscall ("syscall")
Package syscall contains an interface to the low-level operating system primitives.
Package syscall contains an interface to the low-level operating system primitives. package syscall ("syscall"). Documented at pkg.go.dev, syscall.
const SIGTERM = Signal(0xf)
const SIGTERM = Signal(0xf). Documented at pkg.go.dev, syscall.SIGTERM.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch15/agent")
Package agent is the agent loop and the types it works with.
Package agent is the agent loop and the types it works with. package agent ("github.com/blackwell-systems/go-agents-book/code/ch15/agent"). In ch15/agent.
var ErrShutdown = errors.New("agent: shutting down")
ErrShutdown is the cause set on a run's context when the process is asked to stop.
ErrShutdown is the cause set on a run's context when the process is asked to stop. var ErrShutdown = errors.New("agent: shutting down"). In ch15/agent/state.go, line 104.
func Exit(code int)
Exit causes the current program to exit with the given status code.
Exit causes the current program to exit with the given status code. func Exit(code int). Documented at pkg.go.dev, os.Exit.
func Stop(c chan<- os.Signal)
Stop causes package signal to stop relaying incoming signals to c.
Stop causes package signal to stop relaying incoming signals to c. func Stop(c chan<- os.Signal). Documented at pkg.go.dev, os/signal.Stop.
func close(c chan<- Type)
The close built-in function closes a channel, which must be either bidirectional or send-only.
The close built-in function closes a channel, which must be either bidirectional or send-only. func close(c chan<- Type). Documented at pkg.go.dev, builtin.close.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
var Canceled = errors.New("context canceled")
Canceled is the error returned by [Context.Err] when the context is canceled for some reason other than its deadline passing.
Canceled is the error returned by [Context.Err] when the context is canceled for some reason other than its deadline passing. var Canceled = errors.New("context canceled"). Documented at pkg.go.dev, context.Canceled.
var DeadlineExceeded error = deadlineExceededError{}
DeadlineExceeded is the error returned by [Context.Err] when the context is canceled due to its deadline passing.
DeadlineExceeded is the error returned by [Context.Err] when the context is canceled due to its deadline passing. var DeadlineExceeded error = deadlineExceededError{}. Documented at pkg.go.dev, context.DeadlineExceeded.
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the returned Context when the timeout expires.
WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the returned Context when the timeout expires. func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc). Documented at pkg.go.dev, context.WithTimeoutCause.

