Memory Management
- Explain how virtual addresses become physical ones (page tables, TLB) and what a page fault costs
- Read
free, RSS, page cache and cgroup memory stats without misdiagnosing "memory leaks" - Predict when the OOM killer fires, inside and outside containers, and which process it picks
- Decide on huge pages, swap and
mmapfor databases and caches - Configure
GOGCandGOMEMLIMITfor a Go service with a Kubernetes memory limit
TL;DR
- Every process sees virtual memory; the MMU translates it page by page (4 KiB by default) through page tables, cached in the TLB. A TLB miss costs a page-table walk; a page fault costs kernel work — microseconds for minor faults, ~100 µs+ for major faults that hit storage.
- Linux overcommits:
malloc/mmapsucceed and physical pages are assigned on first touch. Running out later is handled by reclaim, swap and, finally, the OOM killer. - Free memory is wasted memory: Linux fills RAM with page cache. Read the
availablecolumn, notfree. - In a container, page cache, kernel memory and anonymous memory are all charged to the cgroup. Exceeding
memory.maxtriggers an OOM kill inside the cgroup — exit code 137,OOMKilled. - Huge pages (2 MiB / 1 GiB) multiply TLB reach; explicit huge pages help databases, but transparent huge pages can cause latency spikes and memory bloat — Redis and many DB vendors say disable or use
madvise. mmapmaps files into memory: zero-copy reads and shared caches, but page faults are invisible blocking I/O — in Go they stall a thread and its P.- For Go in containers: set
GOMEMLIMITto ~90% of the container limit (Go 1.19+) so the GC works harder before the kernel kills you; keepGOGCat default or raise it.
Why it matters
A wallet service caches FX rates and customer limits in memory. Under a promotion campaign its pods start dying with OOMKilled every few hours. The heap profile shows only 300 MiB live, the limit is 1 GiB, yet the container dies. Possible culprits — all OS-level: the Go GC lets the heap grow to 2× live before collecting (GOGC=100), goroutine stacks and buffers from a traffic spike, page cache from writing audit logs to a local file, and memory the runtime freed but the kernel has not reclaimed yet. Without understanding what the cgroup counts and how Go decides when to collect, you either over-provision (expensive at hundreds of pods) or chase a phantom leak.
On the database side, decisions like "enable huge pages for PostgreSQL shared buffers", "disable THP for Redis", "is swap allowed on the Kafka brokers" are made by architects in design reviews. In interviews, "what happens when you access memory that is not in RAM?" is a standard depth probe.
Core concepts
Virtual memory
Virtual memory gives each process a private, contiguous-looking address space backed by physical frames, swap or files. Benefits:
- Isolation — a process cannot address another's memory.
- Overcommit and lazy allocation — reserve 64 GiB of address space, pay only for touched pages.
- Sharing — shared libraries,
forkcopy-on-write and the page cache map the same physical page into many processes. - Files as memory —
mmapturns file I/O into memory access.
Paging and page tables
Memory is divided into pages (4 KiB on x86-64 and most ARM64 configurations). On x86-64 with 4-level paging, a 48-bit virtual address is split into four 9-bit indices (one per page-table level) plus a 12-bit offset within the page.
Each page-table entry carries the physical frame number and flags: present, writable, user-accessible, dirty, accessed, no-execute. The kernel uses the accessed/dirty bits to decide what to reclaim.
TLB and TLB reach
The TLB is a small cache of recent translations. Sizes vary by CPU, but roughly: tens of entries in the L1 data TLB and one to two thousand in the shared L2 TLB. With 4 KiB pages, 1,500 entries cover about 6 MiB — far smaller than a 20 GiB buffer pool. With 2 MiB pages the same entries cover about 3 GiB. That is the core argument for huge pages in large-memory databases.
- PCID/ASID tags let entries survive context switches between processes.
- TLB shootdowns: when one thread unmaps or changes protection on memory, other CPUs running threads of the same process must flush the stale entries via inter-processor interrupts. Heavy
munmap/madvisechurn in a many-threaded process shows up as system CPU.
Page faults
- Minor faults are cheap-ish (roughly sub-microsecond to a few microseconds) but add up: a service touching fresh memory at high rate shows elevated
%sys. - Major faults wait on storage: roughly ~100 µs on NVMe, ~10 ms on spinning disks. Any major fault on a request path is a latency incident waiting to happen.
- Measure:
ps -o min_flt,maj_flt -p PID,/usr/bin/time -v ./cmd,perf stat -e page-faults,major-faults,sar -B 1(majflt/s).
Overcommit
vm.overcommit_memory:
| Value | Behaviour | Notes |
|---|---|---|
| 0 (default) | Heuristic: refuse obviously impossible allocations | Most allocations succeed; OOM killer handles the rest |
| 1 | Always allow | Redis recommends this so fork for BGSAVE never fails |
| 2 | Strict: commit limit = swap + overcommit_ratio% of RAM | Allocations fail with ENOMEM instead of OOM kills; many runtimes reserve large virtual ranges and fail to start |
Page cache
All buffered file I/O goes through the page cache. Reads populate it; writes dirty pages in it and return immediately; background writeback flushes them later (see File Systems & Durable Storage).
$ free -m
total used free shared buff/cache available
Mem: 31958 9120 812 410 22026 21880
Swap: 0 0 0
Here only 812 MiB is "free", but 21,880 MiB is available — most of buff/cache is clean page cache the kernel can drop instantly. Low free is normal; low available plus swap activity (vmstat si/so) or reclaim stalls is a problem.
Kafka is the classic page-cache-friendly design: brokers write to the page cache and consumers reading recent data are served from RAM, so brokers are sized with a large fraction of RAM left for the OS rather than for the JVM heap.
Reclaim, swap and pressure
When free memory falls below watermarks, kswapd reclaims in the background: clean page cache first (cheap), then dirty pages (needs writeback), then anonymous memory (needs swap). If allocation outpaces kswapd, the allocating thread does direct reclaim itself — a latency spike on your request path.
- Swap trades OOM kills for latency.
vm.swappiness(default 60) biases reclaim between page cache and anonymous memory. Latency-sensitive services generally avoid swapping; Kubernetes historically required swap off on nodes, and newer versions support it only with explicit configuration. - PSI memory (
/proc/pressure/memory, per-cgroupmemory.pressure) shows time stalled on reclaim — a better early warning than "used %".
The OOM killer
When reclaim cannot satisfy an allocation, the kernel kills a process. The victim is chosen by oom_score — roughly proportional to its memory footprint (RSS + swap + page tables) — adjusted by oom_score_adj (−1000 = never kill, +1000 = kill first).
- Global OOM (whole host):
dmesgshowsOut of memory: Killed process 4242 (payments) ... anon-rss:.... - cgroup OOM (container exceeded
memory.max):dmesgshowsMemory cgroup out of memory;memory.eventsincrementsoom_kill; Kubernetes reportsOOMKilled, exit code 137. - Kubernetes sets
oom_score_adjby QoS class: Guaranteed −997, BestEffort 1000, Burstable in between based on request size. Under node pressure, BestEffort dies first. memory.oom.group = 1kills the whole cgroup instead of one process — useful when a partially killed container would be worse than a dead one.
Huge pages
| Mechanism | How | Pros | Cons |
|---|---|---|---|
Explicit huge pages (hugetlbfs, vm.nr_hugepages) | Pre-reserved pool, application opts in | Predictable, no compaction at runtime, big TLB-reach win | Reserved memory is unavailable to others; needs app support |
Transparent huge pages (THP) always | Kernel promotes eligible anonymous memory automatically | No app change | Compaction and khugepaged stalls; COW copies 2 MiB; RSS bloat when sparse pages get promoted |
THP madvise | Only regions the app marks with madvise(MADV_HUGEPAGE) | App chooses where it helps | App must know |
THP never | Off | Predictable latency | Lose TLB benefits |
Practice: PostgreSQL can use explicit huge pages for shared_buffers (huge_pages = try); Redis warns at startup when THP is always and recommends disabling it; Oracle and MongoDB guidance has historically recommended disabling THP (check current vendor docs, as advice evolves). Check with cat /sys/kernel/mm/transparent_hugepage/enabled.
Memory-mapped files (mmap)
mmap maps a file (or anonymous memory) into your address space:
MAP_SHAREDfile mappings write back to the file and share the page cache;MAP_PRIVATEgives copy-on-write private copies.- Uses: bbolt (used by etcd) and LMDB map their whole database file; Lucene/Elasticsearch use mmap for index files; Prometheus TSDB maps chunk files.
- Pros: no copy between page cache and a user buffer; the kernel handles caching and sharing across processes.
- Cons: you lose control over eviction and I/O scheduling; I/O errors arrive as
SIGBUS, not error returns; and page faults block the thread. In Go a major fault inside an mmap'd region is not a syscall, so the runtime cannot hand off the P — that P is stalled until the read completes. Crotty, Leis and Pavlo's CIDR 2022 paper "Are You Sure You Want to Use MMAP in Your Database Management System?" lays out why most serious DBMSs manage their own buffer pools.
Stack vs heap
| Stack | Heap | |
|---|---|---|
| Lifetime | Function scope, LIFO | Until freed (C) or unreachable (Go GC) |
| Allocation cost | Bump a pointer | Allocator work + GC pressure |
| Size | OS thread: fixed (8 MiB default virtual); goroutine: starts small, grows by copying up to 1 GB | Limited by memory/cgroup |
| Failure mode | Stack overflow (Go: goroutine stack exceeds 1000000000-byte limit) | OOM, GC thrash |
In Go, escape analysis decides: a value whose address outlives the function (returned pointer, stored in an interface or a long-lived struct, captured by a goroutine) is heap-allocated. go build -gcflags=-m prints the decisions. Fewer heap allocations means less GC work — see Memory, GC & Escape Analysis.
cgroup memory limits
| File (cgroup v2) | Meaning |
|---|---|
memory.max | Hard limit; above it the kernel reclaims, then OOM-kills inside the cgroup. Kubernetes memory limit maps here |
memory.high | Soft throttle: above it, allocating tasks are slowed and forced into reclaim |
memory.min / memory.low | Protection from reclaim under global pressure |
memory.current | Total charged: anonymous + page cache + kernel (slab, socket buffers, page tables) |
memory.stat | Breakdown: anon, file, active_file, inactive_file, sock, slab… |
memory.events | Counters: high, max, oom, oom_kill |
Kubernetes eviction and the "working set" metric use roughly memory.current − inactive_file, because inactive page cache is easily reclaimable. A container that writes large log files may show high usage that is mostly reclaimable cache — the kernel reclaims it before OOM-killing, but dirty pages under heavy write can still push you over.
Go: GOGC and GOMEMLIMIT
GOGC(default 100) sets the heap growth ratio: next GC triggers at roughly live heap × (1 + GOGC/100). Live heap 300 MiB → GC at ~600 MiB.GOMEMLIMIT(Go 1.19+) is a soft limit on total runtime-managed memory (heap, goroutine stacks, runtime metadata — not cgo allocations, the binary itself or page cache). As usage approaches it, the GC runs more often regardless ofGOGC.- Death-spiral guard: if the live heap really exceeds the limit, the GC would run continuously; the runtime caps GC CPU at about 50% (over a time window), so the program keeps making progress and may then exceed the limit and get OOM-killed — a deliberate choice of "die" over "freeze".
- Returning memory: the runtime's scavenger releases unused pages to the OS with
madvise; RSS lags behind heap shrinkage. (Go 1.12–1.15 usedMADV_FREEon Linux, which made RSS look inflated; 1.16 switched back toMADV_DONTNEED.) - Go does not read the cgroup memory limit automatically. Set
GOMEMLIMITyourself (env var,debug.SetMemoryLimit, or a library such asautomemlimit).
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Swap off | Predictable latency; failures are fast and visible | OOM kills under spikes; no cushion | Latency-critical services, Kubernetes default |
| Swap on (small, or zswap) | Absorbs spikes and cold anonymous pages | Unpredictable stalls; hides leaks | Batch hosts, dev boxes, some DB hosts per vendor advice |
THP always | Free TLB win for big heaps | Latency spikes, RSS bloat | Throughput batch/analytics on dedicated hosts |
THP madvise/never + explicit huge pages | Predictable, targeted gains | Manual pool sizing | Databases with large shared buffers |
mmap the data file | Simple, zero-copy, shared cache | No eviction control, faults stall threads, SIGBUS on errors | Read-mostly embedded stores (bbolt, LMDB), index files |
Own buffer pool + pread/O_DIRECT | Full control of eviction, prefetch, I/O errors | Much more code | General-purpose DBMS (PostgreSQL-style buffers, InnoDB) |
GOGC only | Simple; proportional overhead | Ignores the container limit, so the heap can grow past it | No memory limit, or plenty of headroom |
GOMEMLIMIT + default GOGC | GC tightens near the limit; fewer OOMs | More GC CPU near the limit | Most containerised Go services |
GOMEMLIMIT + GOGC=off | Minimal GC until the limit | Under a leak, GC thrash then OOM; risky for shared hosts | Dedicated, well-understood batch or cache workloads |
In practice
Derive GOMEMLIMIT from the cgroup at startup unless it was set explicitly:
package memlimit
import (
"os"
"runtime/debug"
"strconv"
"strings"
)
// FromCgroup sets the Go soft memory limit to ratio × the cgroup v2 memory.max.
// It does nothing if GOMEMLIMIT is already set or the cgroup is unlimited.
func FromCgroup(ratio float64) (int64, error) {
if os.Getenv("GOMEMLIMIT") != "" {
return debug.SetMemoryLimit(-1), nil // -1 reads the current value
}
b, err := os.ReadFile("/sys/fs/cgroup/memory.max")
if err != nil {
return 0, err
}
s := strings.TrimSpace(string(b))
if s == "max" {
return debug.SetMemoryLimit(-1), nil
}
limit, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
target := int64(float64(limit) * ratio)
debug.SetMemoryLimit(target)
return target, nil
}
Call memlimit.FromCgroup(0.9) early in main. Simpler alternative in Kubernetes: set the env var from the limit with the downward API (resourceFieldRef: limits.memory) and a fixed percentage in your Helm template.
Diagnosing "my container uses too much memory":
cat /sys/fs/cgroup/memory.current
grep -E '^(anon|file|inactive_file|active_file|sock|slab) ' /sys/fs/cgroup/memory.stat
cat /sys/fs/cgroup/memory.events # oom_kill counter
grep -E 'VmRSS|RssAnon|RssFile' /proc/1/status
dmesg -T | grep -i -E 'out of memory|oom'
Then compare with Go's own view: runtime/metrics (/memory/classes/heap/objects:bytes, /memory/classes/total:bytes) or /debug/pprof/heap. If anon ≈ Go total, the memory is Go's; if file dominates, it is page cache; if Go total is far below anon, suspect cgo or a native library.
Rough sizing for a Go service with a 1 GiB limit: GOMEMLIMIT≈900MiB, keep live heap at or below ~400–500 MiB at peak so default GOGC rarely needs the limit, and alert on GC CPU fraction and memory.events high/max counters before oom_kill appears.
Common pitfalls
- Treating low
freeas a leak. Page cache fills RAM by design. Symptom: alerts on "memory used 95%" with no impact; look atavailableand PSI. - No
GOMEMLIMITin a tight container. Heap target hits 2× live and crossesmemory.max. Symptom: periodicOOMKilledwith a modest live heap. GOMEMLIMITequal to the container limit. Non-Go memory (cgo, binary, page cache charged to the cgroup, kernel socket buffers) pushes you over. Leave 5–10%+ headroom.- THP
alwayson Redis or latency-sensitive DB hosts. Symptom: latency spikes duringfork,khugepagedCPU, RSS much larger than dataset. mmap-based storage on slow network disks under Go. Symptom: stalls with no syscall visible in traces;maj_fltrising; goroutines delayed although CPU is idle.- Ignoring kernel memory. Tens of thousands of TCP connections with large socket buffers are charged to the cgroup (
sockinmemory.stat). Symptom: OOM with a small Go heap on a WebSocket gateway. - Disabling the OOM killer or setting
oom_score_adj=-1000broadly. The kernel then kills something important instead (or the host hangs). - Load tests that never reach steady state. Memory problems from caches, fragmentation and slow leaks appear after hours; run soak tests before a big sale.
Interview angle
- "What happens when a process accesses an address?" — expected path: TLB → page walk → page fault (minor/major/COW/SIGSEGV), with rough costs.
- "Your Go pod is OOMKilled but the heap profile is small — why?" — GC headroom (
GOGC), page cache and kernel memory charged to the cgroup, goroutine stacks, cgo, RSS lag from scavenging; fix withGOMEMLIMIT, headroom and metrics. - "Should we enable huge pages / swap on the DB hosts?" — explain TLB reach vs THP latency, explicit huge pages for buffer pools, swap as cushion vs latency.
- Follow-ups: what overcommit means and why Redis wants mode 1; how the OOM killer picks a victim; what Kubernetes QoS does to
oom_score_adj; mmap vs buffer pool. - Red flags: "the kernel allocates memory when you call malloc"; "free memory should be high"; "GOMEMLIMIT is a hard limit".
Self-check
1. Explain the difference between a minor and a major page fault, with an example of each in a Go service.
A minor fault is resolved without I/O: first touch of newly allocated heap memory (kernel supplies a zeroed page) or mapping a file page already in the page cache. A major fault requires reading from storage: touching a swapped-out page, or reading an mmap'd bbolt file region not in the page cache. Minor faults cost microseconds of CPU; major faults block the thread for the device latency.
2. Why do huge pages help a database with a 64 GiB buffer pool, and why might you still disable THP?
With 4 KiB pages, the TLB covers only a few MiB, so random access over 64 GiB misses the TLB constantly and pays page walks. 2 MiB pages raise TLB reach by 512×. THP gets the benefit automatically, but it promotes/compacts memory in the background and on fault, causing latency stalls and memory bloat, and makes copy-on-write after fork copy 2 MiB at a time. Explicit huge pages give the benefit predictably for the buffer pool only.
3. A container with a 2 GiB limit shows memory.current at 1.9 GiB, but the Go heap is 600 MiB. Where could the rest be?
Check memory.stat: file (page cache from logs or file reads — mostly reclaimable), sock (socket buffers), slab (kernel objects such as dentries), anon beyond the Go heap (goroutine stacks, GC headroom up to the next target, freed-but-not-scavenged spans, cgo allocations). Compare with Go's runtime/metrics total. Usage near the limit made of reclaimable cache is fine; anon near the limit is not.
4. What exactly does GOMEMLIMIT limit, and what happens when the live heap exceeds it?
It is a soft limit on memory managed by the Go runtime (heap, stacks, runtime metadata), excluding cgo/native memory and OS-held page cache. Near the limit the GC runs more frequently. If the live heap exceeds it, the GC would run continuously, so the runtime caps GC CPU at roughly 50%; memory then grows past the limit and the kernel eventually OOM-kills the process if the cgroup limit is reached.
5. Kubernetes node is under memory pressure. In what order are pods likely affected and why?
The kubelet evicts pods based on usage relative to requests and QoS: BestEffort first, then Burstable pods exceeding requests, Guaranteed last. If the kernel OOM killer acts before eviction, oom_score_adj biases victim choice the same way (BestEffort 1000, Guaranteed −997).
6. Scenario: an e-commerce search pod uses an mmap'd index on a network volume, and p99 spikes after each deploy. Explain and propose a fix.
After a deploy the page cache on the new node is cold, so index lookups cause major page faults that read from the network volume; each fault blocks a thread (and in Go, its P). Fixes: warm up (read/madvise(MADV_WILLNEED) the hot index before taking traffic via the readiness probe), use local NVMe, keep enough RAM for the hot set, or switch from mmap to explicit reads with a managed cache.
Exercise
Watch Go, the kernel and cgroups disagree about memory.
- Write a Go program that allocates and retains 50 MiB every second (append to a slice of
[]byte, touch each page), logsruntime/metricstotal memory and heap objects, and serves/debug/pprof. - Run it in Docker with
--memory=512m. Record when it is killed (docker inspect→OOMKilled, exit code) and whatdmesgsays. - Change it to keep only the last 300 MiB live (drop older slices). Run with
GOGC=100and no limit setting: does it survive? Then run withGOMEMLIMIT=460MiB. Compare GC frequency (GODEBUG=gctrace=1) and peakmemory.current. - In a separate run, write a 2 GiB file with
ddinside the same container and watchmemory.statfilevsanon. Does the container get OOM-killed? Why not? - Bonus:
perf stat -e page-faults,major-faultson a program that mmaps a large file and reads it twice; explain the difference between passes.
Done looks like: a short table (scenario, peak memory.current, GC count, killed yes/no) and a paragraph explaining each outcome.
Further reading
- Operating Systems: Three Easy Pieces — virtualisation chapters: address spaces, paging, TLBs, swapping: https://pages.cs.wisc.edu/~remzi/OSTEP/
- Ulrich Drepper, "What Every Programmer Should Know About Memory" (2007)
- Go team, "A Guide to the Go Garbage Collector": https://go.dev/doc/gc-guide
- Linux kernel documentation, "Control Group v2" (memory controller): https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
- Crotty, Leis, Pavlo, "Are You Sure You Want to Use MMAP in Your Database Management System?" (CIDR 2022)
- Brendan Gregg, Systems Performance (2nd ed.) — Memory chapter
Related
- Memory, GC & Escape Analysis — the Go allocator and GC tuning in depth
- Processes & Threads — address-space layout and fork/COW
- File Systems & Durable Storage — page cache, writeback and fsync
- Linux Containers — how memory limits map from Kubernetes to cgroups
- Redis Deep Dive — fork, overcommit and THP in a real system
- PostgreSQL Deep Dive — shared buffers vs page cache and huge pages
- Capacity Planning & Cost — sizing memory requests and limits
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).