<p>I am trying to understand the behavior of K8S POD memory allocation and so far no luck on the materials I read on the internet.</p>
<p>My question is, If I have a POD template defined with the below values for the memory</p>
<pre><code>Limits:
  cpu:     2
  memory:  8Gi
Requests:
  cpu:     500m
  memory:  2Gi
</code></pre>
<p>And say my application suddenly requires more memory and the POD allocates <code>4Gi</code> ( from <code>2Gi</code> initial memory ) to get the task done. Would the POD give back the extra <code>2Gi</code> it acquired back to the underlying OS and become a <code>2Gi</code> POD again after the task is complete or would it function as a POD with <code>4Gi</code> memory afterward.</p>
<p>My application is a Java application running on Apache Tomcat having the max heap defined for <code>6Gi</code>.</p>

Klaus
<p>The Kubernetes resource requests come into effect at basically three times:</p>
<ol>
<li><p>When new pods are being initially scheduled, the resource requests (only) are used to find a node with enough space.  The sum of requests must be less than the physical size of the node.  Limits and actual utilization aren't considered.</p>
</li>
<li><p>If the process allocates memory, and this would bring its total utilization above the pod's limit, the allocation will fail.</p>
</li>
<li><p>If the node runs out of memory, Kubernetes will look through the pods on that node and <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/#pod-selection-for-kubelet-eviction" rel="nofollow noreferrer">evict the pods whose actual usage most exceeds their requests</a>.</p>
</li>
</ol>
<p>Say you have a node with 16 GiB of memory.  You run this specific pod in a Deployment with <code>replicas: 8</code>; they would all fit on the node, and for the sake of argument let's say Kubernetes puts them all there.  Regardless of what the pods are doing, a 9th pod wouldn't fit on the node because the memory requests would exceed the physical memory.</p>
<p>If your pod goes ahead and allocates a total of 4 GiB of memory, that's fine so long as the physical system has the memory for it.  If the node runs out of memory, though, Kubernetes will see this pod has used 2 GiB more than its request; that could result in the pod getting evicted (destroyed and recreated, probably on a different node).</p>
<p>If the process did return the memory back to the OS, that would show up in the &quot;actual utilization&quot; part of the metric; since its usage would now be less than its requests, it would be in less danger of getting evicted if the node did run out of memory.  (Many garbage-collected systems will hold on to OS memory as long as they can and reuse it, though; see <em>e.g.</em> <a href="https://stackoverflow.com/questions/30458195/does-gc-release-back-memory-to-os">Does GC release back memory to OS?</a>.)</p>
