Developers moving to Go from C or C++ often assume that an automatic garbage collector makes memory leaks impossible. In lower-level languages, forgetting free() loses the pointer physically: the OS keeps the block allocated even though the program has no way to reach it. In Go, that specific bug can't happen. Yet Grafana memory graphs still climb steadily until the Linux kernel kills the container with OOMKilled.
Go's garbage collector (GC) regularly walks the object graph starting from GC roots (global variables and active goroutine stacks) and frees unreachable structures. However, if your code still holds a reference to an object in an active variable, the GC must keep it on the heap, even if your business logic will never need it again. That is a logical memory leak.
Three Classic Ways Go Retains Memory
In Go backend services, most hidden leaks come down to three common patterns:
- Unbounded collections without eviction:
Teams build an in-memory cache using a standard
maporslice, but forget to add a TTL (time-to-live) or an eviction policy like LRU. Every incoming request adds another entry, and the heap grows without limit. - The reslicing trap:
Suppose your service reads a multi-megabyte packet from a socket into
data := make([]byte, 1024*1024*10), then extracts just a 16-byte header withheader := data[:16]. Ifheaderis stored in a long-lived struct, the GC cannot free the original 10 MB array. In Go, a slice holds a pointer to its underlying array, plus length and capacity (cap). As long as even one slice points to that backing array, the entire array stays in memory. The fix is to copy the bytes explicitly usingcopy(). - Leaked goroutines: Goroutines are lightweight (starting with a 2–4 KB stack), but if one blocks forever—for example, trying to write to an unbuffered channel with no reader, or waiting without a context timeout—the runtime will never clean it up. Its stack and every local variable captured in its closure remain tied to GC roots. Hundreds of stuck goroutines can quietly hold onto hundreds of megabytes.
Reading the GC's Mind with gctrace
Your first step when investigating high memory usage is to confirm whether you actually have a logical leak. Run your binary with the runtime debug flag enabled:
GODEBUG=gctrace=1 ./my-service
The runtime will print a detailed line to stderr for every GC cycle:
gc 18 @42.150s 1%: 0.045+1.2+0.030 ms clock, 0.36+0.8/2.1/0+0.24 ms cpu, 14->15->8 MB, 16 MB goal, 8 P
Look closely at the key metric in that output:
- The numbers
14->15->8 MBshow the heap size before marking, at the end of marking, and the live heap size after sweeping. 8 MBis the actual amount of data the GC found reachable.- The smoking gun: If under steady traffic that final live-heap number climbs cycle after cycle—say from 8 MB to 24 MB, then 60 MB, and never drops back—you have a logical memory leak. The GC is sweeping regularly, but retained data keeps growing.
Setting Up pprof and Understanding Heap Modes
Once you confirm a leak, you need to pinpoint where it happens in your code. Go's standard library includes the net/http/pprof package for this.
In pprof, heap profiles work in two very different modes:
-alloc_space: Shows total memory allocated since the process started, including objects already freed by the GC. This helps you spot high allocation pressure, not leaks.-inuse_space: Shows memory currently held by live objects right now. This is the mode that isolates blocks the GC cannot free.
Here is a minimal service that reproduces a leak and exposes the pprof endpoint:
package main
import (
"log"
"net/http"
_ "net/http/pprof"
"time"
)
// Global slice simulating a reference leak
var memorySink = make([]*[1024]byte, 0)
func workerLoop() {
for {
// Regularly allocate a 1 KB object and keep its pointer
chunk := new([1024]byte)
memorySink = append(memorySink, chunk)
time.Sleep(5 * time.Millisecond)
}
}
func main() {
// Expose the pprof debug endpoint on a dedicated port
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
go workerLoop()
log.Println("Сервис запущен. Имитация удержания памяти активна...")
select {}
}
Differential Profiling: Comparing Two Snapshots
The hardest part of hunting a leak in a live service is background noise. A running app always holds hundreds of legitimate structures: network buffers, ORM caches, and worker pools. If you grab a single heap profile, framework internals sit at the top and hide the leaking call path.
Differential comparison of two pprof heap snapshots to detect a hidden memory leak in Go
To isolate the leak reliably, use differential profiling:
- Run the service under load. After caches warm up (2–3 minutes), take a baseline heap snapshot (
heap_base.pb.gz). - Let the app run under the same load for 20–30 minutes while the leak accumulates.
- Take a second snapshot (
heap_target.pb.gz). - Compare the two using the
-diff_baseflag.
Commands to capture the snapshots and run the diff:
# 1. Capture baseline snapshot after warmup
curl -s http://localhost:6060/debug/pprof/heap > heap_base.pb.gz
# 2. Capture target snapshot after 20 minutes of traffic
curl -s http://localhost:6060/debug/pprof/heap > heap_target.pb.gz
# 3. Compare the delta in retained memory
go tool pprof -inuse_space -diff_base heap_base.pb.gz heap_target.pb.gz
Inside the interactive pprof prompt, two commands give you the answer:
(pprof) top
Showing nodes accounting for +18.42MB, 98.5% of +18.70MB total
flat flat% sum% cum cum%
+18.42MB 98.5% 98.5% +18.42MB 98.5% main.workerLoop
(pprof) list workerLoop
ROUTINE ======================== main.workerLoop
+18.42MB +18.42MB (flat, cum) 98.5% of Total
. . 14:func workerLoop() {
. . 15: for {
+18.42MB +18.42MB 16: chunk := new([1024]byte)
. . 17: memorySink = append(memorySink, chunk)
. . 18: time.Sleep(5 * time.Millisecond)
. . 19: }
. . 20:}
The top command pushes functions with the largest positive growth (+18.42MB) right to the top, and list highlights the exact source lines allocating the retained objects.
Returning Memory to the OS: Why RSS Stays High
Engineers often hit a puzzling situation: the leak is fixed, pprof shows the heap dropped from 2 GB to 200 MB, yet top or Kubernetes container_memory_working_set_bytes still reports 2 GB.
This comes down to how Go's runtime talks to the Linux kernel. The GC frees memory inside Go's own virtual heap, organizing it into spans (mspan) for future allocations. Returning physical pages to the OS happens asynchronously in a background thread called the scavenger.
The scavenger calls madvise with the MADV_DONTNEED flag. That tells Linux it can reclaim those physical pages if memory gets tight, while keeping the virtual address range reserved. As a result, OS-level RSS drops gradually and with a delay.
Engineer's Checklist: Five Rules to Prevent Leaks
To prevent memory degradation in production and avoid sudden pod crashes, follow these five rules:
- Put strict size limits or TTL expiration on every in-memory store and cache. When a store hits its threshold, evict old keys automatically.
- Whenever you slice a small piece out of a large buffer, copy it into a fresh array with
copy(). - Track the lifecycle of every goroutine you spawn. Pass a
context.WithTimeoutand make sure channels are drained so goroutines exit cleanly on cancellation. - Run suspicious services with
GODEBUG=gctrace=1during load tests. If the live heap grows alongside test duration, find the leak before shipping. - Make
go tool pprof -diff_basea regular part of load testing. It cuts through static noise and points straight to the leaking line of code.

