Advanced Go: Runtime, Memory, Concurrency Patterns, Performance
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
| Letter | Is | Role |
|---|---|---|
| G | Goroutine | The code to run, with its own small stack |
| M | Machine | An OS thread |
| P | Processor | A 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
What blocks and what does not
| Operation | Effect |
|---|---|
Channel operation, mutex, time.Sleep, network I/O | Parks the goroutine; the thread runs another one |
| Blocking system call or cgo call | Occupies an OS thread for its duration |
GODEBUG=schedtrace=1000 or the execution tracer (go tool trace).Check yourself
- In the GMP model, what is a P?
- What does GOMAXPROCS control?
- What is work stealing?
- Why are goroutines much cheaper than OS threads?
- Since Go 1.14, a goroutine in a tight loop without function calls can be preempted.
- What happens to a goroutine waiting for network data?
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.
The garbage collector
| Property | Go's GC |
|---|---|
| Algorithm | Tri-color mark and sweep |
| Concurrent | Yes: marking runs alongside the program, with very short stop-the-world pauses |
| Generational | No |
| 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.Builderinstead of+=in loops.
Check yourself
- What does escape analysis decide?
- Which command shows the compiler's escape decisions?
- Which description fits Go's garbage collector?
- What does raising GOGC from 100 to 200 do?
- What is true of objects kept in a sync.Pool?
- Returning the address of a local variable is unsafe in Go because the stack frame is destroyed.
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 untouchedappend 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.Mapfor specific patterns. - You cannot take the address of a map element, and
m[k].field = vdoes 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 1 | Word 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
- What does a slice header contain?
- a := []int{1,2,3,4}; b := a[:2]; b = append(b, 99). What is a[2]?
- What does the full slice expression a[:2:2] do?
- What happens on concurrent writes to a plain Go map?
- Why can a 10-element slice keep 1 GB of memory alive?
- Converting a string to []byte normally shares the same memory without copying.
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 cancelledgolang.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
}len(urls), or a select on ctx.Done().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
- What is a goroutine leak?
- How does a buffered channel act as a semaphore?
- What does errgroup.WithContext provide?
- Who should close a channel?
- What changed for loop variables in Go 1.22?
- In a worker pool, how do workers know there is no more work?
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
| Profile | Answers |
|---|---|
| CPU | Where is time spent? |
| Heap | What is in memory, and who allocates? |
| Goroutine | What are all goroutines doing? (finds leaks) |
| Block, mutex | Where 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
[]byteandstringconversions. - 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.
default.pgo in the main package and the compiler uses it to inline and lay out hot code better.Check yourself
- In a Go benchmark, what is b.N?
- Which pprof profile helps find goroutine leaks?
- What does -benchmem add to benchmark output?
- What is benchstat for?
- What is false sharing?
- Which tool shows scheduling delays and GC pauses along a timeline?
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 valueStruct tags are strings read by reflection; encoding/json uses them. Reflection can only set exported fields of an addressable value (reached through a pointer).
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=0gives a pure Go binary. - Go pointers passed to C must follow strict rules, because the GC does not see C memory.
Build tooling
| Feature | Use |
|---|---|
//go:build linux && amd64 | Compile a file only for some platforms or tags |
GOOS=linux GOARCH=arm64 go build | Cross-compile |
//go:embed static/* | Embed files in the binary |
//go:generate cmd | Run code generators with go generate |
-ldflags "-X main.version=1.2" | Set a string variable at link time |
unsafe last.Check yourself
- What are struct tags used for?
- What is required to set a struct field through reflection?
- Why is holding an address in a uintptr dangerous?
- What is a cost of cgo?
- Which directive embeds files into the compiled binary?
- How do you cross-compile a Go program for Linux on ARM64?