Go manages memory for you with a garbage collector and growable goroutine stacks, but it does not manage every resource. Files, sockets, database connections, goroutines and timers are your responsibility: acquire them, bound how many you hold, release them with defer, and let a context.Context cancel work that is no longer needed.
This guide explains how Go allocates and reclaims memory, how it schedules CPU, and the practices that keep file descriptors, connections and goroutines under control in production services. Examples target Go 1.24 and later.
Go allocates values either on a goroutine stack or on the heap. The compiler's escape analysis decides which: a value that does not outlive its function stays on the stack and is freed automatically on return, while a value whose address escapes (returned pointer, stored in an interface or a long-lived structure, captured by a goroutine) goes on the heap.
Heap memory is reclaimed by a concurrent mark-sweep garbage collector. You influence it through two settings:
| Setting | Meaning | Typical use |
|---|---|---|
GOGC | Heap growth percentage before the next cycle (default 100) | Raise it to spend memory for less GC CPU |
GOMEMLIMIT | Soft limit on total Go memory (Go 1.19+) | Set to about 90 percent of a container memory limit |
You can read live numbers with runtime/metrics or runtime.ReadMemStats, as below. runtime.GC() forces a cycle, which is useful in tests and demos but should not be called in production code paths.
Each goroutine starts with a small stack (a few kilobytes). When it needs more, the runtime allocates a larger contiguous stack and copies the old one into it. Older Go releases (before 1.3) used segmented stacks, but modern Go does not. You never size stacks yourself, though extremely deep recursion can still hit the maximum stack size (1 GB by default on 64-bit systems) and crash the program. Prefer iteration for unbounded depth.
The runtime scheduler runs goroutines on a pool of OS threads, with at most GOMAXPROCS threads executing Go code at once. Since Go 1.25 the default respects container CPU limits. Goroutines blocked on channels, locks or network I/O are parked cheaply and do not hold a thread.
The practical rule is to bound concurrency yourself. Starting one goroutine per item of unbounded input can exhaust memory long before it exhausts CPU. errgroup with a limit is the shortest safe pattern:
Since Go 1.22 each loop iteration has its own id variable, so capturing it in the closure is safe.
The garbage collector eventually closes an unreferenced *os.File through a finalizer, but you cannot predict when, and each open file consumes a file descriptor limited by ulimit -n. Close resources explicitly and immediately after a successful open:
Three habits prevent most leaks:
defer x.Close() right after the error check, not at the end of the function.resp.Body from http.Client calls and read it to completion if you want the connection reused.defer inside a long loop; wrap the body in a function so each iteration releases its resource.Expensive resources should be pooled and capped. The standard database/sql package already pools connections; configure it rather than leaving the defaults:
For HTTP clients, reuse one http.Client and its Transport for the whole process and set timeouts. For reusable buffers on hot paths, use sync.Pool. Always give servers and clients explicit timeouts so a slow peer cannot hold resources forever.
A context.Context carries cancellation and deadlines through every layer. Pass it as the first argument, derive it with context.WithTimeout, and always call the returned cancel function, otherwise the timer and its goroutine stay alive until the deadline.
/debug/pprof/goroutine?debug=1 over time; a count that only grows is a leak.pprof and compare them with -base./proc/<pid>/fd and watch the trend.go test -race and consider a goroutine-leak checker in integration tests.No. The garbage collector frees unreachable heap memory. You must still release non-memory resources such as files, connections and locks.
No. Closing only signals receivers that no more values will arrive. The channel is collected when nothing references it.
No. Finalizers run at an unspecified time, if at all before exit, so descriptors can run out first. Use defer Close().
Hundreds of thousands are practical because stacks start small, but the real limit is the memory each goroutine holds and the work it does, so bound them.
Go automates heap memory and stack growth, but you manage everything else. Close resources with defer, pool and cap connections, bound goroutines with errgroup or a semaphore, propagate context for cancellation, and use GOMEMLIMIT and profiling to keep memory predictable.