Why untouched Go slices can end up in physical memory more often under GOMEMLIMIT

A Go program that allocates large slices and never writes to them should need almost no physical memory. Linux backs anonymous memory with physical pages on first write, so untouched virtual memory is free. Yet a program that does nothing but allocate 400 MiB slices ends up with 0.9 GiB of RSS, and 2.1 GiB once GOMEMLIMIT is set. The cause is how the runtime decides when it has to clear memory before handing it out. Clearing is a write, and the first write to a page makes the kernel back it with a physical page, even when the bytes written are zeros.

The demo

vm-demo.go allocates a 400 MiB slice every second, 200 times, and keeps a reference to each one without reading or writing it.

 1func main() {
 2    var d [][]byte
 3    time.Sleep(3 * time.Second) // sleep 3 seconds for the collection script to find PID.
 4    for range 200 {
 5        d = append(d, make([]byte, 8*50*1024*1024)) // 400 MiB
 6        time.Sleep(time.Second)
 7        // Reference d, in case compiler optimizes d away.
 8        fmt.Println(len(d))
 9    }
10}

collect.sh samples VmSize and VmRSS from /proc/PID/status every second, and plot-memory-usage.py draws the runs. Everything ran with Go 1.27.4 and swap disabled. The four runs are vm-demo without a limit, with GOMEMLIMIT=2048MiB, with GOMEMLIMIT=2048MiB and GODEBUG=disablethp=1, and a variant that takes its slices from mmap instead of make, explained at the end.

Virtual and physical memory of vm-demo

Virtual memory grows to 80 GiB in every run. Physical memory grows in steps of 400 MiB: two steps without a limit, five with GOMEMLIMIT. Each step is one whole slice becoming resident.

The RSS is real memory, not an accounting artifact. Under a 200 MiB cgroup limit, the program is OOM-killed:

1$ sudo systemd-run --scope -p MemoryMax=200M -E GOMEMLIMIT=2048MiB ./vm-demo
2Running scope as unit: run-rb6a475e55a26415684b003f6e9e34af9.scope
31
1kernel: Memory cgroup out of memory: Killed process 3192538 (vm-demo) total-vm:2147972kB, anon-rss:202240kB, file-rss:0kB, shmem-rss:1100kB, UID:0 pgtables:508kB oom_score_adj:0
2systemd[1]: run-rb6a475e55a26415684b003f6e9e34af9.scope: A process of this unit has been killed by the OOM killer.

Something writes to the whole slice

/proc/PID/smaps puts the RSS in the Go heap mapping. The other large mapping, about 90 MiB, is runtime metadata for 80 GiB of heap. vm-demo-mincore.go calls mincore(2) on every slice after each allocation. A slice is either not resident at all or resident in full, 400 of 400 MiB, from the moment make returns. The writes happen inside make.

Go guarantees that make returns zeroed memory. Pages fresh from the kernel are already zero, so the runtime skips clearing them, but it has to know which pages are fresh. It tracks that with one high-water mark per 64 MiB heap arena, zeroedBase, in allocNeedsZero:

 1func (h *mheap) allocNeedsZero(base, npage uintptr) (needZero bool) {
 2    for npage > 0 {
 3        ai := arenaIndex(base)
 4        ha := h.arenas[ai.l1()][ai.l2()]
 5
 6        zeroedBase := atomic.Loaduintptr(&ha.zeroedBase)
 7        arenaBase := base % heapArenaBytes
 8        if arenaBase < zeroedBase {
 9            // We extended into the non-zeroed part of the
10            // arena, so this region needs to be zeroed before use.
11            needZero = true
12        }
13        // ... raise zeroedBase to the end of the allocation, continue in the next arena
14    }
15    return
16}

The result is one bool for the whole allocation. If a 400 MiB allocation starts even one page below zeroedBase, the whole span is marked as needing zeroing. Since Go 1.26 there is one exception, in allocSpan: on Linux, a span whose pages were all returned to the OS with MADV_DONTNEED reads as zero, so it is not cleared.

1if (needZeroAfterSysUnused() || scav != npages*pageSize) && needZero {
2    s.needzero = 1
3}

If even one page of the span has not been returned, mallocgcLarge clears all 400 MiB with memclrNoHeapPointersChunked. Writing zeros is still a write: each 4 KiB page takes a page fault on first write, and the kernel backs it with its own physical page, so every page of the slice becomes resident.

Where the reused pages come from

vm-demo allocates more than slices. fmt.Println and the runtime allocate small objects, and the page allocator puts them at the lowest free address, right after the last slice, which raises zeroedBase in that arena. When a GC frees them, a hole opens below zeroedBase. The next 400 MiB allocation takes the lowest free range that fits, which starts in that hole and runs on into fresh memory.

log-zeroing.patch adds two prints to the runtime: REUSED when a large allocation starts below zeroedBase, and ZEROED when its span is actually marked for clearing. With vm-demo built against the patched Go 1.27.4 runtime, two runs of each configuration gave:

200 allocations of 400 MiB GC cycles REUSED ZEROED max RSS
no GOMEMLIMIT 8 2 2 895 MiB
no GOMEMLIMIT 8 2 2 895 MiB
GOMEMLIMIT=2048MiB 202 9 4 1,698 MiB
GOMEMLIMIT=2048MiB 200 13 5 2,098 MiB
GOMEMLIMIT=2048MiB, disablethp=1 204 13 5 2,098 MiB
GOMEMLIMIT=2048MiB, disablethp=1 202 16 4 1,698 MiB

Every ZEROED allocation is one 400 MiB step in RSS, on top of about 95 MiB of runtime metadata and binary. The reused part at the start of a slice was small, 32 KiB or 544 KiB most of the time, and at most 16 MiB. In the logs (no-limit.zeroing.log, gomemlimit.zeroing.log, gomemlimit-disablethp.zeroing.log), each zeroed span had all but 32 to 224 KiB of its 409,600 KiB already returned to the OS. A few KiB of reused memory that the scavenger had not released yet cost 400 MiB of RSS.

Why GOMEMLIMIT makes it worse

A hole only appears after a GC frees the small objects in front of the heap. Without a limit, the GC runs when the heap doubles, 8 times over the whole run, so few holes ever open. With GOMEMLIMIT=2048MiB, the live heap passes the limit after the sixth slice and keeps growing to 80 GiB. The limit can never be met, so the GC runs on every allocation, about 200 times over the run, and each cycle frees the latest small garbage. Large allocations started in a reused hole 9 to 16 times instead of 2.

The scavenger works harder under the limit too, and it returns most holes to the OS before a slice lands on them. Those allocations skip the clear. The ones that land on a hole the scavenger has not reached yet are cleared in full: 4 or 5 per run against 2 without the limit.

Transparent huge pages are not involved

GODEBUG=disablethp=1 looks like a fix for this kind of bloat, and it changes nothing here: the disablethp runs zeroed 4 and 5 slices, the same as the runs without it. On a host transparent_hugepage is set to madvise, so the kernel only uses huge pages for mappings that ask for them with MADV_HUGEPAGE. Go asks only for a few pieces of GC metadata once the heap goal passes 1 GiB. strace shows one MADV_HUGEPAGE call per run, and AnonHugePages in /proc/PID/smaps_rollup stays at 0 in every run.

What to do about it

Most programs write to what they allocate, so for them the clear costs CPU time but not memory they would not have used anyway. It hurts programs that allocate large buffers and use only part of them, such as a 64 MiB read buffer that only ever holds a few KiB, or just bugs.

Set GOMEMLIMIT above the live heap. A limit that cannot be met. The GC runs back to back until its CPU limiter caps it at about half the CPU, and, as the table shows, more large allocations end up fully resident.

Allocate what you use. Grow a buffer as data arrives instead of reserving the maximum up front.

For a large region that should stay sparse, allocate it outside the Go heap. vm-demo-mmap.go replaces make with syscall.Mmap of 400 MiB of anonymous private memory. With GOMEMLIMIT=2048MiB, it reached 79 GiB of virtual memory with 3 MiB of RSS, the flat line in the figure. The kernel provides zero pages on first touch and the Go runtime never clears that memory. In exchange, the program has to munmap it, and GOMEMLIMIT does not account for it.

I'm currently open to engineer opportunities. If you liked this post and would like to have me on your team, reach out on X, LinkedIn or GitHub.