skip to content

A .NET 10 order-matching service in a 2 GiB container has p99 latency spikes that line up with gen 2 collections; how do you find the cause and fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. which kind of full collection
  2. GCKind.FullBlocking vs Background
  3. what consumed the budget
  4. 75% of the container
  5. fix the trigger before the knob

basics

~20 s

Classify the gen 2 collections and find their trigger with GC.GetGCMemoryInfo and GC.CollectionCount: LOH churn, a heap near the container's default 75% limit, GC.Collect calls or gen 2 growth. Remove that trigger before tuning GC settings.

solid answer

~50 s

First classify the collections: `GC.GetGCMemoryInfo(GCKind.FullBlocking)` and `GC.GetGCMemoryInfo(GCKind.Background)` show whether the spikes come from blocking full collections or background ones, with `PauseDurations`, `Compacted` and `PauseTimePercentage`, and `GC.CollectionCount(2)` against the request rate gives their frequency. Then find the trigger. Buffers of 85,000 bytes or more churn the large object heap budget and force gen 2s. In a 2 GiB container the GC heap limit defaults to 75%, about 1.5 GiB, and a heap that grew after the deploy runs closer to it, while memory load at 90% of the container limit pushes the GC towards compacting full collections. Explicit `GC.Collect()` calls are full blocking collections, and medium-lived objects promoted into gen 2 raise its cost. Fix the cause: reuse large buffers, delete induced collections, find what grew the heap, and only then consider `GCLatencyMode.SustainedLowLatency`, which trades a bigger heap for fewer blocking gen 2s.

code

csharp · 14 lines
csharp
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

// Stand-in for the service: 300 KB order-book snapshots built and dropped.
for (int i = 0; i < 2_000; i++) _ = new byte[300_000];

GCMemoryInfo last = GC.GetGCMemoryInfo();
GCMemoryInfo full = GC.GetGCMemoryInfo(GCKind.FullBlocking);
GCMemoryInfo background = GC.GetGCMemoryInfo(GCKind.Background);

Console.WriteLine($"gen2 collections: {GC.CollectionCount(2)}; last GC: gen {last.Generation}, compacted={last.Compacted}");
Console.WriteLine($"last full blocking GC #{full.Index}, last background GC #{background.Index}");
Console.WriteLine($"heap {last.HeapSizeBytes >> 20} MB of a {last.TotalAvailableMemoryBytes >> 20} MB GC limit");
Console.WriteLine($"pause time in GC: {last.PauseTimePercentage}%, finalization pending: {last.FinalizationPendingCount}");

go deeper

for a junior

Recall that gen 2 collections are full collections, that some of them block every thread, and that GC.Collect() forces one.

for a middle

Explain how LOH churn, memory load near the container limit and induced collections each trigger gen 2, and what the 75% default heap limit means.

for a senior

Demonstrate the order of work: classify collections with GCKind, find the trigger, fix the code, and reach for latency modes only with a load test behind them.

for a principal

Turn the incident into fleet guardrails: standard GC signals on every dashboard, no induced collections in service code, and memory limits set with explicit headroom.

## Classify the collections first "Gen 2 lines up with p99" covers several different events, and each has a different fix. The in-process API answers the first questions without any external tool: | Call | What it reports | |---|---| | `GC.GetGCMemoryInfo()` (`GCKind.Any`) | The most recent collection of any kind | | `GC.GetGCMemoryInfo(GCKind.Ephemeral)` | The most recent gen 0 or gen 1 collection | | `GC.GetGCMemoryInfo(GCKind.FullBlocking)` | The most recent blocking gen 2 collection | | `GC.GetGCMemoryInfo(GCKind.Background)` | The most recent background gen 2 collection | Each `GCMemoryInfo` carries `Index`, `Generation`, `Compacted`, `Concurrent`, `PauseDurations`, `HeapSizeBytes`, `FragmentedBytes`, `PromotedBytes`, `FinalizationPendingCount` and `TotalAvailableMemoryBytes`, plus the process-wide `PauseTimePercentage`. `GC.CollectionCount(2)` sampled once a second against the request rate gives the full-collection rate, and `GC.GetTotalPauseDuration()` the cumulative pause. Blocking, compacting full collections with long `PauseDurations` are the classic p99 spike; background collections pause briefly but still burn CPU. Counter tools show the same data live, and they belong with the diagnostics tooling. All of these numbers depend on the machine and the GC mode, so compare before and after on the same host type. ## The usual triggers in a memory-limited container 1. **Large object heap churn.** Order-book snapshots or serialized batches of 85,000 bytes or more are allocated on the LOH. Its allocation budget is consumed directly, and exceeding it triggers a gen 2 collection that also examines the whole small object heap, including the long-lived order book. 2. **Memory pressure against the limit.** Inside a container the memory limit is treated as the machine's physical memory. With no settings, the GC heap hard limit (`GCHeapHardLimit`, maximum commit for the heap and its bookkeeping) defaults to 75% of the container limit, or 20 MB if that is larger: about 1.5 GiB of a 2 GiB container. At a memory load of 90% (`System.GC.HighMemoryPercent`), the GC favours full compacting collections over background ones, and the docs state that the LOH is compacted automatically when a hard limit is in force, which means copying large objects during those collections. A heap that "keeps growing after a deploy" pushes the service into that regime. 3. **Induced collections.** `GC.Collect()` is a full blocking collection of every generation. A timer or a library that calls it every few minutes produces spikes on a schedule. 4. **Gen 2 growth from promotion.** Objects that live just long enough to be promoted, such as per-order caches with expiry or objects held by finalizers, inflate gen 2, so each full collection marks more. ## Fixes, in order - **Remove the trigger.** Reuse large buffers instead of allocating them per message (pooling mechanics belong with the material on memory buffers), and delete `GC.Collect()` calls from service code. - **Find the growth.** Compare `HeapSizeBytes` after successive full collections; a rising floor means something retains more after the deploy. Heap snapshots that show what holds it belong with the diagnostics tools. - **Give the heap honest headroom.** If the live set legitimately grew, raise the container limit or set `System.GC.HeapHardLimitPercent` deliberately, leaving room for native memory: the container kills the process when *total* memory crosses its limit, whatever the managed heap is doing. - **Only then tune latency.** Change `GCSettings.LatencyMode` or the LOH threshold with a load test showing the effect. ## Latency-mode tools and their limits | Tool | Effect | Constraint | |---|---|---| | `GCLatencyMode.Interactive` | Default with background GC | None | | `GCLatencyMode.SustainedLowLatency` | Suppresses foreground (blocking) gen 2; keeps gen 0, gen 1 and background gen 2 | Needs background GC; larger heap, more fragmentation; blocking collections still happen under memory pressure | | `GCLatencyMode.LowLatency` | Suppresses gen 2 for short periods, except under low memory or an induced gen 2 | Workstation GC only | | `GC.TryStartNoGCRegion(totalSize)` | No collections while allocations stay within `totalSize` | `totalSize` at most the ephemeral segment size; `GC.EndNoGCRegion()` throws `InvalidOperationException` if a collection was induced or allocations exceeded it | `SustainedLowLatency` fits a bounded busy window, such as trading hours, in a container with spare memory. In a container already near its limit it moves the problem: the heap grows, memory load rises, and the blocking collections come back.

  • When is GCLatencyMode.SustainedLowLatency the right fix in .NET?
    When the spikes are blocking gen 2 collections during a bounded busy period and the process has memory headroom. The mode suppresses foreground gen 2 collections while keeping gen 0, gen 1 and background gen 2, so it needs background GC enabled. The heap grows and, without compaction, fragments more, and blocking collections still happen under memory pressure, so it is wrong for a container already near its limit.
  • Why does the .NET GC heap default to 75% of a container's memory rather than all of it?
    Inside a container the GC treats the memory limit as physical memory and, with no settings, sets the heap hard limit to 75% of it, or 20 MB if that is larger. The remaining quarter is headroom for memory the GC heap does not hold, such as native allocations and thread stacks. The container kills the process when total memory crosses its limit, regardless of the managed heap.
  • What does GC.TryStartNoGCRegion offer, and why is it rarely the fix for a service?
    It asks the GC to perform no collections while the process allocates up to `totalSize` bytes, which must not exceed the ephemeral segment size, and returns whether that was possible. `GC.EndNoGCRegion()` throws `InvalidOperationException` if a collection was induced or allocations overran. That suits a short, bounded critical section, not a service that allocates continuously across many concurrent requests.

  • Background GC means gen 2 collections cannot cause latency spikes.
  • By default the GC heap may use the container's entire memory limit.
  • Calling GC.Collect() in quiet periods is a safe way to prevent busy-time pauses.
  • SustainedLowLatency turns off gen 2 collections entirely.
  • Raising the container memory limit always shortens gen 2 pauses.