Lesson 5 of 9 · 24m
Allocations, GC, and Service Memory in Practice
How heaps grow, why allocators rarely shrink, and how to diagnose leaks, fragmentation, and garbage-collection pauses in long-lived services.
Long-lived services do not use memory the way textbooks draw it. They allocate, free, cache, fragment, compact, and retain objects for reasons nobody remembers. The OS sees pages; the runtime sees objects; the service owner sees a graph drifting upward. Your job is to connect those three views without jumping straight to 'leak.'
Freeing memory does not mean returning it to the OS
service heap: [used][free][used][free][free][used]
kernel pages: [R][R][R][R][R][R]An allocator can reuse holes inside the heap, but it may be unable to return whole pages because a few live objects pin them. RSS stays high even after object memory is 'freed.' This is fragmentation. glibc's malloc has arenas and tunables; jemalloc and mimalloc make different tradeoffs. The runtime matters.
Check allocator behavior before blaming business logic. A memory spike followed by a plateau can be cache warmup plus retained high-water memory. A true leak keeps growing under stable workload because references remain reachable.
Leak shapes have signatures
- Sawtooth: cache or batch job grows then resets; usually bounded.
- Monotonic stair-step: objects retained per request, deploy, connection, or tenant; suspicious.
- Flat high plateau: warmup or fragmentation; not necessarily a leak.
- Sudden vertical jump: unbounded input, decompression bomb, queue restore, or large allocation.
Use runtime-native tools first. Go exposes heap profiles through net/http/pprof; Java has JFR, heap dumps, and GC logs; Node has heap snapshots; Python can use tracemalloc. OS-level RSS is the effect, not the mechanism.
Garbage collection trades throughput for convenience
GC pauses happen because the runtime must prove which objects are live. Modern collectors are incremental or concurrent, but allocation rate and live-set size still drive cost. Doubling traffic often doubles allocation rate and therefore GC pressure even if CPU use looks fine.
For a JVM service, at minimum know:
java -Xmx2g -Xlog:gc*:file=/var/log/app/gc.log:time,level,tags ...Look for pause duration, frequency, and whether memory returns to a stable baseline after full collections. If post-GC live memory trends upward, that is stronger evidence of a leak than RSS growth.
Caches need admission and eviction policy
'Cache it in memory' is not a design. Every cache needs bounds, eviction, TTL, and an answer for hot-key concentration. An unbounded Map keyed by user input is a memory exploit with a friendly API.
# bad: unbounded growth driven by caller-controlled keys
cache[key] = expensive_resultPrefer explicit LRU or size-aware caches with metrics: hits, misses, evictions, bytes, and oldest-entry age. Without those numbers, caches hide both memory growth and correctness bugs.
Use limits intentionally
Container memory limits translate object growth into a predictable failure. That sounds harsh, but it is better than an unbounded service triggering the host OOM killer and taking unrelated victims. A restart under a tight limit is observable and contained. Size the limit from steady-state plus spikes, not from a quiet laptop test.
Field notes
- Watch memory per request or per connection. Normalizing by load separates leak growth from traffic growth.
- Core dumps and heap dumps can contain secrets. Restrict access and retention before enabling them in production.
- RSS reduction after a deploy does not prove the old version leaked; allocator behavior changes with binary and library versions.
- The most valuable leak evidence is object type plus allocation stack, not a line chart of total memory.
Was this lesson helpful?