The first time I saw a Go service eat 4 GB of RAM, I did what most people do: I opened top, stared at the number, and assumed I had a memory leak. Two hours of pprof later, the answer was much less dramatic. The service was fine. It was just allocating a lot of short-lived objects, and the garbage collector was doing exactly what it was designed to do: letting the heap grow so it did not have to work too hard.
That day taught me something I wish someone had told me earlier. In Go, memory usage is not a number you read once and judge. It is a negotiation between your allocation rate and the collector’s pacing, and the collector is on your side.
So let me write the explanation I needed back then: what garbage collection is, how Go’s version works under the hood, why it sometimes looks like it is wasting memory, and the small number of things that actually make a difference.
What garbage collection is, in plain words
Every program creates data. Some of it is needed for the whole run: configuration, connection pools, caches. Most of it is temporary: a request body, a decoded JSON struct, a string built for one log line.
In a language like C, you call malloc and later free. Forget the free and you leak. Call it twice and you corrupt the heap. Use the pointer after freeing and you get a bug that appears once a week in production and never on your machine.
A garbage collector takes that job away from you. The runtime periodically asks a simple question: which of these objects can the program still reach? Anything reachable is alive. Everything else is garbage, and its memory can be reused. You never free anything, so you cannot free it wrongly.
Go’s collector is tracing (it follows pointers from roots), non-moving (objects stay where they are), and concurrent (it runs alongside your code). Those three words explain almost all of its behaviour, good and bad, and I will come back to each of them.
How Go’s collector actually works
The core algorithm is called tri-color mark and sweep, and it is easier than the name suggests.
Imagine every object has one of three colors:
- White — not visited yet. At the end, white means garbage.
- Grey — discovered, but its children have not been checked yet.
- Black — discovered, and everything it points to has been checked.
The collector starts by marking the roots grey: global variables, goroutine stacks, and anything else the runtime knows is alive. Then it repeatedly takes a grey object, marks everything it points to grey, and turns the object black. When there are no grey objects left, everything still white is unreachable, and its memory goes back to the allocator.
That is the whole idea. The interesting part is that Go does this while your program keeps running.
The part that makes it concurrent
If the collector is walking the heap while your goroutines are allocating and writing pointers, it can make mistakes. Your code might move a pointer into an object the collector already decided was black. The collector would never look at it again, and you would free memory that is still in use. That is the kind of bug that ends careers.
Go solves this with a write barrier. When the collector is in its concurrent marking phase, every pointer write goes through a tiny piece of runtime code that records the change, so the collector can re-check it. Your program still runs, but pointer writes get slightly more expensive during that window.
This is also why the collector has short stop-the-world phases. There are two, both tiny: one at the start to enable the write barrier and scan the roots, one at the end to disable it and finish up. In modern Go these are typically well under a millisecond, often microseconds, and they are the reason people say Go’s GC “has no long pauses”. It does pause. The pauses are just very short, and the expensive work happens while your code is running.
What a cycle looks like
A full cycle goes roughly like this:
- Mark setup — stop the world briefly, turn on the write barrier.
- Concurrent mark — goroutines and collector work at the same time, using 25% of available CPU by default.
- Mark termination — stop the world briefly, finish marking, turn off the write barrier.
- Sweep — memory of dead objects is reclaimed lazily, mostly as part of allocation.
Notice what is missing: there is no compaction step that moves objects around, and no generational split into young and old. Which brings us to the surprises.
Three design choices, and what they cost you
Go’s collector is non-moving. Objects never move. That sounds like a detail, but it is the reason Go can pass pointers to C, the reason you can take the address of a struct field and rely on it, and the reason slices behave the way they do. A moving collector, like the ones in Java or .NET, gets to compact the heap and keep it tidy. Go gives that up in exchange for a much simpler contract with your code.
It is also non-generational. Many collectors assume most objects die young, so they check the young generation often and the old one rarely. Go does not split the heap that way. Instead, it relies on the fact that short-lived objects usually become garbage before the next cycle, and on the compiler’s escape analysis, which keeps many small objects on the stack entirely so the collector never sees them.
And it is concurrent, which means it competes with your program for CPU. By default the collector is allowed to use about 25% of the CPUs available to the process. On a 4-core machine that is one core doing GC work while three serve requests. On a 64-core machine, that 25% is a lot of cores, which is why some teams set GOMAXPROCS deliberately in containers.
The two knobs that actually matter
Go has been tuned over many releases so that most services never need to touch anything. But two settings are worth knowing.
GOGC: how much the heap may grow
GOGC is a percentage. If the live heap after a cycle is 100 MB and GOGC=100 (the default), the next cycle starts when the heap reaches 200 MB. Setting it to 200 means the heap can double twice as far before the collector runs: less GC work, more memory used.
GOGC=200 go run main.go # collect less often, use more memory
GOGC=50 go run main.go # collect more often, use less memory, more CPU
GOGC=off go run main.go # disable the collector entirely (be careful)
For a batch job that runs for ten minutes and then exits, GOGC=off is a legitimate trick: let the OS reclaim everything when the process dies. For a long-running service, it is a way to get OOM-killed politely.
GOMEMLIMIT: a soft memory ceiling
Since Go 1.19 there is a much better tool for containers: GOMEMLIMIT. It tells the runtime “do not let the heap grow past this”, and the collector responds by working harder as you approach the limit instead of blindly following GOGC.
GOMEMLIMIT=900MiB ./myservice
This is the setting I now add to every containerised Go service. If the container has a 1 GB limit, setting GOMEMLIMIT to around 900 MiB keeps the runtime from waiting for a GOGC trigger that will never come before the OOM killer arrives. It is a soft limit, not a hard cap: if your live data genuinely exceeds it, the collector cannot invent memory. But it turns a class of mysterious OOM kills into a predictable slowdown.
The combination people use in production is GOGC=off plus GOMEMLIMIT, which lets the heap grow freely up to the ceiling and stops wasting CPU on cycles nobody needed. I would not start there, but it is a good end state for a stable service.
What it costs
I am not going to pretend the collector is free. Here is the honest bill.
CPU. Concurrent marking uses CPU. On allocation-heavy services, GC can eat a noticeable slice of your total CPU time. That is the price of never calling free.
Memory headroom. Because the heap is allowed to grow to GOGC percent above live data, a Go service will often use more memory than the live set suggests. This is by design: the collector is trading memory for CPU. A service with 100 MB of live data sitting at 200 MB RSS is not leaking.
Latency jitter. Even with sub-millisecond stop-the-world phases, concurrent marking slows down pointer writes and competes for CPU. For a request handler this is invisible. For a hard real-time system it is disqualifying, which is why that domain uses Rust, C++, or Go with the collector effectively disabled and a very careful allocation strategy.
A less predictable memory profile than manual management. You cannot say exactly when an object’s memory returns. You can say it will be reused eventually. For most software that is fine.
What it gives you
No use-after-free, no double-free, no manual lifetime bugs. That entire category of crash and security vulnerability simply does not exist in ordinary Go code. The number of production incidents this prevents across the industry is hard to overstate.
Simpler code. No ownership annotations, no shared_ptr ceremony, no destructors to reason about. You create a struct, use it, and forget it. The code you read is the logic, not the memory management.
Fast development. The compiler and runtime handle lifetimes for you. New team members cannot get it wrong in a way that only appears under load.
A predictable tail latency for web services. Go’s GC was designed for exactly this: a server holding thousands of connections where a 200 ms pause would be a disaster. The design goal was a collector whose pauses stay small regardless of heap size, and for typical service workloads it delivers.
Safety at the language level. Combined with Go’s type system and bounds checks, the collector is a big part of why Go services tend to fail in boring ways: a panic with a stack trace, not a corrupted heap.
Why your service sometimes looks like it is leaking
This deserves its own section because it causes so many false alarms.
A Go process’s RSS does not fall just because objects died. The runtime keeps memory around to reuse it, because asking the OS for pages is expensive and returning them constantly is wasteful. So a service can sit at 500 MB RSS with 80 MB of live data and be perfectly healthy.
The numbers that matter are the ones in runtime/metrics, or the output of:
GODEBUG=gctrace=1 ./myservice
which prints a line per cycle with heap sizes, pause times, and CPU fraction. Reading it takes ten minutes and saves hours of guessing. Something like gc 42 @12.345s 3%: 0.015+2.1+0.002 ms clock tells you the cycle number, when it happened, the GC CPU percentage, and the pause breakdown.
If you want the real live set, force a collection and read the heap:
var stats runtime.MemStats
runtime.GC() // only for diagnostics, never in a hot path
runtime.ReadMemStats(&stats)
fmt.Printf("live heap: %.1f MB\n", float64(stats.HeapAlloc)/1024/1024)
If HeapAlloc after runtime.GC() keeps climbing over hours, that is a leak. If it stays flat while RSS is high, you are looking at a runtime that is holding reusable memory, which is not a problem to fix.
The habits that actually reduce GC pressure
You cannot tune your way out of allocating too much. The real wins are in the code.
Preallocate when you know the size. make([]T, 0, n) avoids repeated growth and copying. This is the single easiest change and it shows up immediately on allocation-heavy code.
// worse: several reallocations and copies
results := []Order{}
for _, row := range rows {
results = append(results, parse(row))
}
// better: one allocation, exact capacity
results := make([]Order, 0, len(rows))
for _, row := range rows {
results = append(results, parse(row))
}
Stop building strings in loops. s += part allocates a new string every iteration. strings.Builder exists for this, and it is not micro-optimisation when the loop runs a hundred thousand times.
var b strings.Builder
b.Grow(len(items) * 8)
for _, item := range items {
b.WriteString(item)
b.WriteByte(',')
}
result := b.String()
Let escape analysis help you. Small values that never leave a function stay on the stack. Returning a pointer to a local forces it to the heap, which is often necessary but occasionally just a habit. go build -gcflags='-m' tells you which values escape, and reading that output once for a hot function is genuinely educational.
Reuse buffers for hot paths. sync.Pool for byte buffers in HTTP handlers or encoders is the standard pattern. It is not free, it is not always faster, and it is worth measuring before adopting it everywhere.
Watch what your libraries allocate. A JSON library that allocates three times per request makes your GC work three times as hard. This is often the biggest factor and the hardest to notice, because it is not in your code.
Do not hold references you do not need. A large slice kept alive by one small field, a map that only grows, a cache with no eviction policy: these are real leaks from the collector’s point of view, because the objects are technically reachable. runtime.GC() will never clean them up, and no GOGC setting will save you.
When I would not use Go because of GC
Being honest about the limits is part of understanding the tool.
If I am writing audio processing where a 2 ms pause is audible, or a trading path where tail latency is measured in microseconds, or a game engine loop, the collector is the wrong foundation. Rust gives me those guarantees, and it is the right answer there.
If I am writing an embedded system with 64 KB of RAM, Go’s runtime itself is too big.
For everything else, which is to say almost every API, worker, CLI, and internal service I have built in the last few years, the collector is not the bottleneck. The database is. The unindexed query is. The N+1 loop is. Blaming the GC before profiling is a reliable way to spend a week optimising the wrong thing.
A short checklist
When memory looks wrong in a Go service, this is the order I check things in:
- Read
GODEBUG=gctrace=1for a minute. Is the GC even running often? - Force
runtime.GC()and compareHeapAllocover time. Is live data growing? - Look for a cache or map that only grows.
- Look for per-request allocations that could be preallocated or pooled.
- Set
GOMEMLIMITin the container to match the memory limit. - Only after all of that, think about tuning
GOGC.
Closing thoughts
For a long time I thought of the garbage collector as a tax: something I paid for convenience and occasionally complained about. Now I think of it as a colleague that runs in the background, doing a boring job competently, and occasionally needing me to stop handing it so much work.
Go’s collector is not the fastest, the cleverest, or the most advanced in the world. It is a deliberate compromise: short pauses, no moving, no generations, and a runtime that assumes you would rather ship features than manage object lifetimes. For the kind of software Go was built for, that compromise is very hard to beat.
Give It Less Work, Not More Knobs
If you take one thing from this article, make it this: before you tune anything, measure. Turn on `gctrace`, watch `HeapAlloc` after a forced collection, and find out whether you actually have a problem. Most Go services do not. The ones that do are almost always allocating in a loop that did not need to, not suffering from a badly tuned collector. And if your RSS is higher than your live heap, congratulations, that is the design working exactly as intended. 🐹
Comments
comments powered by Disqus