Memory growth in a Go service is not always a leak. The garbage collector returns memory to the OS lazily, and heap size depends on runtime settings, not only on code. So measure what exactly is growing first, and only then look for the culprit.
First tell a leak from normal growth.
A leak is memory that grows with uptime under the same load and does not come back after a quiet period. Growth under peak load that then levels off is not a leak; it is the service’s working set. A single RSS chart is not enough to tell them apart:
- Look at the runtime metrics (the
runtime/metricspackage, exported to Prometheus or expvar): the live heap after collection, memory held by the runtime, and the number of goroutines — each separately. - Record these values over several hours of normal load. The shape of the charts points to the cause sooner than reading code does.
- Correlate growth with deployments and load changes: a leak that appeared after a release usually lives in that release’s diff.
01 / SIGNAL
Goroutines grow
Almost certainly a goroutine leak, the most common cause in Go: blocked channels, waits without timeouts, contexts that are never cancelled.
02 / SIGNAL
Live heap grows
Something is holding references: a cache without eviction, a map that only grows, subscribers that were never removed, slices of large buffers.
03 / SIGNAL
Only RSS grows
The live heap is stable, so the cause is the garbage collector and limits, or memory outside the heap: cgo, large buffers, mmap.
A useful first question
Does memory grow together with the goroutine count, with the live heap, or on its own? The answer decides which profile to take.
Goroutine leaks are the main cause.
A goroutine is cheap, so it is easy to start one and forget it. If it waits on a channel nobody writes to anymore, or blocks sending to a channel nobody reads, it never finishes. Its stack, local variables, and everything they reference — buffers, connections, request bodies — stay alive with it.
- A request timed out and returned an error, but the goroutine doing the work is still trying to send its result into an unbuffered channel.
- A
for rangeloop over a channel that is never closed. selectwithout actx.Done()case: cancelling the context never reaches the goroutine.- Workers started per request instead of a pool and never stopped after the response.
How to see it: the goroutine profile in pprof groups goroutines by stack. If thousands of goroutines are parked on the same line, that is the one. In tests, goleak from Uber catches leaks: a test fails if stray goroutines remain after it finishes.
Take a pprof profile.
pprof is part of the standard library: import net/http/pprof and serve its handlers on a separate internal port, not the one exposed to the outside.
01 /
Goroutine profile
/debug/pprof/goroutine?debug=1 shows how many goroutines exist and where they are parked. Take two snapshots some time apart: the groups that grow are the candidates.
02 /
Heap profile
/debug/pprof/heap — what currently lives in the heap (inuse_space) and who allocated it. Compare two snapshots with go tool pprof -base: the difference shows what accumulated.
03 /
Allocation profile
alloc_space shows who allocated the most over the whole run. This is not a leak, but a high allocation rate loads the garbage collector and looks like memory growth.
04 /
Look at it visually
go tool pprof -http=:8081 profile opens the call graph and a flame graph. Look not for the biggest nodes but for the ones that grow between snapshots.
Profiling in production is safe if done occasionally and the debug port is not exposed. For continuous observation there is continuous profiling (Pyroscope, Parca, cloud providers’ profilers): it shows exactly when growth began and which release brought it.
What to keep
A pair of heap and goroutine snapshots from before and after the growth. With them the cause is usually found in one session; without them it is guesswork.
Common sources of leaks in Go.
- Unclosed response body. After
http.Client.Dothe body must be read to the end and closed; otherwise the connection does not return to the pool and its buffers stay in memory. - Cache without eviction. A global map written per request key grows forever. It needs a size or lifetime limit (LRU, TTL).
- Subscribers and handlers. Callbacks and channels registered per request or connection and never removed when it ends.
- Slices of large buffers.
b[:10]taken from a megabyte buffer keeps the whole megabyte alive. Copy the part you need. - Context stored in a long-lived struct. An object that keeps the request’s
context.Contextholds all its values and everything cancelled through it. - Pools with objects of varying size. In a
sync.Poolbuffers of different sizes get mixed: a request for a small buffer gets a large one, and while the pool is in active use, memory stays at the level of the largest buffers. - cgo and off-heap memory. Memory allocated through C is invisible to the garbage collector and the heap profile. Find it by the gap between RSS and runtime metrics.
When there is no leak: the garbage collector and the memory limit.
Go’s garbage collector runs when the heap grows by a set proportion of the live data (GOGC, 100 by default, meaning at doubling). With a lot of live data, the heap legitimately doubles between collections. That is not a leak, but a container with a hard memory limit sees exactly these peaks.
GOMEMLIMITsets a soft ceiling for all runtime memory: as it approaches, the collector runs more often. This is the main tool for services in memory-limited containers.- Lowering
GOGCreduces memory at the cost of CPU; raising it does the opposite. Change it based on charts, not guesses. - A high allocation rate (
alloc_spacein the profile) keeps the collector busy: the service spends CPU on cleanup and responds slower. Reusing buffers and allocating fewer temporary objects on the hot path helps. - The runtime returns freed memory to the OS gradually, in the background, so RSS drops with a delay. Look at runtime metrics:
toponly shows RSS.
A simple check
Set GOMEMLIMIT below the container limit. If the chart flattens, there was no leak. If memory hits the limit and the collector runs non-stop, there is a leak: go back to the profiles.
Guardrails in production.
- Runtime metrics and goroutine count in monitoring, with an alert on growth over a day, not only on crossing a threshold.
- A timeout and a context on every external call: HTTP client, database, queue.
- The pprof debug port reachable only from inside the network or through a tunnel.
- A goroutine leak test (
goleak) for packages with background work. - A load run before release with a memory chart: a leak shows within an hour under load rather than a week later in production.
If the leak comes with growing latency, the causes are often shared. The guide “Slow API: how to find the cause” shows how to measure a service’s response piece by piece.
What to bring to the first conversation.
You do not need a diagnosis. Describe how the problem shows: does memory grow steadily or in steps, does the service get restarted on the memory limit, when it started, and what changed in code and load. Memory and goroutine charts over several days and a pair of pprof profiles let us go straight to the cause.
- How is the service run: the container and its memory limit, Go version, GOGC and GOMEMLIMIT values?
- What observability is in place: runtime metrics, logs, tracing, access to pprof?
- What downtime is acceptable, and how are fixes deployed today?