Announcing Hatchet v2 & our $5.7M seed round →
all posts ·

The case of phantom memory in Kubernetes

Did Kubernetes wake me up in the middle of the night just to lie to me? An investigation.

Mohammed NafeesMohammed NafeesFounding EngineerHatchet

At three o’clock in the morning, my phone rang. It was a thundering sound, best described as European ambulance. Half-asleep, I groaned, knowing exactly what that sound meant. There was a production incident.

Soon, I was running through my standard (informal) list of ‘production incident’ questions:

  1. How bad is it?
  2. Who does it affect?
  3. … did I cause it? (Shit.)

That particular incident originated from a repeated, critical alert: High memory usage of controller pods. Not good. According to kube-state-metrics and kubectl top, we were on the brink of OOM’ing. Really not good!

It usually takes just a few minutes of digging to track down the source of a memory spike, but this time, a quick look at pprof told me… nothing. The heap was flat at 3 MiB, but Kubernetes showed more than 400 MiB. Evidently, nothing our app was doing would explain the number Kubernetes was so mad about. Since I’d never seen this behavior before, I wasn’t sure what Kubernetes was even measuring.

Cut to an hour later, with the help of cgroups and a full tour of how the kubelet counts memory, I figured it out. TL;DR, nothing ended up crashing, but the incident uncovered interesting findings on what our autoscaler spends money on, what wakes up Hatchet’s on-call engineer, and what Kubernetes uses in deciding whether to kill a pod, so I figured I’d write it up.

How much memory is my app using?

After some more digging through pprof profiles, there was some interesting behavior in the alloc_space sample. This sample, which measures the total amount of memory allocated since the start of the program, pointed straight at one workload.

That workload had allocated nearly a third of every byte since the program’s start. Our controller writes batches of data to temporary files before offloading it to S3 for cold storage.

Meanwhile, the pod kept climbing towards its limit, and the alerts kept resolving on their own after I triggered our vertical pod autoscaler. The process inside looked fine. Since the issue seemed unrelated to production, I decided then to rebuild the workload on my laptop.

I wrote a simple Go program to mirror the behavior of the workload in question. The program creates temporary files and immediately removes them. The result is the same high churn of temp files we see in production. The hot loop is as follows:

for {
	f, _ := os.CreateTemp("/tmp", "batch-*")
	f.Write(payload)
	f.Close()
	os.Remove(f.Name())
}

I ran this with 8 goroutines in a distroless container with 4 KiB payloads and at steady state, there are zero such files on disk.

Here’s the pod running in a kind cluster on my MacBook with a 512 MiB memory limit. kubectl top reports it climbing towards the set limit:

NAME          CPU(cores)   MEMORY(bytes)
hatchet-ctrl  1182m        409Mi

I used runtime.ReadMemStats, the Go runtime’s own view of its heap, plus the process RSS from /proc/self/status to see what memory looks like inside the container:

t=5s   heap_alloc=2.2Mi  heap_inuse=3.2Mi  sys=19.2Mi  RSS=14.7Mi
t=10s  heap_alloc=2.8Mi  heap_inuse=3.8Mi  sys=19.2Mi  RSS=14.6Mi
t=15s  heap_alloc=3.3Mi  heap_inuse=4.5Mi  sys=19.2Mi  RSS=13.3Mi

Go’s heap allocations report between 2–3 MiB and the resident set of the process is about 15 MiB even as the workload does over 100k operations per second. Going by these numbers, the app is in a healthy state. Yet kubectl top says 409Mi, climbing towards the limit.

The curious case of the missing memory

At this point, I understood that the Go runtime might not be able to help me further. It was time to ask the Linux kernel’s cgroups for more information.

Control groups, or cgroups for short, are how Linux groups processes so their resource usage can be limited and measured. Kubernetes depends on them to enforce a pod’s memory limit.

The container’s memory cgroup exposes plaintext files under /sys/fs/cgroup. To access this, you don’t need any special mounts or privileges. A simple cat of the files under this directory will give you all the information you need.

To make sense of the files exposed in these files, since cgroups are versioned, I first needed to check which version my node’s Linux kernel was running:

$ grep cgroup /proc/filesystems

If it supports cgroup v2, I’d see something like:

nodev   cgroup
nodev   cgroup2

Note: our nodes run cgroup v2, so that’s what the rest of this post uses.

To get the cgroup memory usage information, I added a second reader alongside the ReadMemStats call:

// total current memory usage ...
current, _ := readUint("/sys/fs/cgroup/memory.current")

// ...and the per-type breakdown, one "key value" pair per line.
stat := readKV("/sys/fs/cgroup/memory.stat")
//   anon                <- the process's own heap/stacks
//   file                <- page cache (file contents)
//   slab_reclaimable    <- kernel slab that CAN be reclaimed (dentries, inodes)
//   inactive_file       <- the page cache kubelet subtracts

// workingSet is exactly what kubectl top reports:
workingSet := current - stat["inactive_file"]

That’s pretty much the entire trick. Once I printed these fields along with the Go runtime’s memory stats, the problem showed up immediately.

t=1245s  files_created=205469094  GO heap_alloc=1.3Mi  RSS=16.0Mi  ||  CGROUP current=455.9Mi  working_set=455.9Mi  anon=11.3Mi  file=0.0Mi  slab_recl=441.7Mi

Reading the line past the CGROUP bit:

anon=11.3Mi        # the actual running Go program
slab_recl=441.7Mi  # there it is

The slab is the allocator the Linux kernel uses for its own bookkeeping objects. Two of those matter here:

dentries  # the directory entry cache: every path lookup and every file creation
          # adds an entry so the kernel doesn't have to walk the filesystem again
inodes    # the in-memory representation of a file's metadata

When you use Go’s os.CreateTemp on Linux, it creates a new dentry and a new inode. os.Remove unlinks the file but the kernel doesn’t immediately free the associated dcache / icache entries. They go to a reclaimable slab list and sit there as warm cache. From the kernel’s point of view caching metadata is good since it makes the next lookup fast and cheap. What it didn’t know, in this particular case, was that I was never going to ask for file batch-h47ch37 again.

At 100k+ files per second, our workload was creating dentries and inodes faster than the kernel reclaimed them. The slab kept growing until memory pressure forced it back down.

I confirmed it by dropping the caches on the node:

$ echo 2 > /proc/sys/vm/drop_caches # drop dentries + inodes

working_set fell instantly.

None of this was the process’s memory. The kernel allocated it on the slab for its own caches. The only way my program found it was by reading the cgroup files directly.

Another realization was that kernel memory allocated on behalf of a cgroup is billed to that cgroup. That seems unfair until you consider the alternative: if it weren’t the case then a container could exhaust a node’s kernel memory for free.

This is what our alerts and autoscaler had been reacting to. There were zero restarts and zero OOM kills. The container was completely healthy, but kubectl top indicated that it was nearing the memory limit. That’s what led our internal alerts to fire, a phantom memory tax.

From a quick search online, I realized I wasn’t the first to experience this. An ipmi_exporter issue documents the same failure.

Why we see it in kubectl top

I was able to trace my way to find the missing memory. But I was still not sure why kubectl top counted it.

kubectl top queries the metrics.k8s.io Kubernetes API to read pod_memory_working_set_bytes. This metric shows the amount of memory a container is using. The way it gets this information is through a multi-step aggregation pipeline which includes cAdvisor all the way up to metrics-server.

The calculation is one subtraction:

# cgroup v2
working_set = total - inactive_file

# cgroup v1
working_set = total - total_inactive_file

Everything else counts, including the slab that held our dentries and inodes.

Kubernetes uses this value for its eviction mechanism as well as to decide when to OOM containers.

I found an upstream issue for this, from March 2017 with 140+ comments as of writing this post. The title is itself a question—“kubelet counts active page cache against memory.available (maybe it shouldn’t?)” Nine years later, it’s still open.

Some quick fixes

Obviously, I went back to sleep. But before doing so, I fixed the alert to use the ratio rss / request to measure when a pod is outgrowing its requested memory and working_set / limit to measure when a pod is on the brink of OOM’ing.

In summary, if Kubernetes is blowing up but your app looks fine, here are the three steps I suggest you follow to check what’s going on:

  1. Check the app’s view of its own memory. If the heap and RSS are small and flat, the missing memory is certainly not your process’s own memory.
  2. Ask the kernel cgroups for memory accounting directly by reading /sys/fs/cgroup/memory.stat. If slab_reclaimable is the larger number, it may be the dentry/inode cache due to filesystem churn.
  3. Confirm that the reclaimable cache is the culprit by running echo 2 > /proc/sys/vm/drop_caches on the node and watch the working set collapse.

I hope this helps future first responders.