Brainbotox · Lessons · Exams

Advanced Go: Runtime, Memory, Concurrency Patterns, Performance

by lazizanie · Programming · Go · English

Advanced Go for senior developers: the scheduler, escape analysis and the garbage collector, slice and map internals, concurrency patterns, profiling with pprof, reflection and unsafe.

Study this lesson with its quizzes on Brainbotox →

The Go scheduler: goroutines, the GMP model and preemption

The Go runtime multiplexes many goroutines onto a small number of operating system threads with a user-space scheduler known as the GMP model. This is why a program can run hundreds of thousands of goroutines.

G, M and P

LetterIsRole
GGoroutineThe code to run, with its own small stack
MMachineAn OS thread
PProcessorA scheduling context with a local run queue; an M needs a P to run Go code

The number of Ps is GOMAXPROCS, by default the number of CPU cores available. It limits how many goroutines execute Go code in parallel.

How work is distributed

  • Each P has a local run queue; there is also a global queue.
  • Work stealing: a P with an empty queue steals half of another P's queue.
  • When a goroutine blocks in a system call, its M is detached and the P is handed to another M, so other goroutines keep running.
  • Network I/O uses the netpoller (epoll, kqueue, IOCP): a goroutine waiting on a socket is parked without holding a thread.

Goroutine stacks

A goroutine starts with a stack of a few kilobytes that grows and shrinks on demand by copying. An OS thread typically reserves megabytes. That difference is what makes goroutines cheap.

Preemption

Since Go 1.14 the scheduler is asynchronously preemptive: a goroutine that runs a tight loop without function calls can still be interrupted, so it cannot starve the others or block the garbage collector.

What blocks and what does not

OperationEffect
Channel operation, mutex, time.Sleep, network I/OParks the goroutine; the thread runs another one
Blocking system call or cgo callOccupies an OS thread for its duration
Inspect scheduling with GODEBUG=schedtrace=1000 or the execution tracer (go tool trace).

Check yourself

  1. In the GMP model, what is a P?
  2. What does GOMAXPROCS control?
  3. What is work stealing?
  4. Why are goroutines much cheaper than OS threads?
  5. Since Go 1.14, a goroutine in a tight loop without function calls can be preempted.
  6. What happens to a goroutine waiting for network data?

Take the quiz on Brainbotox

Go memory: escape analysis and the garbage collector

The Go compiler decides with escape analysis whether each value lives on the goroutine stack or on the heap, and a concurrent mark-and-sweep garbage collector reclaims the heap.

Escape analysis

func onStack() int {
    x := 42
    return x          // x stays on the stack
}
func escapes() *int {
    x := 42
    return &x         // x escapes to the heap: it outlives the function
}

See the decisions with go build -gcflags=-m. Common causes of escape: returning a pointer, storing a value in an interface, capturing it in a closure that outlives the function, or sending a pointer on a channel.

Stack allocation is nearly free and needs no GC. Heap allocation costs time now and GC work later. Reducing allocations is the main lever for Go performance.

The garbage collector

PropertyGo's GC
AlgorithmTri-color mark and sweep
ConcurrentYes: marking runs alongside the program, with very short stop-the-world pauses
GenerationalNo
Compacting (moves objects)No

A write barrier keeps marking correct while the program modifies pointers.

Tuning

  • GOGC (default 100): a new cycle starts when the heap has grown by that percentage over the live heap left by the previous cycle. Higher means fewer collections and more memory.
  • GOMEMLIMIT: a soft memory limit for the runtime, useful in containers.

Reducing allocations

var bufPool = sync.Pool{
    New: func() any { return new(bytes.Buffer) },
}
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
defer bufPool.Put(b)
  • Preallocate: make([]T, 0, n).
  • Reuse buffers with sync.Pool (the GC may empty the pool at any time).
  • Prefer values to pointers for small structs.
  • Use strings.Builder instead of += in loops.

Check yourself

  1. What does escape analysis decide?
  2. Which command shows the compiler's escape decisions?
  3. Which description fits Go's garbage collector?
  4. What does raising GOGC from 100 to 200 do?
  5. What is true of objects kept in a sync.Pool?
  6. Returning the address of a local variable is unsafe in Go because the stack frame is destroyed.

Take the quiz on Brainbotox

Go slices, maps, strings and interfaces under the hood

A slice is a three-word header (pointer, length, capacity), a string is a two-word header (pointer, length), and an interface is a two-word pair (type, data). Knowing these layouts explains most subtle Go bugs.

Slice header and aliasing

a := []int{1, 2, 3, 4}
b := a[:2]              // len 2, cap 4, same array
b = append(b, 99)       // fits in capacity: overwrites a[2]!
fmt.Println(a)          // [1 2 99 4]
c := a[:2:2]            // full slice expression: cap limited to 2
c = append(c, 7)        // must reallocate: a is untouched
Passing a slice copies the header only. The callee can change elements, but an append inside it is invisible to the caller unless the new slice is returned.

Memory retention

A small slice of a huge array keeps the whole array alive. Copy the part you need: small := slices.Clone(big[:10]).

Growth

When capacity is exceeded, append allocates a larger array (about double for small slices, a smaller factor for large ones) and copies the elements.

Maps

  • A map value is a pointer to a hash table, so passing a map shares it.
  • Maps are not safe for concurrent use. Concurrent writes cause a fatal error that cannot be recovered. Protect with a mutex or use sync.Map for specific patterns.
  • You cannot take the address of a map element, and m[k].field = v does not compile for struct values.
  • A map never shrinks its bucket memory when keys are deleted.

Strings and byte slices

Strings are immutable. Converting between string and []byte normally copies the data. Build strings with strings.Builder, which appends into one growing buffer.

Interface values

Word 1Word 2
Type information (and method table)Pointer to the data

Storing a non-pointer value in an interface usually allocates. Method calls through an interface are indirect and cannot be inlined in general. An interface is nil only when both words are nil.

Check yourself

  1. What does a slice header contain?
  2. a := []int{1,2,3,4}; b := a[:2]; b = append(b, 99). What is a[2]?
  3. What does the full slice expression a[:2:2] do?
  4. What happens on concurrent writes to a plain Go map?
  5. Why can a 10-element slice keep 1 GB of memory alive?
  6. Converting a string to []byte normally shares the same memory without copying.

Take the quiz on Brainbotox

Go concurrency patterns: worker pools, pipelines and leaks

Production Go code combines goroutines, channels and context into a few recurring patterns: worker pool, pipeline, fan-out and fan-in, and bounded concurrency. Each must guarantee that every goroutine eventually exits.

Worker pool

jobs := make(chan Job)
results := make(chan Result)
var wg sync.WaitGroup
for w := 0; w < 8; w++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        for j := range jobs { results <- process(j) }
    }()
}
go func() { wg.Wait(); close(results) }()

Bounded concurrency with a semaphore

sem := make(chan struct{}, 10)     // at most 10 at a time
for _, u := range urls {
    sem <- struct{}{}
    go func() {
        defer func() { <-sem }()
        fetch(u)
    }()
}

errgroup

g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10)
for _, u := range urls {
    g.Go(func() error { return fetch(ctx, u) })
}
if err := g.Wait(); err != nil { ... }   // first error; ctx is cancelled

golang.org/x/sync/errgroup waits for a group, returns the first error and cancels the shared context so the others stop early.

Goroutine leaks

func first(urls []string) string {
    ch := make(chan string)            // unbuffered
    for _, u := range urls {
        go func() { ch <- fetch(u) }() // losers block forever
    }
    return <-ch
}
A goroutine blocked forever on a channel is never collected: it leaks its stack and everything it references. Fixes here: a buffered channel of size len(urls), or a select on ctx.Done().
Before starting a goroutine, know how it will stop. Every blocking operation should also watch ctx.Done().

Other rules

  • Only the sender closes a channel, and only once.
  • Since Go 1.22, each loop iteration has its own copy of the loop variable, so closures in a loop capture the right value. Older code needed v := v.
  • For a simple counter or flag, use sync/atomic (atomic.Int64) instead of a channel.
  • Use a mutex to protect state and channels to transfer ownership or signal events.

Check yourself

  1. What is a goroutine leak?
  2. How does a buffered channel act as a semaphore?
  3. What does errgroup.WithContext provide?
  4. Who should close a channel?
  5. What changed for loop variables in Go 1.22?
  6. In a worker pool, how do workers know there is no more work?

Take the quiz on Brainbotox

Go profiling and performance: pprof, benchmarks and tracing

Go ships with a sampling profiler (pprof), a benchmark framework and an execution tracer, so performance work starts from measurements and not from guesses.

Benchmarks

func BenchmarkJoin(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        strings.Join(parts, ",")
    }
}
go test -bench=Join -benchmem -count=10 > new.txt
benchstat old.txt new.txt

The framework chooses b.N so the run lasts long enough to be stable. -benchmem shows bytes and allocations per operation. Compare runs with benchstat, which reports whether a difference is statistically significant.

pprof profiles

ProfileAnswers
CPUWhere is time spent?
HeapWhat is in memory, and who allocates?
GoroutineWhat are all goroutines doing? (finds leaks)
Block, mutexWhere do goroutines wait?
import _ "net/http/pprof"     // exposes /debug/pprof/ on the default mux
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
go test -cpuprofile cpu.out -bench=.
go tool pprof -http=:8080 cpu.out     // flame graph in the browser

The execution tracer

go tool trace shows scheduling, GC pauses and blocking over time. Use it for latency problems that a CPU profile does not explain.

Common wins

  • Fewer allocations: preallocate slices and maps, reuse buffers, avoid needless []byte and string conversions.
  • Avoid interface conversions and reflection in hot loops.
  • Order struct fields from largest to smallest to reduce padding.
  • False sharing: variables written by different cores on the same cache line slow each other down. Pad them apart.
  • Small functions are inlined by the compiler; huge ones are not.
Profile first, change one thing, benchmark again. Most programs have one or two hot spots, and optimising anything else is wasted effort.
Profile-guided optimisation: place a CPU profile from production as default.pgo in the main package and the compiler uses it to inline and lay out hot code better.

Check yourself

  1. In a Go benchmark, what is b.N?
  2. Which pprof profile helps find goroutine leaks?
  3. What does -benchmem add to benchmark output?
  4. What is benchstat for?
  5. What is false sharing?
  6. Which tool shows scheduling delays and GC pauses along a timeline?

Take the quiz on Brainbotox

Go reflection, unsafe, cgo and build tooling

Reflection inspects types and values at run time, unsafe bypasses the type system, and cgo calls C code. All three are powerful escape hatches with real costs.

Reflection

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age,omitempty"`
}
t := reflect.TypeOf(User{})
for i := 0; i < t.NumField(); i++ {
    f := t.Field(i)
    fmt.Println(f.Name, f.Tag.Get("json"))
}
v := reflect.ValueOf(&u).Elem()
v.FieldByName("Age").SetInt(40)    // needs an addressable value

Struct tags are strings read by reflection; encoding/json uses them. Reflection can only set exported fields of an addressable value (reached through a pointer).

Reflection is slow, allocates, and turns compile-time errors into run-time panics. Prefer generics or code generation where possible.

unsafe

size := unsafe.Sizeof(User{})
p := unsafe.Pointer(&x)

unsafe.Pointer converts between pointer types and to uintptr. Code using it is outside the Go compatibility promise and can break memory safety. A uintptr is just a number: the GC does not treat it as a reference, so the object may be freed.

cgo

  • A call from Go to C costs far more than a Go function call, and blocks an OS thread.
  • It complicates cross-compilation and static builds. CGO_ENABLED=0 gives a pure Go binary.
  • Go pointers passed to C must follow strict rules, because the GC does not see C memory.

Build tooling

FeatureUse
//go:build linux && amd64Compile a file only for some platforms or tags
GOOS=linux GOARCH=arm64 go buildCross-compile
//go:embed static/*Embed files in the binary
//go:generate cmdRun code generators with go generate
-ldflags "-X main.version=1.2"Set a string variable at link time
Order of preference for flexible code: plain interfaces, then generics, then code generation, then reflection, and unsafe last.

Check yourself

  1. What are struct tags used for?
  2. What is required to set a struct field through reflection?
  3. Why is holding an address in a uintptr dangerous?
  4. What is a cost of cgo?
  5. Which directive embeds files into the compiled binary?
  6. How do you cross-compile a Go program for Linux on ARM64?

Take the quiz on Brainbotox