kubernetes: kubelet counts active page cache against memory.available (maybe it shouldn't?)
Is this a request for help? (If yes, you should use our troubleshooting guide and community support channels, see http://kubernetes.io/docs/troubleshooting/.): No
What keywords did you search in Kubernetes issues before filing this one? (If you have found any duplicates, you should instead reply there.): active_file inactive_file working_set WorkingSet cAdvisor memory.available
Is this a BUG REPORT or FEATURE REQUEST? (choose one): We’ll say BUG REPORT (though this is arguable)
Kubernetes version (use kubectl version):
1.5.3
Environment:
-
Cloud provider or hardware configuration:
-
OS (e.g. from /etc/os-release): NAME=“Ubuntu” VERSION=“14.04.5 LTS, Trusty Tahr” ID=ubuntu ID_LIKE=debian PRETTY_NAME=“Ubuntu 14.04.5 LTS” VERSION_ID=“14.04”
-
Kernel (e.g.
uname -a): Linux HOSTNAME_REDACTED 3.13.0-44-generic #73-Ubuntu SMP Tue Dec 16 00:22:43 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux -
Install tools:
-
Others:
What happened: A pod was evicted due to memory pressure on the node, when it appeared to me that there shouldn’t have been sufficient memory pressure to cause an eviction. Further digging seems to have revealed that active page cache is being counted against memory.available.
What you expected to happen: memory.available would not have active page cache counted against it, since it is reclaimable by the kernel. This also seems to greatly complicate a general case for configuring memory eviction policies, since in a general sense it’s effectively impossible to understand how much page cache will be active at any given time on any given node, or how long it will stay active (in relation to eviction grace periods).
How to reproduce it (as minimally and precisely as possible): Cause a node to chew up enough active page cache that the existing calculation for memory.available trips a memory eviction threshold, even though the threshold would not be tripped if the page cache - active and inactive - were freed for anon memory.
Anything else we need to know: I discussed this with @derekwaynecarr in #sig-node and am opening this issue at his request (conversation starts here).
Before poking around on Slack or opening this issue, I did my best to read through the 1.5.3 release code, Kubernetes documentation, and cgroup kernel documentation to make sure I understood what was going on here. The short of it is that I believe this calculation:
memory.available := node.status.capacity[memory] - node.stats.memory.workingSet
Is using cAdvisor’s value for working set, which if I traced the code correctly, amounts to:
$cgroupfs/memory.usage_in_bytes - total_inactive_file
Where, according to my interpretation of the kernel documentation, usage_in_bytes includes all page cache:
$kernel/Documentation/cgroups/memory.txt
The core of the design is a counter called the res_counter. The res_counter
tracks the current memory usage and limit of the group of processes associated
with the controller.
...
2.2.1 Accounting details
All mapped anon pages (RSS) and cache pages (Page Cache) are accounted.
Ultimately my issue is concerning how I can set generally applicable memory eviction thresholds if active page cache is counting against those, and there’s no way to to know (1) generally how much page cache will be active across a cluster’s nodes, to use as part of general threshold calculations (2) how long active page cache will stay active, to use as part of eviction grace period calculations.
I understand that there are many layers here and that this is not a particularly simple problem to solve generally correctly, or even understand top to bottom. So I apologize up front if any of my conclusions are incorrect or I’m missing anything major, and I appreciate any feedback you all can provide.
As requested by @derekwaynecarr: cc @sjenning @derekwaynecarr
About this issue
- Original URL
- State: open
- Created 10 years ago
- Reactions: 210
- Comments: 141 (18 by maintainers)
Links to this issue
Commits related to this issue
- Set the memory limit to 200MB Two reasons why this is OK: - We have improved memory usage: https://github.com/GoogleCloudPlatform/google-fluentd/pull/197 - This seems to be right for workloads that... — committed to Stackdriver/kubernetes-configs by jkohen 7 years ago
- Set the memory limit to 200MB (#43) Two reasons why this is OK: - We have improved memory usage: https://github.com/GoogleCloudPlatform/google-fluentd/pull/197 - This seems to be right for workload... — committed to Stackdriver/kubernetes-configs by jkohen 7 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- Add k8s global memory indicators The kubelet will terminate end-user pods when the worker node has 'MemoryPressure' according to [1]. But confusingly, there exits two reasons for pods being evicted: ... — committed to bytedance/atop by ShirleyFei 4 years ago
- feat: add metrics for total_active_file and total_inactive_file memory The goal of this PR is to have additional cAdvisor metrics which expose total_active_file and total_inactive_file. Today workin... — committed to jrcichra/cadvisor by jrcichra 3 years ago
- feat: add metrics for total_active_file and total_inactive_file memory The goal of this PR is to have additional cAdvisor metrics which expose total_active_file and total_inactive_file. Today workin... — committed to jrcichra/cadvisor by jrcichra 3 years ago
- feat: add metrics for total_active_file and total_inactive_file memory The goal of this PR is to have additional cAdvisor metrics which expose total_active_file and total_inactive_file. Today workin... — committed to jrcichra/cadvisor by jrcichra 3 years ago
I’d like to share some observations, though I can’t say I have a good solution to offer yet, other than to set a memory limit equal to the memory request for any pod that makes use of the file cache.
Perhaps it’s just a matter of documenting the consequences of not having a limit set.
Or perhaps an explicit declaration of cache reservation should exist in the podspec, in lieu of assuming “inactive -> not important to reserve”.
Another possibility I’ve not explored is cgroup soft limits, and/or a more heuristic based detection of memory pressure.
Contrary Interpretations of “Inactive”
Kubernetes seems to have an implicit belief that the kernel is finding the working set, and keeping it in the active LRU. Everything not in the working state goes in the inactive LRU and is reclaimable.
A quote from the documentation [emphasis added]:
Compare a comment from mm/workingset.c in the Linux kernel:
While both Kubernetes and Linux agree that the working set is in the active list, they disagree about where memory in excess of the working set goes. I’ll show that Linux actually wants to minimize the size of the inactive list, putting all extra memory in the active list, as long as there’s a process using the file cache enough for it to matter (which may not be the case if the workload on a node consists entirely of stateless web servers, for example).
The Dilemma
One running an IO workload on Kubernetes must:
The Kernel Implementation
Note I’m not a kernel expert. These observations are based on my cursory study of the code.
When a page is first loaded,
add_to_page_cache_lru()is called. Normally this adds the page to the inactive list, unless this is a “refault”. More on that later.Subsequent accesses to a page call
mark_page_accessed()within mm/swap.c. If the page was on the inactive list it’s moved to the active list, incrementingpgactivatein /proc/vmstat. Unfortunately this counter does not distinguish between the anonymous and file LRUs, but examiningpgactivatein conjunction withnr_inactive_fileandnr_active_filegives a clear enough picture. These same counters are available withinmemory.statfor cgroups as well.Accessing a page twice is all that’s required to get on the active list. If the inactive list is too big, there may not be enough room in the active list to contain the working set. If the inactive list is too small, pages may be pushed off the tail before they’ve had a chance to move to the active list, even if they are part of the working set.
mm/workingset.c deals with this balance. It forms estimates from the inactive file LRU list stats and maintains “shadow entries” for pages recently evicted from the inactive list. When
add_to_page_cache_lru()is adding a page and it sees a shadow entry for that page it callsworkingset_refault()andworkingset_refaultis incremented in /proc/vmstat. If that returns true then the page is promoted directly to the active list andworkingset_activatein /proc/vmstat is incremented. It appears this code path does not incrementpgactivate.So a page accessed twice gets it added to the active list. What puts downward pressure on the active list?
During scans (normally by kswapd, but directly by an allocation if there are insufficient free pages),
inactive_list_is_low()may return true. If it does,shrink_active_list()is called.The comments to
inactive_list_is_low()are insightful:So, the presence of refaults (meaning, pages are faulted, pushed off the inactive list, then faulted again) indicates the inactive list is too small, which means the active list is too big. If refaults aren’t happening then the ratio of active:inactive is capped by a formula based on the total size of inactive + active. A larger cache favors a larger active list in proportion to the inactive list.
I believe (through I’ve not confirmed with experiment) that the presence of a large number of refaults could also mean there simply isn’t enough memory available to contain the working set. The refaults will cause the inactive list to grow and the active list to shrink, causing Kubernetes to think there is less memory pressure, the opposite of reality!
I ran into the same issue today. On node with 32GB memory, 16+GB is cached. When the memory used + cache exceeded 29GB (~90% of 32GB), the kubelet tried to evict all the pods which shouldn’t have happened since the node still had close to 50% of memory available, although in cache. Is there a fix to this issue?
Please do not use this issue as a catch-all for every kind of memory problem that might be encountered while running Kubernetes. While some kernels have bugs in cgroup accounting, this issue is not about that. Read the issue description carefully:
Take note: A pod was evicted due to memory pressure on the node. If you are experiencing OOM kills, where the kernel kills the process and “oom-killer” appears in the system log, you are not experiencing this issue. If you are unable to create docker containers, you are not experiencing this issue. If setting the memory limit equal to the request did not work for you, then the problem is not that the workaround failed, the problem is you are experiencing a different issue.
A pod eviction due to memory pressure on the node is not an OOM kill. The kernel will invoke the OOM killer when it is unable to service a page fault, due to insufficient physical RAM on the host or limits imposed on a particular cgroup. Kubernetes does not OOM kill.
A pod eviction is a decision made by Kubernetes. It depends on cluster configuration. “oom-killer” will not appear in the system logs, and the node condition may show
MemoryPressureif you manage to catch it at the right time.This issue is about that eviction logic in Kubernetes. It is not about the kernel. Even in the absence of any kernel bugs, a process can (will, if it does file IO) utilize page cache beyond its memory request, and up to but not beyond its memory limit, and then kubelet may decide the node is experiencing “memory pressure” and evict pods, even though the RAM usage is predominately cache and there is no actual memory pressure. It is, in my evaluation, a design bug in kubernetes due to a misunderstanding of what “active” cache means. It can not be fixed by upgrading the kernel or changing kernel parameters.
If you are experiencing OOM kills or a kernel bug, please don’t post about it here, as that only detracts from the actual issue.
Also having this problem. We had 53GB of available memory and 0.5GB free. 52.5GB is in buff/cache and it starts trying to kill pods due to SystemOOM.
Kubernetes resource limits are implemented with cgroups. It is intended for cgroups to limit all RAM, including cache. If you want to use available RAM as cache, you must set a bigger limit, or no limit.
Ostensibly, if Cassandra could run fine on 10 GB but it could be faster with up to 100 GB if it happened to be available, then you could set the RAM request to 10 GB and the limit to 100 GB.
The problem, and the topic of this bug, is if you then run a process which uses a lot of cache, kubernetes will then decide the node is experiencing “memory pressure” and evict pods, even though the kernel could evict that cache if there was any actual memory pressure. This is because the kubernetes logic (“active” pages probably aren’t reclaimable) is not in line with the reality in the kernel logic (an “active” page is anything that’s been used twice).
I think the intent is to avoid a less graceful OOM kill, but the effect in practice is the memory limit must always be set, and equal to the memory request. Otherwise pods keep getting evicted, usually the one that’s using the cache since it’s usually the one most over the memory request. Even if the application can tolerate the disruption, restarting the process on another node every time it’s warmed up it’s cache is rather pointless.
I don’t think you understand how cache works. Processes don’t control how much cache they use. A process that uses a lot of cache doesn’t deserve to be “penalized”. It’s done nothing wrong. It’s simply using that cache because it’s done some file IO.
It’s more efficient to use all available RAM for cache. Unused RAM does nothing but waste money, and it takes work to figure out what pages can be evicted from the cache. Why would you spend CPU time to evict pages from cache, when there’s nothing better to do with that RAM, and when you might be evicting something that could avoid a disk read in the future?
The problem is Kubernetes treats the perfectly normal and acceptable condition of using nearly all excess physical RAM as disk cache as an operational emergency, and starts evicting pods to “fix” it. So if you don’t want Kubernetes terminating your database every time it’s warmed up the disk cache, you must set a memory limit equal to the request, avoiding the situation entirely.
Would you rather:
If you choose the former, you must set a memory limit equal to the request. Not setting a memory limit, or setting it above the request, chooses the latter.
I have been waiting for 4 years!!!!! any news??
How can this be still open? Shouldn’t there be a way to reliably detect the available memory? I mean 5 years is a long time, someone might have invented subtraction and total and used memory calculation in the mean time. 😉
Nope!!! But thanks for pinging 54 people who are subscribed to this issue???
At this point in my research I’m wondering if drop_caches releases active page cache because it actually first moves pages to the inactive_list, then evicts from the inactive_list. And if something like that is happening, then maybe it’s not possible to determine what from the active_list cold be dropped without iterating over it, which is not something cadvisor or kubelet would do. I guess I was hoping there’d be some stats exposed somewhere that could be used as a heuristic to determine with some reasonable approximation what could be dropped without having to do anything else, but maybe that just doesn’t exist. But if that’s the case, then it I wonder how it’s possible to use memory eviction policies effectively.
At this point I’m sufficiently dizzy from reading various source code and documents, and I’m just going to shut up now.
Remaining problem here appears to be
vm.dirty_bytesconfiguration in kernel. This isn’t the read caches which are problematic (any more), it’s the write back cache.Memory is allocated into the writeback cache pool and attributed to a cgroup. However, that cache is only flushed once the system wide limits are exceeded. Per default 10% of total system RAM before write out begins asynchronously, 20% before write operations would even start blocking. All in expectation that disk access costs can be reduced by write-combining, so it does make at least some sense.
2009 there had been attempts to bring per-cgroup dirty limits into the kernel, but the discussion around the patch sets derailed into treating it as a performance (non-)optimization and the patch set was discarded.
Hard workaround: Explicitly set
vm.dirty_bytesto a significantly lower value, such thatvm.dirty_bytes+ working set < per cgroup limit.You should then also decrement
vm.dirty_background_bytesto 1/2 or 1/4 ofvm.dirty_bytes, and decrementvm.dirty_writeback_centisecssignificantly to ensure thatvm.dirty_background_bytesis checked often enough, and async writeback remains common case despite smaller buffers.Worst case, each cgroup can allocate all of
vm.dirty_bytesduring a burst write, on top of the regular working set. It’s essential that thevm.dirty_bytesquota must fit within the cgroup quota, or write back will never be throttled, resulting in OOM before stall.Be careful if you are relying on
mmap()syscalls anywhere though, they are also allocated fromvm.dirty_bytesquota. If you are in that unlucky situation, the only option left is to perform file writes from any context with bursts explicitly bypassing or flushing the write back cache (usingO_DIRECT,O_DSYNCor spammingfsync()etc.).Root cause is a design fault in the dirty page tracking in cgroups 2. It makes perfect sense to limit dirty pages locked in memory via explicit
mmap()and alike (as they can’t be freed), but it makes no sense to maintain the attribution after the process has already released the memory. Pressuring the kernel into prioritizing write back got it all backwards.container_memory_working_set_bytesis a cAdvisor metric, it has nothing to do with the Linux OOM killer. We must rid ourselves of this Kubernetes view point and look at what the kernel does.Clearly, inactive pages will always be reclaimed before an OOM kill. The kernel tries to keep a balance between active and inactive lists and adjusts them periodically, moving pages back from active to inactive. It should be noted here that the kernel is rather conservative and keeps pages in active list that haven’t been accessed for some time if there is no pressure to balance the lists, so the active list can be larger than the actual working set. It is my understanding that a page on the active list has to be unreferenced for two consecutive “cycles” to move back to the inactive list via asynchronous reclaim. An OOM kill happens when a page fault can not be satisfied from the kernel’s list of free pages and the synchronous direct reclaim fails to evict enough pages. The question is then, does the direct reclaim evict pages directly from the active list or at least rebalance it so that they can be evicted from the inactive list in the next scan?
The entry point for direct reclaim is
do_try_to_free_pageswhich callsshrink_zones, which further callsmem_cgroup_soft_limit_reclaimandshrink_node. Further following those two code paths shows that they both eventually end up atshrink_node_memcg. In this function, thefor_each_evictable_lruloop is our first hint that active file lru is considered evictable and will indeed be scanned for page reclaim. At the end,shrink_active_listfunction is called, which appears to move pages from active lru back to inactive lru, where they should be reclaimed in the next iteration ofshrink_zones(the reclaim algorithm is repeatedly executed with increasing priority/pressure when the previous iteration failed to reclaim enough pages).Here’s an older blog post from 2015 that also shows how
shrink_active_listis called in the direct reclaim code path for active file lru: https://chengyihe.wordpress.com/2015/12/04/kernel-mm-shrink_lruvec/ https://chengyihe.wordpress.com/2015/12/05/kernel-mm-shrink_active_list/And here is StackOverflow post where a user creates a Kernel patch specifically to avoid reclaim of active page cache.
While I’m far from an expert on the Linux reclaim algorithm, given this evidence I do believe that active file pages will generally be reclaimed before an OOM kill is triggered, absent new information.
I can imagine a few reasons why an OOM may occur while there is still active file usage reported: wrong NUMA zone, take too long to write back (file system locks preventing writeout), memory fragmentation, slow metrics collection, etc.
In any case, I don’t see what goal this is supposed to achieve. If this page cache is on the inactive lru, then it will surely be reclaimed before an OOM, I think everyone can agree on that. If it is on the active lru and part of the true working set, then dropping it manually will do nothing as it will be faulted in again almost immediately. If this page cache is “active” but not truly used, then the kernel will eventually move it back to inactive when balancing the lrus, where again it can be reclaimed.
Trying to summarize information on this for my own understanding… Any clarifications appreciated!
As far as I can tell, although it seems cgroup v2 alone may not fully address this, the memory QoS feature KEP 2570 introduced in k8s 1.22, which uses new features of cgroup v2, is meant to address this. This feature was further improved in k8s 1.27.
A comment in the PR for that KEP says:
However based on a careful reading of the changes in k8s 1.27, a Guaranteed pod (req=lim) no longer results in setting
memory.high. So the workaround described earlier in this thread using the Guaranteed QoS would no longer have the intended effect if Memory QoS is enabled. More specifically, this shows that in k8s >= 1.27 with memory QoS enabled, pods should be Burstable or Best Effort in order for memory.high to be set. From what I understood, you need to have memory.high to trigger the PSI (Pressure Stall) mechanism to try to reclaim some memory from page caches.The memory QoS feature gate remains alpha (off by default) in k8s 1.30.
We’ve noticed that prometheus with thanos sidecars increases
active_filein the prometheus container due to multiple processes reading the same file (prometheusandthanos-sidecar).active_filegets as big as the the amount of prometheus data files you have on disk as that’s what thanos is reading in full and shipping to S3.All the containers in this scenario have a generous guaranteed memory limit.
With large enough prometheus data retention / metric count and limited enough memory,
container_memory_working_set_byteshovers between 90% and 95% of the container memory limit, but the kernel will start shrinkingactive_fileonce it needs more memory for either other files or prometheus needs more memory (RSS).This makes it difficult to alert and know when prometheus instances with thanos sidecars are running out of memory and are close to OOM. I’m sure this applies to other heavy data workloads such as a mysql database with a backup sidecar.
In short,
container_memory_working_set_bytesisn’t always accurately describing when a container is nearing OOM from the kernel. In most cases it does, but not always.It would be great if
container_memory_working_set_bytesor a different metric excludedactive_fileand any other forms of evictable memory so we could accurately alert on close to OOM’ing containers consistently.Fair enough. This consideration kind of suggests that a new type of requests/limits has to be added: page cache. While it still cannot be counted as the actual process memory usage (RSS + swap), it cannot be totally ignored, either, since having a certain amount of page cache available (possible even dedicated) may be important for some types of workloads.
It seems that the kernel bug which causes this error is finally fixed now, and will be released in
kernel-3.10.0-1075.el7, which is due in RHEL 7.8, but goodness knows when that will be, as RHEL 7.7 only came out on August 6th, ~3 weeks ago.https://bugzilla.redhat.com/show_bug.cgi?id=1507149#c101
I’ve opened a cAdvisor PR to expose a non-evictable memory metric: https://github.com/google/cadvisor/pull/3445
Right now it excludes both
inactive_fileandactive_file. The goal for the PR is to have a metric which (as accurately as it can) exposes total non-evictable memory. That may mean additional cgroup fields are included/excluded over time.We have replicated this issue running on AKS where the “buff/cache” keeps increasing indefinitely up to the point the POD is evicted.
kubectl version:
Client Version: version.Info{Major:“1”, Minor:“19”, GitVersion:“v1.19.3”, GitCommit:“1e11e4a2108024935ecfcb2912226cedeafd99df”, GitTreeState:“clean”, BuildDate:“2020-10-14T12:50:19Z”, GoVersion:“go1.15.2”, Compiler:“gc”, Platform:“windows/amd64”}
Server Version: version.Info{Major:“1”, Minor:“18”, GitVersion:“v1.18.10”, GitCommit:“62876fc6d93e891aa7fbe19771e6a6c03773b0f7”, GitTreeState:“clean”, BuildDate:“2020-10-16T20:43:34Z”, GoVersion:“go1.13.15”, Compiler:“gc”, Platform:“linux/amd64”}
On the above image the memory used/allocated for the running dotnet program remains quite constant but the “buff/cache” eventually uses the entire memory causing the eviction.
This should not happen since buff/cache is reclaimable memory:
“buff/cache – is the combined memory used by the kernel buffers and page cache and slabs. This memory can be reclaimed at any time if needed by the applications.”
Alternatively, use
(posix_)fadviseand(POSIX_)FADV_DONTNEEDto push unneeded data out of the page cache proactively.In general, ‘due’ to how memory limits on CGroups works (at least when used through resource limits on Pods in K8s), which includes accounted
kmem(and, as such, block caches), I think it’s advisable not to setmemorylimits on stateful workloads using some kind of local volume/FS.The page cache being included in the memory accounting of a Pod makes a lot of sense in a way (it’s something to take into account when sizing systems anyway…), but at the same time most applications not being equipped to ‘manage’/limit the amount of cache they occupy (unlike e.g., memory) and getting OOM-killed as a result is troublesome. If the kernel would prioritize flushing the page cache occupied by data from processes in cgroups that are about to hit their memory limit, and maybe use uncached IO once such limit is reached (i.e., not let a Pod occupy more memory than allocated to it, i.e., it’s sized for, but also not halt servicing IO or OOMkill the process), that could be nice… This slower IO should then be observable through (application) metrics, at which point sizing/limits can be adjusted.
To my knowledge, the contents of these posts propagate myths.
I basically agree with what @tschuchortdev has been saying in this thread.
In my experience,
container_memory_working_set_bytesis a highly misleading metric and has been causing a large amount of confusion, myth, and miss-management of memory controls for a very long time now.The really difficult thing here is that memory accounting is very complicated. More complicated than one number can surface to users.
For OOMs that’s related to dirty pages, try setting
memory.highas 99% ofmemory.limit_in_bytesormemory.maxas a workaround. e.g.,Note that we are using a kernel that has backported
memory.highto cgroup v1.This is not expected behavior. The OS caching the memory has been around for a long time. Any app looking at memory usage should consider the cached memory. Using
nocacheis not an ideal solution either. Is there anyway we can bump up the severity/need on this issue? We’re planning to go into production soon but can’t without this issue getting fixedI forget where I read it but I heard that cgroups v2 was supposed to fix this. I think all you need to do is use a linux distro with cgroup v2 + update to kube 1.25 which makes kube cgroup v2 aware.
https://kubernetes.io/blog/2022/08/31/cgroupv2-ga-1-25/#:~:text=cgroup v2 provides a unified,has graduated to general availability.
It might be worth testing if this is still an issue in the latest version.
It’s quite obvious that cache memory is reclaimable memory, which can be freed nearly instantly if a process calls a new
malloc()and therefore it should not be counted in the pod memory usage. Otherwise it leads to wrong hardware allocation decisions, gives very confusing numbers inkubectl top pod, etc.For anything but performance tuning, the memory used by page cache must be considered the same as free memory.
In my particular case, I have a pod that uses 30 MB of RSS memory at most (there’s no swap), but because of intensive disk operations it uses a significant amout of page cache memory, and so
kubectl top podreports its usage at 3+ GB, which is clearly not the actual amount of memory the pod requires to run (cache is welcome, but not required). This also affects thekubectl top nodemetrics, which apparently also affects the autoscaling decision, which in turn leads to wasted money to run the nodes which otherwise would not be required.https://github.com/linchpiner/cgroup-memory-manager I am using this for workaround, for now, it works ok
Interesting…the nodes I executed the above tests on were GKE COS nodes
Swapping the node out for an Ubuntu node seems to correct the memory usage. The pod never uses more than 600 MiB of RAM according to
kubectl top pod.This is looking more and more like some kind of memory leak or misaccounting that’s present in the 4.4 series kernel used in COS nodes but not in the 4.13 series used by Ubuntu nodes.
/remove-lifecycle rotten
it seems like we’re affected by this problem as well. with tightly packed containers, long running jobs involving heavy disk I/O sporadically fail.
take this example:
Test this with:
the latter command might take a moment to become available.
The job tries to unpack 1TiB of zeroes (triple-compressed with zstd) - and apparently fails because of memory exhaustion by buffers filled by tar.
There seems to be the problem like https://serverfault.com/questions/704443/tar-uses-too-much-memory-for-its-buffer-workaround
The zstd used is a vanilla 1.2.0 packaged for xenial - previous versions are not multithreaded and have a slightly different file format.
Are you sure the page cache (active files) won’t cause OOM kills? When container_memory_working_set_bytes metric reaches the container memory limit, the container is expected to be OOM killed. This metric takes account into active page caches. That’s why some people here are desperately trying to drop caches for IO bound pods. Setting request=limit may help in node evictions but won’t help for OOM kills.
My understanding is as follows:
PSI is an observability feature that merely measures the delays caused by reclaim. In my opinion it has no relevance here. The kernel’s reclaim algorithm will trigger when cgroup v1’s memory.limit or cgroup v2’s memory.high or memory.max is reached. The only difference here between memory.high and memory.max is that memory.high will trigger earlier and not cause an OOM if the reclaim fails, but in both cases it will reclaim all page cache before failing.
TLDR: Slightly overcommit node memory available for scheduling. Use sensible memory.request and memory.limit values for all containers. If your application needs page cache to function, make room for it in your memory.request. If your nodes have swap enabled then cgroup v2’s memory.high (i.e. Kubernetes memory QoS feature) together with PSI metrics can gracefully degrade your workload giving you more time to increase memory.request before an OOM kill but does nothing new to solve the node pressure eviction issue that we’re talking about here.
Has anyone been able to confirm this?
The other option to consider here is to fast-track migrating to cgroup v2 and leverage https://www.kernel.org/doc/html/latest/accounting/psi.html per cgroup memory.pressure metric. Facebook have written about their usage and an userspace oomd killer here: https://facebookmicrosites.github.io/cgroup2/docs/memory-strategies.html
/remove-lifecycle stale
As part of other investigations we’ve been recommended to use https://github.com/Feh/nocache to wrap the corresponding calls, which helped a fairly big amount 😃
I also have the same issue in my k8s 1.15 cluster!!! any news regarding the issue???
It’s not caused by the kernel at all. The kernel is correctly reporting that RAM has been used for cache. The kernel, as always, will reclaim cache when RAM is needed for other purposes.
This is a basic misunderstanding of how RAM management works, pretty common among novice system administrators:
The issue (I’d call it a design bug) is that kubernetes makes decisions to evict pods based on this misunderstanding.
Stale issues rot after 30d of inactivity. Mark the issue as fresh with
/remove-lifecycle rotten. Rotten issues close after an additional 30d of inactivity.If this issue is safe to close now please do so with
/close.Send feedback to sig-testing, kubernetes/test-infra and/or
@fejta. /lifecycle rotten /remove-lifecycle staleThis works by clearing the page cache it seems, some apps can get their performance crippled with clearing the page cache if they are read intensive apps. It is a smart work-around, but be aware of what type of app you are running and how clearing the cache continuously might affect performance negatively, especially with network based storages.
Another +1 for this running as a Daemonset - immediate relief on memory pressure (cursory glance at
container_working_set_bytesis very promising).It’ll do for now 🤷
Hi folks – I was suffering from this problem too, and I think I have a workaround. Main problem is I didn’t really know the nuts and bolts of cgroups, and so k8s’ behavior was super non-intuitive to me in this case. The answer came from something @bitglue said on this thread way back in 2018: “Perhaps it’s just a matter of documenting the consequences of not having a limit set.”
TL;DR: Set a memory LIMIT on your pod, not just a request, and the kernel will flush the page cache so as to keep your pod under the limit and save it from being evicted by k8s due to too much active memory usage.
Here’s a snippet from my Argo workflow (basically a Pod Spec if you’re not familiar with Argo):
More detail if it’s interesting:
My pods: Batch jobs that pull a ~30GB file down (it’s DNA sequencing data), do some work (utilizing not more than a couple of GB of malloc’d RAM at any point), then upload some modestly sized results.
My cluster: Nodes with ~30GB of RAM is the salient detail. Coincidentally, that’s about the size of my data files, so loading them entirely into page cache will max out the RAM on the machine.
@sjenning, @derekwaynecarr: has there been any kind of discussion about this issue within the k8s team? Are there any next steps for this issue?
I would like to propose that a change is made in kubelet to allow different metrics to be used when evaluating pod memory usage. That would allow people to opt into more “aggressive” memory metrics (like referenced_memory, introduced in cadvisor in https://github.com/google/cadvisor/pull/2495) to fix these bogus MemoryPressure events, while retaining the standard behavior for anyone who isn’t hitting this. Does that sound like a reasonable way forward?
The work around of setting request = to limit did not work for us. The only thing we reliably use to get around this problem is by ensuring we are running with rhel kernel version of kernel-3.10.0-1075.el7 or greater in combination with the kernel setting --args=cgroup.memory=nokmem.
https://github.com/docker/for-linux/issues/841
I’m seeing a variant of this as well.
Scenario:
dentryby ~5mb each time (as reported by `/proc/slabinfo)This has a history of reports on CentOS 7 / Kernel 3.10. However, I am seeing it on a brand new GKE instance (Google Container OS 69, kernel 4.14.127+).
Here’s a pod definition that grows
dentrykmem quickly by simulating what curl’s thousands of access() calls would do (create negative cache entries for files that don’t exist):What does this look like in practice? Here’s what Google’s pod “Memory usage” chart shows for this pod after about 25 minutes:
In my test pod above, it’s worth noting that once the memory “usage” (cache included) hits the
limitsomething appears to garbage collect and the usage drops back down. However, in production (on pods affected by this issue), the memory usage never drops back down even after hitting the limit, withdentrykmem occupying almost all of the memory accounting for the pod.That said, I believe that filesystem cache should not count against a pod. What can we do to resolve this?
Hi @gcoscarelli , Did you see this issue? The issue happens on 3.10 kernel so it’s quite similar. https://github.com/kubernetes/kubernetes/issues/61937#issuecomment-469662772
Hi, we are experiencing a similar issue. We have java based service running in pods that have 3GB QoS memory settings. The service is disk intensive (keeps git repos), so eventually we hit this limit. We first thought that java was being OOM’ed but after some tests we realized that just with a plain pod (no java) doing file creations (via dd command) we still reached that limit, Kernel memory went up and up and up according to /sys/fs/cgroup/memory/memory.kmem.usage_in_bytes. The other thing we noticed is that even the container (not pod) is recreated after OOM, pod starts to be in Crash Loop path like if its memory was not being cleared between restarts. Only by deleting the pod made things go back to normal (until next crash of course). So my questions are:
I have found MongoDB workloads seem to also consistently recreate this problem. I am having to give pods +50% memory (around 50% of the dataset size) to prevent them from getting evicted even when the node still has 40% of its system memory in a reclaimable state. As such I’m migrating MongoDB out of Kubernetes.
Edit: As an interim solution, wouldn’t it be possible to make whether kubelet considers this cache toward available configurable?
Edit 2: Systemd handles this by providing both a LimitRSS and MemoryLimit which seems like a good solution as it gives enough configurable options to the user to handle workloads like ones that Kubernetes is currently evicting.
Solution Edit: It did not dawn on me that the Linux kernel would be aware of the memory limit inside of the container and only fill up page cache to that point. I just set the memory limit and request of the MongoDB pod to the (node’s memory available - 3GB).
Issues go stale after 90d of inactivity. Mark the issue as fresh with
/remove-lifecycle stale. Stale issues rot after an additional 30d of inactivity and eventually close.Prevent issues from auto-closing with an
/lifecycle frozencomment.If this issue is safe to close now please do so with
/close.Send feedback to sig-testing, kubernetes/test-infra and/or
@fejta. /lifecycle staleI have recently also faced this issue in cluster when exporting data to a cloud storage periodically. The memory manager (https://github.com/linchpiner/cgroup-memory-manager) did not work for me very well as it destroyed the performance of my original functionality. As I/O operation consumes page cache in linux by default, another workaround is to use the O_DIRECT flag to read/write data to bypass page cache in the system. It consumed quite some cpu & ram and affected performance to some extent, but we eventually managed to export files with an acceptable compromise in performance by setting a relatively large export batch size via testing. Hope this helps a bit if you also have similar memory issues with frequent I/O operations in cluster.
Using cgroups v2 does not seem to solve the problem. We have an AKS cluster, that runs cgroups v2 as default, and are still experiencing same problem.
/kind feature /lifecycle frozen 🏂 there isn’t a clear path forward, so we need somebody to adopt this and drive it 🤔 nobody in sig node is currently working on this.
sync && echo 1 > /proc/sys/vm/drop_caches or clear the disk data
After working with Google support about this issue impacting GKE, we have an issue filed here: https://issuetracker.google.com/issues/140577001
Ultimately, I was able to work around my immediate problem by identifying
curltriggering this problem, but the underlying cause is still present: The kernel and/or Kubernetes are incorrectly attributing memory “usage” in the filesystem cache to containers/pods and using that attribution to determine when a pod should be evicted.Some small workarounds:
NSS_SDB_USE_CACHE=no. This causescurlto avoid creating massive amounts of dentry per invocationlimitto be the same value as memoryrequest. This helps the kernel purge the file system cache when the pod hits this memory limit (where “hits” includes counting file system / dentry cache).I don’t know where the bug (or bugs) is, but I’m likely at the extent to which I can contribute to identifying the symptoms and areas affected. With this workaround, I’m able to spend less time on this problem.
+1 to https://github.com/kubernetes/kubernetes/issues/43916#issuecomment-2500992482. Setting
memory.highto be slightly lower than the eviction threshold should help ensure active pages that can be reclaimed are reclaimed before eviction kicks in, and solve this problem. It would need to be done on the allocatable cgroup.cc @dchen1107
We have tried @wenjianhn 's workaround setting
memory.high = 0.9 * memory.maxon some Pods with good results (at 99%, it was to late to start cleaning cache)We also noticed that Kubernetes 1.27: Quality-of-Service for Memory Resources (alpha) follows the same approach by improving the handling of
memory.max,memory.minandmemory.high.Above workaround unfortunately only works with cgroups v1, I believe this is a rough, quick-and-dirty bash equivalent for cgroups v2, only partly tested (I believe it works after running it for a couple days, but haven’t rigorously tested):
(part of a Daemonset definition that also dynamically provisions disks for swap)
maybe related to https://github.com/google/cadvisor/issues/3286
Here’s an idea: cgroups has a concept of a memory “soft limit”. The kernel docs describe them as:
This sounds pretty much identical to the kublet concept of “memory pressure”, right?
I haven’t read the code or tried to use soft limits, but AFAIK kubernetes makes no use of this feature. Being in the kernel, cgroups is much better positioned to actually know what can and cannot be reclaimed. Also, it can actually reclaim RAM, whereas kublet can only terminate the entire process.
So assuming soft limits work (again, I haven’t tested it at all), I would propose deleting all the memory pressure functionality in kublet, and instead setting the memory request as the cgroup soft limit.
I am also experiencing this problem. I will try the workaround of setting memory limit to memory request but, I would like to know if there are any plans to update how kubernetes calculates memory used (specifically it should not count buffer cache to determine OOM trigger)
@jordansissel I am having the same problem for apache spark container running on K8S and I am using redhat linux 7.6.It is noticed container memory grows over the period of time and it dies eventually with OOM I tried you solution to set the environment variable and it doesn’t seem to be working.
We don’t currently have a reliable reproducer for this, but we often hit this when restoring large PostgreSQL backups with
pg_basebackup. A particularly horrible but effective hack to help the backup restore process complete is to exec into the pod andsync; echo 1 > drop_cachesrepeatedly as suggested above (it also helps to sigstop/cont the backup process while flushing the cache).Is there a good way to fix this without a change to the kernel’s implementation of cgroups, though? Should this perhaps rather be a kernel bug?