skip to content

As a lead, which GC settings would you standardise for a fleet of .NET 10 services in memory-limited containers, and how would you decide them?

level: principalimportance: should knowfreq 30%

answer

  1. defaults are a policy too
  2. flavor per service class
  3. headroom under the container limit
  4. one place for the settings
  5. evidence for every exception

basics

~20 s

Write one explicit baseline in a shared Directory.Build.props: GC flavor, DATAS, heap hard limit percent and any memory-conservation level, chosen per service class from load tests, with GC signals on every dashboard and evidence for each exception.

solid answer

~50 s

I would make the defaults explicit rather than invent new ones. Per service class: request-serving services on several cores keep **server GC with DATAS** (on by default for server GC since .NET 9), which sizes the heap to the live data; single-CPU containers and densely packed sidecars use workstation GC, or server GC with a capped `System.GC.HeapCount`. Every container gets a memory limit, and `System.GC.HeapHardLimitPercent` is set on purpose, lower for services with heavy native memory, rather than inherited at 75% by accident; `System.GC.ConserveMemory` is an option for memory-dense fleets that can spend CPU. The settings live in one shared `Directory.Build.props` (MSBuild properties plus `RuntimeHostConfigurationOption` items), because environment variables override them at start-up and scattered overrides drift. Service code may not call `GC.Collect()` or change latency modes without review. Every service exports pause percentage, gen 2 rate and heap size against the limit, and any deviation needs a load test that shows the gain.

code

xml · 13 lines
xml
<Project>
  <!-- Fleet GC baseline: every service inherits it; deviations need a load-test record. -->
  <PropertyGroup>
    <ServerGarbageCollection>true</ServerGarbageCollection>
    <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
    <GarbageCollectionAdaptationMode>1</GarbageCollectionAdaptationMode>
  </PropertyGroup>
  <ItemGroup>
    <!-- No MSBuild property exists for these; they are written to runtimeconfig.json. -->
    <RuntimeHostConfigurationOption Include="System.GC.HeapHardLimitPercent" Value="70" />
    <RuntimeHostConfigurationOption Include="System.GC.ConserveMemory" Value="3" />
  </ItemGroup>
</Project>

go deeper

for a junior

Recall that GC settings exist at all, that console and web projects default to different GC flavors, and that containers cap the heap below their limit.

for a middle

Explain each setting's three spellings, what the defaults are on .NET 10, and why a RuntimeHostConfigurationOption item is needed for some of them.

for a senior

Show how a load test and the GC signals justify each value, and how you would roll a changed baseline out without surprising any service.

for a principal

Own the trade between density, throughput and latency across the fleet, decide who may deviate, and tie every exception to evidence and a re-test date.

## What the defaults already decide A fleet with no GC settings still has a GC policy; it is just implicit, and it differs between project types: | Setting | Default on .NET 10 | Where it comes from | |---|---|---| | Flavor | Workstation; server for `Microsoft.NET.Sdk.Web` projects | `ServerGarbageCollection`, set by the Web SDK | | Background GC | On | `System.GC.Concurrent` = `true` | | DATAS | On, server GC only | `System.GC.DynamicAdaptationMode` = `1` since .NET 9 | | Heap hard limit in a container | 75% of the container limit (minimum 20 MB) | `System.GC.HeapHardLimitPercent` unset | | High memory threshold | 90% memory load | `System.GC.HighMemoryPercent` unset | | Memory conservation | Off | `System.GC.ConserveMemory` = `0` | A worker built on `Microsoft.NET.Sdk.Worker` and an API built on the Web SDK therefore run different GC flavors in the same cluster unless someone decides otherwise. The lead's job is to make that decision visible and deliberate. ## The decisions a lead owns 1. **Flavor per service class.** Request-serving services with several dedicated cores: server GC with DATAS, which starts with one heap and grows the heap count with load, so the heap tracks the live data rather than the node's core count. Single-CPU containers get workstation GC anyway, because the runtime falls back to it on one logical CPU. Small sidecars packed many to a node: workstation GC, or server GC with `System.GC.HeapCount` capped so a dozen processes do not start a GC thread per core each. 2. **DATAS on or off.** Keep it on by default. Its costs are more gen 0 and gen 1 collections and allocation waits while the heap count catches up at start-up or at the start of a peak; the docs report a 2-3% throughput loss for an over-80% working-set gain on one benchmark. Allow `GarbageCollectionAdaptationMode` = 0 only with a load test, and consider `System.GC.DTargetTCP` before switching it off. 3. **Memory headroom.** Every container has a memory limit. Set `System.GC.HeapHardLimitPercent` explicitly per class: lower for services with large native footprints (compression, native clients), up to the default for lean ones. The container kills the process when *total* memory crosses the limit, so the heap limit must leave room for everything else. 4. **Density versus CPU.** `System.GC.ConserveMemory` (1-9) makes the GC work harder to keep the heap small and compacts a fragmented LOH; it suits memory-bound fleets with spare CPU. 5. **Code rules.** No `GC.Collect()` in service code; `GCSettings.LatencyMode` changes and `GC.TryStartNoGCRegion` only with review; services resized in place call `GC.RefreshMemoryLimit()` (.NET 8) so the GC picks up the new limit. ## Where the settings live A runtime setting has up to three spellings: a runtimeconfig.json name (`System.GC.Server`), an MSBuild property (`ServerGarbageCollection`) and a `DOTNET_` environment variable (`DOTNET_gcServer`, hex values). Settings without an MSBuild property, such as `System.GC.HeapHardLimitPercent`, go in as `RuntimeHostConfigurationOption` items. Putting the baseline in a shared `Directory.Build.props` makes it versioned, reviewed and visible in every service's runtimeconfig.json. Environment variables win at start-up (in a .NET 10 run, `DOTNET_gcServer=0` beat `System.GC.Server: true`), so reserve them for emergencies and record them in the deployment manifest, never as silent per-environment drift. ## Evidence and guardrails - Every service exports the same GC signals: pause-time percentage, gen 2 rate, heap size against `TotalAvailableMemoryBytes`, and `FinalizationPendingCount`. - Changing the baseline or granting an exception needs a load test on production-like limits, comparing p99, throughput, CPU and memory. - Exceptions are written next to the service with their reason and the measurement, and reviewed when the runtime moves to a new major version, because GC defaults move (DATAS became the default in .NET 9). ## The trade-offs in one place | Choice | Buys | Costs | |---|---|---| | Server GC with DATAS | Throughput with a heap sized to live data | More ephemeral collections; waits while the heap count ramps up | | Workstation GC | Small memory and CPU footprint | Lower allocation throughput on many cores | | Lower heap hard limit | Room for native memory under the container limit | More frequent, more compacting full collections | | `ConserveMemory` | Smaller heaps, denser packing | More collection CPU and longer pauses |

  • Why keep fleet GC settings in the build rather than only in container environment variables?
    Settings in a shared Directory.Build.props are versioned, reviewed with the code and visible in each build's runtimeconfig.json. Environment variables are read at start-up and override runtimeconfig.json, so values spread across manifests drift silently between environments. Keeping environment variables for emergencies, recorded in the manifest, gives one source of truth and an escape hatch.
  • When would you let one service switch DATAS off?
    When a load test on production-like limits shows a throughput loss or start-up and peak-ramp allocation waits that break its latency target, and the service has dedicated cores and memory that make heap growth affordable. It sets `GarbageCollectionAdaptationMode` to 0, records the measurement next to the setting, and the exception is re-tested on the next major runtime upgrade.
  • How should a .NET service react when its container memory limit changes without a restart?
    Call `GC.RefreshMemoryLimit()`, available since .NET 8, which makes the GC re-read the memory limit and the hard-limit settings, including values set beforehand with `AppContext.SetData("GCHeapHardLimit", ...)`. It throws `InvalidOperationException` if the new hard limit would be below what is already committed, so a scale-down may need the heap reduced first.

  • Server GC suits every container, however few CPUs it gets.
  • Set GCHeapHardLimitPercent to 100 so the heap can use the whole container.
  • Turning DATAS off is the first step whenever throughput dips.
  • GC settings only matter for the largest services, so the rest can stay implicit.
  • Per-environment environment variables are the cleanest place for GC settings.

Assumes .NET 10: DATAS has been on by default for server GC since .NET 9, and GC.RefreshMemoryLimit exists since .NET 8.