Garbage collection
Go's garbage collector reclaims heap objects that are no longer reachable. You do not free. You still control how much garbage you create: allocations, leftover slice capacity, and lingering pointers.
Detailed Explanation
When newSession returns a *Session and no variable still points at it, the collector can reuse that memory. The GC is concurrent: it marks reachable objects while the program runs, then sweeps. You do not stop the world for a long time on modern Go, but you do pay CPU and you do see latency spikes if you allocate huge amounts in a short window.
Reachability is the rule. A global, a stack root, or a pointer from another live object keeps a value alive. A goroutine blocked on a channel keeps the function's locals (and what they point at) alive. A slice header that points at a 10 MiB array keeps the array, even if len is 1.
GOGC and GOMEMLIMIT. GOGC=100 (default) aims to run a cycle after the heap grows by about 100% from the live size. Lower GOGC collects more often (less memory, more CPU). GOMEMLIMIT (Go 1.19+) sets a soft memory cap the GC tries to respect. Do not set GOGC=off in a server unless you have a hard reason and a memory limit.
runtime.GC() forces a cycle. Use it in tests and benchmarks that measure after cleanup, not in a request handler.
What it costs. Allocation rate drives GC work. A handler that makes a large map per request creates garbage even if the live set is small. Reuse (sync.Pool, sized buffers, pooling structs) is an allocation-rate fix, not a way to hide leaks. A real leak is a growing live set: forgotten goroutines, global maps, unbounded caches.
Code Examples
package main
import "runtime"
func main() {
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
_ = ms.HeapAlloc
runtime.GC() // for tests / benchmarks, not per request
}func leak(cache map[string][]byte, key string, buf []byte) {
cache[key] = buf[:1] // still holds cap(buf) bytes
}Common Gotchas
A tiny live slice can pin a huge array
copy if you store a window.
Finalizers (`runtime.SetFinalizer`) are not destructors
they run at an unspecified time and are easy to get wrong. Prefer `defer Close`.
Cgo memory is not Go-heap memory
you still `C.free` what you `C.malloc`.
`GOGC=off` without a memory limit grows the heap without bound
`GOGC=off` without a memory limit grows the heap without bound