📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How should you set Kubernetes CPU and memory requests and limits for a .NET 10 service? Explain how the GC and the thread pool read container limits, what CPU throttling does to latency, when to use DOTNET_GCHeapHardLimit or GCHeapHardLimitPercent, and how you size a pod from measurements.

Sizing .NET 10 pods: requests versus limits, QoS classes, how the runtime reads cgroup limits (ProcessorCount, GC heap hard limit at 75%), Server GC and DATAS, CFS CPU throttling and its latency impact, GC heap limit settings, and a measurement-driven sizing method.

Mid-Level Theory Intermediate containers cpu-throttling devops garbage-collection kubernetes resource-limits

🎯 Key points

  • Requests drive scheduling and QoS; limits are enforced by cgroups (OOMKill for memory, throttling for CPU)
  • .NET reads cgroup limits: ProcessorCount from the CPU limit (rounded up); GC heap hard limit defaults to 75% of the memory limit unless configured
  • No CPU limit: .NET sees all node cores; requests are ignored by the runtime
  • CFS quota per period (100 ms by default on Linux/Kubernetes): bursts from GC and startup JIT exhaust it and add latency
  • Server GC is the default for ASP.NET Core (Microsoft.NET.Sdk.Web) projects; DATAS (default since .NET 9) adapts heap count to load
  • DOTNET_GCHeapHardLimit (hex bytes) / DOTNET_GCHeapHardLimitPercent leave room for native memory
  • Size from load-test p95/p99 memory and CPU; monitor throttled periods, working set versus limit and OOMKilled counts
  • Common pattern: memory request = limit; CPU request set, CPU limit generous or absent

⏱ 30-second answer

Requests are what the scheduler reserves and set the pod's QoS class; limits are enforced by cgroups: exceed the memory limit and the container is OOMKilled, exceed the CPU limit and it is throttled within each 100 ms CFS period.

The .NET runtime reads the cgroup limits: Environment.ProcessorCount follows the CPU limit (rounded up) and the GC's heap hard limit defaults to 75% of the memory limit. With no CPU limit, .NET sees every node core.

I set memory request equal to limit, sized from load tests with headroom for native memory. For CPU I set a realistic request and a generous limit or none, because throttling turns GC and JIT bursts into p99 latency spikes. DOTNET_GCHeapHardLimitPercent is for when native memory needs more room. The trade-off is density versus tail latency.

🗣 Full answer (senior)

How I would answer this in an interview

"First, requests and limits do different jobs. The request is a reservation: the scheduler only places the pod on a node with that much unreserved CPU and memory, and it decides the QoS class. The limit is a ceiling enforced by the kernel's cgroups. Memory is incompressible, so crossing the memory limit gets the container OOMKilled. CPU is compressible, so crossing the CPU limit gets the container throttled: the CFS scheduler gives it a quota per 100 ms period, and once that's spent, every thread in the container waits for the next period.

The .NET runtime is container-aware. It reads cgroup v2 cpu.max and memory.max. Environment.ProcessorCount becomes the CPU limit rounded up, so a 1.5-core limit looks like 2 processors, and that drives Server GC heap count and thread pool sizing. If there's no CPU limit, .NET sees all the node's cores, even with a 250m request, because the runtime doesn't read requests; then I may set DOTNET_PROCESSOR_COUNT. On memory, the GC sets a heap hard limit of 75% of the container limit by default, leaving the rest for native memory: thread stacks, the JIT, SQL client buffers, gRPC and TLS. If an app uses a lot of native memory, I lower DOTNET_GCHeapHardLimitPercent; I rarely set an absolute DOTNET_GCHeapHardLimit. ASP.NET Core uses Server GC, and since .NET 9 DATAS is on by default, which adapts the number of heaps to load, so memory per pod is far lower than with classic Server GC.

For example, at [company] our [service] had p99 latency spikes of [400 ms] every few seconds with average CPU at only [40%]. container_cpu_cfs_throttled_periods_total showed throttling in [30%] of periods: gen0 GCs on 4 Server GC heaps burned the 1-core quota in bursts. We raised the CPU limit to [2], kept the request at [1], and p99 dropped to [90 ms]. The mistake I see is setting tight CPU limits 'to be safe' and then blaming .NET for tail latency."


Requests, limits and QoS

Setting Enforced by Effect when exceeded
CPU request Scheduler + CFS weights Guaranteed share under contention
CPU limit CFS quota (cpu.max) Throttled until next 100 ms period
Memory request Scheduler Eviction order under node pressure
Memory limit cgroup memory.max OOMKilled (exit code 137)
QoS class Rule Eviction priority
Guaranteed requests = limits for CPU and memory Last
Burstable some requests set Middle
BestEffort none set First

What .NET does with the limits

Runtime behaviour Source Override
Environment.ProcessorCount CPU limit, rounded up; node cores if no limit DOTNET_PROCESSOR_COUNT
GC heap hard limit 75% of memory limit (min 20 MB) DOTNET_GCHeapHardLimitPercent, DOTNET_GCHeapHardLimit (hex)
Server GC heap count ProcessorCount; adapted by DATAS DOTNET_GCHeapCount, DOTNET_GCDynamicAdaptationMode=0
Thread pool min threads ProcessorCount ThreadPool.SetMinThreads, System.Threading.ThreadPool.MinThreads

Production example

After load testing an API at 800 requests/s, peak working set was 310 MB with a 180 MB managed heap. We set memory request and limit to 512 Mi (75% hard limit = 384 MB heap ceiling, plenty for native), CPU request 500m and limit 2. OOMKills went to zero and throttled periods stayed under 1%.

🔍 What the interviewer is checking

Checks that the candidate understands how Kubernetes resource settings interact with the .NET runtime and can size pods from data.

Green flags

  • Distinguishes requests (scheduling) from limits (enforcement)
  • Knows .NET reads cgroup limits: ProcessorCount and the 75% heap hard limit
  • Explains CFS throttling and its effect on p99
  • Mentions DATAS / Server GC and native memory headroom
  • Sizes from load tests and metrics

Red flags

  • Thinks requests and limits are the same thing
  • Sets memory limit to the managed heap size
  • Never heard of CPU throttling

📚 Learn in depth

1. How CFS throttling works

 CPU limit = 1 core  →  quota 100 ms per 100 ms period

 period 1: |██████████ 4 threads × 25 ms = 100 ms used at t=25ms|░░░░ throttled 75 ms ░░░░|
 period 2: |██ normal ██|.............................................|

The quota is per container across all threads. A gen0 GC with 4 Server GC threads, or a burst of JIT at startup, can spend the whole quota in 25 ms of wall time, and then every request thread waits 75 ms. Average CPU looks fine; p99 doesn't. Watch container_cpu_cfs_throttled_periods_total / container_cpu_cfs_periods_total (in Azure Monitor Container Insights or Prometheus).

2. How the runtime reads limits

At start-up the runtime reads cgroup v1 or v2 files (/sys/fs/cgroup/cpu.max, memory.max). CPU: quota / period, rounded up, becomes the processor count (capped at node cores). Memory: the limit becomes TotalAvailableMemoryBytes, and when running in a container with a memory limit, the GC sets GCHeapHardLimit to 75% of it unless configured. When the heap approaches the hard limit, the GC collects more aggressively; if it still can't fit, you get OutOfMemoryException, which is different from an OOMKill by the kernel.

3. OOMException versus OOMKilled

OutOfMemoryException OOMKilled
Who .NET GC hit the heap hard limit Kernel: container total exceeded memory.max
Visible as Exception in logs, maybe a crash Exit code 137, Reason: OOMKilled, no managed logs
Usual cause Managed leak or limit too small Native memory growth, or heap limit + native > container limit

If you see OOMKilled with a small managed heap, look at native memory (the related Phase 1 question covers working set versus GC heap in depth).

4. Server GC, Workstation GC and DATAS

Server GC creates one heap and one GC thread per logical processor, which gives throughput but uses more memory. DATAS (Dynamic Adaptation To Application Sizes), on by default for Server GC since .NET 9, starts with one heap and grows the heap count with load, so a quiet pod uses a fraction of the memory. For tiny pods (under ~0.5 core and 256 MB) Workstation concurrent GC can be better: <ServerGarbageCollector>false</ServerGarbageCollector>.

5. A sizing method

  1. Load test at expected peak plus 30% with production-like data.
  2. Record working set, managed heap (dotnet-counters monitor System.Runtime), CPU and throttling.
  3. Memory limit = peak working set × 1.3–1.5; memory request = limit (avoids eviction surprises and noisy-neighbour OOMs).
  4. CPU request = steady-state p50–p90 usage; CPU limit = 2–4× request, or none if the cluster policy allows and you set DOTNET_PROCESSOR_COUNT.
  5. Use the Vertical Pod Autoscaler in recommendation mode to check, and the HPA on CPU or a KEDA metric for replicas.

Try it yourself

  1. Run a pod with limits.cpu: 500m and log Environment.ProcessorCount (expect 1).
  2. Run with no CPU limit on a 4-core node and see 4, regardless of the request.
  3. Load test with bombardier or k6 at CPU limits of 1 and 2; compare p99 and throttled periods.
  4. Set DOTNET_GCHeapHardLimitPercent=0x32 (50%, the value is hex) and watch GC.GetGCMemoryInfo().TotalAvailableMemoryBytes.
  5. Toggle DOTNET_GCDynamicAdaptationMode=0 and compare memory per pod at idle.

💻 Code

Resource settings for a .NET 10 API, with the runtime knobs that matter:

containers:
  - name: api
    image: crordersprod.azurecr.io/orders-api:1.4.2
    resources:
      requests:
        cpu: 500m          # what the scheduler reserves; steady-state usage
        memory: 512Mi
      limits:
        cpu: "2"           # generous, so GC/JIT bursts aren't throttled
        memory: 512Mi      # = request: predictable, no eviction surprises
    env:
      # GC heap ceiling as a percentage of the container limit (hex 0x46 = 70)
      # Lower than the 75% default because this app uses a lot of native memory (gRPC, SqlClient)
      - name: DOTNET_GCHeapHardLimitPercent
        value: "0x46"

A startup log line that makes the effective settings visible in Application Insights:

using System.Runtime;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var gc = GC.GetGCMemoryInfo();
app.Logger.LogInformation(
    "Runtime limits: ProcessorCount={Cpu}, GcHeapLimitMB={Heap}, ServerGC={Server}, LatencyMode={Mode}",
    Environment.ProcessorCount,
    gc.TotalAvailableMemoryBytes / 1024 / 1024,
    GCSettings.IsServerGC,
    GCSettings.LatencyMode);

app.MapGet("/", () => "ok");
app.Run();
# Is the container being throttled? (cgroup v2, from a debug container sharing the pod)
cat /sys/fs/cgroup/cpu.stat        # nr_periods, nr_throttled, throttled_usec
# Live runtime view
dotnet-counters monitor -p 1 System.Runtime --counters dotnet.gc.heap.total_allocated,dotnet.process.memory.working_set

⚠ Common mistakes

  • Mistake: Tight CPU limits equal to the request (for example 250m). Why it is wrong: GC and JIT bursts exhaust the CFS quota and add tens to hundreds of milliseconds to p99. Instead: Generous limits (2–4× the request) or none, and watch throttled periods.
  • Mistake: No CPU limit and no awareness of the effect. Why it is wrong: .NET sees all node cores (say 16), creates up to 16 Server GC heaps and a big thread pool in a pod that only has a 250m share. Instead: Set DOTNET_PROCESSOR_COUNT or rely on DATAS and verify memory use.
  • Mistake: Memory limit set from the managed heap size alone. Why it is wrong: Native memory (stacks, JIT, buffers) sits on top, so the kernel's OOM killer, which acts on the container's total cgroup memory and ignores the GC's view, kills the pod. Instead: Size from working set and keep the heap hard limit at 75% or lower.
  • Mistake: Memory request much lower than the limit. Why it is wrong: Nodes are overcommitted, and under node memory pressure the kubelet evicts Burstable pods first and the kernel's oom_score_adj (set from the QoS class) picks them as OOM victims. Instead: Memory request = limit for production APIs (Guaranteed or near it).
  • Mistake: Writing DOTNET_GCHeapHardLimitPercent=50. Why it is wrong: GC config env vars are parsed as hex, so 50 means 80%. Instead: 0x32 for 50%, or use runtimeconfig.json (System.GC.HeapHardLimitPercent), which takes decimal.
  • Mistake: Guessing sizes. Why it is wrong: Over-sizing wastes nodes; under-sizing causes OOMKills. Instead: Load test, measure, then set; review with VPA recommendations.
  • Mistake: Watching only average CPU and memory. Why it is wrong: Averages hide throttling bursts and slow memory climbs. Instead: Dashboards and alerts in Azure Monitor Container Insights or Prometheus/Grafana for throttled-period ratio (container_cpu_cfs_throttled_periods_total), working set as a percentage of limit, OOMKilled events and restart counts, alongside dotnet-counters / OpenTelemetry runtime metrics (GC heap size, GC pause time, thread pool queue length).

🏛 Senior insight: trade-offs

CPU limits are a trade-off between noisy-neighbour protection and tail latency, and for latency-sensitive .NET APIs I usually favour latency: set accurate requests (so scheduling and fair share work) and a high or absent CPU limit, with a namespace LimitRange or ResourceQuota as the guardrail. Memory is the opposite: always set the limit, make request equal limit, and treat any OOMKill as a bug to investigate, not something to tune away with more memory.

Approach When it fits Cost When not to
Request = limit (Guaranteed) Critical APIs, predictable latency Lower density Bursty batch work
Request < generous CPU limit Most .NET APIs Some overcommit Strict multi-tenant fairness
No CPU limit Platform allows, latency critical Needs DOTNET_PROCESSOR_COUNT awareness Shared clusters without quotas
Workstation GC Tiny pods, many replicas Lower throughput High-throughput APIs

I measure: throttled-period ratio, OOMKilled count, p99 latency, and requested-versus-used CPU per namespace in Cost Management or Kubecost.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions OOMKilled or native memory Why: Checks they can investigate OOMKills when the GC heap looks small
    How to answer

    RAM is physical memory. Each process gets a virtual address space that the OS maps onto RAM page by page. The working set is what's resident in RAM right now; private (committed) memory is what the process owns. The GC heap is only one part: native allocations (native libraries, NativeMemory, unmanaged buffers), thread stacks, JIT code, and runtime structures add to it. In Kubernetes, the cgroup limit counts all of it, and going over gets the container OOMKilled (exit code 137), not an OutOfMemoryException. So if the GC heap is small but the pod dies, I compare GC heap size with working set in dotnet-counters. A big gap points to native memory or too many threads; a growing GC heap points to a managed leak I'd chase with dotnet-gcdump. Then I fix the cause and set limits and GC settings deliberately.

  2. When: Candidate mentions CPU throttling or the scheduler Why: Checks their understanding of OS scheduling, time slices and CPU limits
    How to answer

    The scheduler keeps a queue of runnable threads per core and gives each a time slice. Scheduling is preemptive: when the slice ends, or a higher-priority thread becomes ready, the running thread is interrupted and another runs. Threads that wait for I/O, locks or timers are blocked and don't use CPU. Windows uses priority-based round-robin with temporary boosts; Linux uses a fair scheduler (CFS, and EEVDF from kernel 6.6). For a .NET service the practical points are: don't play with thread priorities; blocking threads wastes them; and in containers, a CPU limit is enforced as a quota per 100 ms period, so a burst of work can use the quota early and get throttled, causing latency spikes. Environment.ProcessorCount follows the limit and sizes the thread pool and GC.

🛠 Real-world problems: how you handle them

p99 latency spikes caused by CPU throttling on a tight limit
Situation
A [payments] API on AKS in Australia East, [6] replicas with CPU request and limit both [500m], serving [400] requests/s. The SLO is p99 under [200 ms].
Signals
p99 latency alerts at [450 ms] in bursts every few seconds while average CPU per pod showed only [45%]. No errors, no GC alerts. Customers reported intermittent slow checkouts.
Investigation
Container Insights showed a high throttled-period ratio ([35%]). `kubectl top pods` looked normal. Inside a debug container, `/sys/fs/cgroup/cpu.stat` confirmed rising `nr_throttled`. `dotnet-counters` showed gen0 GCs lining up with the spikes; Environment.ProcessorCount was 1, so Server GC with DATAS was small, but request threads plus GC still exhausted the 50 ms quota per period. Application Insights dependency timings were flat, ruling out SQL.
Resolution
Immediate: raised the CPU limit to [2] cores with the request at [500m]; p99 dropped to [110 ms] within minutes. Long term: load-tested to set the request at the real p90 usage ([700m]), added an HPA on CPU at 70% of request, and documented the policy.
Prevention
Alert on throttled-period ratio above 5%. A namespace LimitRange with a default limit of 4× the request. Load tests in CI for the hot paths with p99 gates. An ADR on CPU limit policy for latency-sensitive services.

How to tell it (STAR)

**S:** Our [payments] API on AKS had p99 spikes of [450 ms] against a [200 ms] SLO, yet average CPU was under half. **T:** I was asked to find out why before [the end-of-month peak]. **A:** I ruled out the database with Application Insights, then checked Container Insights and found [35%] of CFS periods throttled. The CPU limit equalled the request at [500m], so short bursts of GC and request work used the whole quota. I raised the limit to [2], set the request from load-test data, and added a throttling alert and a namespace default. **R:** p99 fell to [110 ms], we handled [the peak] with no SLO breach, and the CPU limit policy became a team standard.

↩ Usually asked after

More in Containers

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me