Phase 30 of 30 · Topic 30.4

Container Resource Limits: Memory Limits & CPU Quota Tuning

1Concept

In Docker/Kubernetes with memory limits (e.g. `limits.memory: 512Mi`), the CLR GC automatically reads cgroup limits to size its generational heaps, preventing Out-Of-Memory (OOMKilled) pod crashes.

2Architecture Diagram

Kubernetes Pod Limit: 512MB RAM
       │
CLR Reads cgroups v2 memory.max
       │
Sizes Server GC Heap to stay under 400MB (Zero OOMKilled Restarts!)

3Code Example

C# 13 & .NET 9
using System;

public class CgroupTuningDemo
{
    public static void Main()
    {
        Console.WriteLine("Environment variables for containerized .NET:");
        Console.WriteLine("DOTNET_GCDynamicAdaptationMode = 1 (.NET 9 dynamically tunes GC for container limits)");
        Console.WriteLine("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT = 1");
    }
}

4Expected Output

Environment variables for containerized .NET:
DOTNET_GCDynamicAdaptationMode = 1 (.NET 9 dynamically tunes GC for container limits)
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT = 1

5Key Takeaways

  • .NET 9 introduces Dynamic Adaptation to Application Sizes (DATAS) for container GC.
  • Automatically adapts GC heap size to fluctuating container loads.
  • Set `DOTNET_GCHeapHardLimitPercent` if fine-grained heap thresholding is needed.