<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anders Pedersen on Medium]]></title>
        <description><![CDATA[Stories by Anders Pedersen on Medium]]></description>
        <link>https://medium.com/@anders_pedersen?source=rss-6f9e8a8039e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Anders Pedersen on Medium</title>
            <link>https://medium.com/@anders_pedersen?source=rss-6f9e8a8039e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:08:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anders_pedersen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[.NET Memory Dump Analysis with DumpLinq]]></title>
            <link>https://medium.com/@anders_pedersen/net-memory-dump-analysis-with-dumplinq-8a7a73f1c136?source=rss-6f9e8a8039e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7a73f1c136</guid>
            <category><![CDATA[memory-dump]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[debugging-tools]]></category>
            <dc:creator><![CDATA[Anders Pedersen]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 11:20:32 GMT</pubDate>
            <atom:updated>2026-02-28T11:20:32.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Long-running services that handle millions of requests will occasionally end up in a bad state and require a restart. When that happens, it can be a good idea to take a memory dump of the service.</p><p>A memory dump is a snapshot of a process’s memory that lets you inspect its state after failure.</p><p>Analyzing a memory dump in a debugger is similar to the experience when debugging and hitting a breakpoint, except that you cannot continue execution. E.g., if you open a memory dump in Visual Studio, you can use the usual debugging UI to jump between different threads and different stack frames of the thread, and if the compiler hasn’t optimized them away, you will be able to inspect local variables.</p><h3>Why do you need memory dumps?</h3><p>The most important property of a memory dump is that it preserves evidence. As soon as the process is restarted, the state that caused the service to misbehave is lost forever. Logs might tell you what the service thought it was doing, but are often incomplete or might even lie, a memory dump reflects the actual in-memory state of the process.</p><p>They are especially valuable in a production environment, where the service needs to be brought back to a healthy state as soon as possible to minimize disruption.</p><p>There are two main cases I see .NET memory dumps advocated for:</p><ol><li>Memory leaks</li><li>Threads that are stuck</li></ol><p>These are both valid use-cases that I also use memory dumps for, but an often overlooked, and in my opinion more powerful technique, is to use the dump to query the state of the process.</p><p>Think about it: A lot of the behavior of a process is dictated by the state of the process, and if a restart resolves the misbehavior, then there is a high probability that some state in the dump will explain the misbehavior, and perhaps there is even evidence of how the process ended up in that state.</p><p>Even when the dump doesn’t directly help you figure out what went wrong, it can still be useful for hypothesis testing, i.e. if you come up with a hypothesis for what happened, and you are able to use this hypothesis to make a non-trivial prediction about what the state of the program will look like, then you can use the dump to test that hypothesis. If the prediction turns out to be wrong, then either the hypothesis is incorrect, or the reasoning that led to the prediction is incomplete. If the prediction turns out to be true, you can have more confidence that you are fixing the right problem.</p><p>To show you how this can look in practice, I will go through two of my past investigations. I’ll use <a href="https://github.com/anderspedersen/DumpLinq">DumpLinq</a>, a library I made that makes it easy to use LINQ to query memory dumps like a database. Notice that I did not actually use DumpLinq for my original investigations, as it didn’t exist at the time. Instead, I used slower and more manual processes to achieve the same result.</p><h3>Investigation 1: The unbalanced load balancer</h3><p>For the first issue, after doing an intraday deployment of a service, we noticed a spike in CPU usage where some instances were running at close to their maximum capacity. Early on, it was determined that this was because most requests to that service were being served by a handful of instances, rather than being evenly distributed among all instances of the service.</p><p>The service uses client-side load balancing using a component we deliver, and I quickly suspected that something had caused this component to end up in a bad state, so before restarting one of the calling services, I had a memory dump of that service created. After restarting the calling service, the load was again being evenly distributed, so that confirmed my suspicion.</p><h4>Looking for anomalies</h4><p>When I started my analysis, I had little idea what could explain the behavior we were seeing. A weird detail was that health checks and other calls that weren’t being load-balanced were still coming through, so the client had to be aware of the other instances and able to talk to them. It just wasn’t sending any business traffic to them.</p><p>A tactic I like to employ, when I don’t know what I am looking for, is to just investigate the state of classes, which I think could be related to the issue at hand, and look for something that seems unusual. In this case, I thought it would be interesting to see what the component thought the service cluster looked like.</p><p>We have this class that represents a service instance inside the component:</p><pre>class ServiceInstance<br>{<br>  Version _version;<br>  Uri _requestUrl;<br>}</pre><p>(The class has been greatly simplified for the sake of this article. The real class has many more fields.)</p><p>DumpLinq makes it very easy to enumerate all instances of that class in the memory dump and print their state recursively:</p><pre>using dump = Dump.Load(@&quot;d:\mydump.dmp&quot;);<br><br>foreach (var obj in dump.EnumerateHeapObjects(&quot;*.ServiceInstance&quot;))<br>{<br>  Console.WriteLine(obj.ToString(depth: 3));<br>}</pre><p>DumpLinq expects fully-qualified type names (including namespace), but supports wildcard matching, so you can just replace the namespace with a wildcard, like I did with <strong>*.ServiceInstance</strong>.</p><p><strong>DumpObject.ToString</strong> will format the content of the object in a tree-like structure, and the <strong>depth</strong> parameter controls how many levels of nested objects will be expanded:</p><pre>ServiceName.Client.ServiceInstance @ 0x0000012ACE8B4ED8<br>  _version: Version @ 0x0000012ACE8B4EE8<br>    Major: 1<br>    Minor: 2<br>    Build: 3<br>    Revision: 0<br>  _requestUrl: System.Uri @ 0x0000012ACE8AFC20<br>    _string: &quot;tcp:\\server1:123&quot;<br>    _originalUnicodeString: null<br>    _syntax: System.UriParser+BuiltInUriParser @ 0x0000012ACE8B0710<br>    _flags: 81604378637<br>    _info: null<br>ServiceName.Client.ServiceInstance @ 0x0000012ACE8B4F58<br>  _version: Version @ 0x0000012ACE8B4F68<br>    Major: 1<br>    Minor: 2<br>    Build: 3<br>    Revision: 0<br>  _requestUrl: System.Uri @ 0x0000012ACE8B4F00<br>    _string: &quot;tcp:\\server2:123&quot;<br>    _originalUnicodeString: null<br>    _syntax: System.UriParser+BuiltInUriParser @ 0x0000012ACE8B0710<br>    _flags: 81604378637<br>    _info: null<br>ServiceName.Client.ServiceInstance @ 0x0000012ACE8B4FD8<br>  _version: Version @ 0x0000012ACE8B4FE8<br>    Major: 1<br>    Minor: 2<br>    Build: 4<br>    Revision: 0<br>  _requestUrl: System.Uri @ 0x0000012ACE8B4F80<br>    _string: &quot;tcp:\\server3:123&quot;<br>    _originalUnicodeString: null<br>    _syntax: System.UriParser+BuiltInUriParser @ 0x0000012ACE8B0710<br>    _flags: 81604378637<br>    _info: null<br>ServiceName.Client.ServiceInstance @ 0x0000012ACE8B5070<br>  _version: Version @ 0x0000012ACE8B5080<br>    Major: 1<br>    Minor: 2<br>    Build: 4<br>    Revision: 0<br>  _requestUrl: System.Uri @ 0x0000012ACE8B5018<br>    _string: &quot;tcp:\\server4:123&quot;<br>    _originalUnicodeString: null<br>    _syntax: System.UriParser+BuiltInUriParser @ 0x0000012ACE8B0710<br>    _flags: 81604378637<br>    _info: null</pre><p>From the output, it can be seen that the component thought that some of the service instances were running the old version (1.2.3.0) of the service we had just deployed, and some were running the new version (1.2.4.0). This seemed odd, but I wasn’t yet ready to jump the gun. Essentially, there were three options:</p><ol><li>This was unrelated to the issue we were facing, perhaps even expected behavior.</li><li>This was a symptom of the issue.</li><li>This was causing the issue.</li></ol><p>To test options 2 and 3, I came up with a prediction. If either of them were true, we would expect that the service instances that were getting traffic would show the one version, while the instances that were not getting traffic would show the other.</p><h4>Verifying the prediction</h4><p>In this simplified example, it’s easy to group the four instances at a glance. In the real investigation, there were 22 instances in the cluster, more than we could keep track of mentally, so let’s see how we can write a query to do this for us using DumpLinq.</p><p>The basic idea here is to use the LINQ extension method <strong>GroupBy</strong> to group by version. To get an object you can group by, you have two options:</p><p>If <strong>Version</strong> is an unmanaged struct (a struct that doesn’t contain any managed references) and you have access to that type from the DumpLinq script, then you can just read the value as that struct:</p><pre>var groups = dump.EnumerateHeapObjects(&quot;*.ServiceInstance&quot;)<br>    .GroupBy(x =&gt; x.GetField(&quot;_version&quot;).ReadAs&lt;Version&gt;().Value);<br><br>foreach (var group in groups)<br>{<br>    Console.WriteLine(&quot;Version: &quot; + group.Key + <br>                      &quot; Servers: &quot; + string.Join(&#39;;&#39;, group.Select(x =&gt; x<br>                          .GetField(&quot;_requestUrl&quot;)<br>                          .GetField(&quot;_string&quot;)<br>                          .AsString().Value)));<br>}</pre><p>If you don’t have access to the same type from the dump, or if it is not a struct, then you can always just use the primitive constituents in a tuple:</p><pre>var groups = dump.EnumerateHeapObjects(&quot;ServiceInstance&quot;)<br>    .GroupBy(x =&gt; (<br>        x.GetField(&quot;_version&quot;).GetField(&quot;Major&quot;).ReadAs&lt;int&gt;().Value,<br>        x.GetField(&quot;_version&quot;).GetField(&quot;Minor&quot;).ReadAs&lt;int&gt;().Value,<br>        x.GetField(&quot;_version&quot;).GetField(&quot;Build&quot;).ReadAs&lt;int&gt;().Value,<br>        x.GetField(&quot;_version&quot;).GetField(&quot;Revision&quot;).ReadAs&lt;int&gt;().Value));<br><br>foreach (var group in groups)<br>{<br>    Console.WriteLine(&quot;Version: &quot; + group.Key + <br>                      &quot; Servers: &quot; + string.Join(&#39;;&#39;, group.Select(x =&gt; x<br>                          .GetField(&quot;_requestUrl&quot;)<br>                          .GetField(&quot;_string&quot;)<br>                          .AsString().Value)));<br>}</pre><p>For the approach with an ad-hoc tuple, we get the following output:</p><pre>Version: (1, 2, 3, 0) Servers: tcp:\\server1:123;tcp:\\server2:123<br>Version: (1, 2, 4, 0) Servers: tcp:\\server3:123;tcp:\\server4:123</pre><p>The output confirmed that the instances that were getting traffic were the same instances that the client component thought were running the latest version, and for the instances that were not getting traffic, it thought they were running the old version.</p><h4>Fixing the issue</h4><p>After gaining confidence that the versions were related to the issue, I searched through the code looking for places that read the version (to try to see if the different versions were causing the behavior), and I quickly discovered that we had some code in the load balancer that would prioritize instances with a higher version number. So this explained why the instances that the client component thought were running an old version were not getting any traffic.</p><p>The next step was to figure out why the client component had ended up in that state. I shared my findings with my colleague, and he immediately had a guess at how this could happen. It turned out we had a logic bug in the code that updated the client component’s view of the cluster, which caused <strong>_version</strong> not to be updated in some cases.</p><p>So, because we were able to view the state of the failed process, we had a fix for the problem before the day was over. If we hadn’t used a memory dump to gain insight, I am not convinced we would even have found the issue.</p><h3>Investigation 2: The stuck scheduler</h3><p>The second issue, which querying a memory dump helped solve, happened during the start-up of a service. When the service starts, it loads a snapshot of the current state of the system. Loading the snapshot uses the same custom scheduling mechanism that is used for later state changes, so when the snapshot is loaded, a bunch of work items are enqueued in our internal scheduler, which will then process them to create the initial state.</p><p>What we observed was that this would get stuck on rare occasions. According to logs, there were still work items waiting to be processed, but for some reason, none of our worker threads were picking them up. As a result, the service never came online and had to be restarted.</p><h4>Lock-free scheduling</h4><p>I won’t try to give you the full overview of the custom scheduling logic that was implemented, but one thing you need to know is that there were multiple work item queues and fewer worker threads, so with the intention to make sure that all non-empty queues will be processed by exactly one worker thread, the following lock-free code was implemented:</p><pre>void ExecuteWorkItems()<br>{<br>  // Empty queue and execute all work items<br>  while (_queue.TryDequeue(out var workitem))<br>  {<br>    workitem.State = State.Running;<br>    workitem.Execute();<br>    workitem.State = State.Completed;<br>  }<br><br>  // Work queue is not being executed anymore<br>  _running = 0;<br>  <br>  // Check if another thread has added items to queue<br>  if (_queue.IsEmpty)<br>    return;  <br><br>  // Only one thread should call ScheduleQueue<br>  if (Interlocked.CompareExchange(ref _running, 1, 0) == 0)<br>  {<br>    ScheduleQueue();<br>  }<br>}<br><br>void ScheduleWorkItem(WorkItem workitem)<br>{<br>  // Enqueue work item<br>  workitem.State = State.Scheduled;  <br>  _queue.Enqueue(workitem);<br><br>  // If queue is already running, nothing more to do<br>  if (_running != 0)<br>    return;<br><br>  // Only one thread should call ScheduleQueue<br>  if (Interlocked.CompareExchange(ref _running, 1, 0) == 0)<br>  {<br>    ScheduleQueue();<br>  }<br>}</pre><p>If you are not used to seeing lock-free code, then the above code might be a bit hard to understand. The basic idea is that if a worker thread, <strong>Thread A</strong>, is running <strong>ExecuteWorkItems</strong> and finishes at around the same time as another thread, <strong>Thread B</strong>, enqueues a work item by calling <strong>ScheduleWorkItem</strong>, then we want to make sure that exactly one of the threads calls <strong>ScheduleQueue</strong>.</p><p>If <strong>Thread A</strong> sets <strong>_running</strong> to zero before <strong>Thread B</strong> enqueues the work item, then <strong>Thread B</strong> will not return early.</p><p>If <strong>Thread B</strong> enqueues the work item before <strong>Thread A</strong> sets <strong>_running</strong> to zero, then <strong>Thread A</strong> will not return early.</p><p>If they do it around the same time, then neither will return early.</p><p>In all cases, at least one thread will reach the <strong>Interlocked.CompareExchange</strong>, and exactly one will succeed in changing <strong>_running</strong> from 0 to 1. That thread becomes responsible for calling <strong>ScheduleQueue</strong>.</p><h4>Testing the assumption</h4><p>At this point, I was fairly certain that the problem was elsewhere. After all, I am only showing a small slice of the complex scheduling logic, so there were many other places the problem could hide.</p><p>Nevertheless, since I had a copy of the process state, it should be possible to determine definitively that a non-empty queue was not left unscheduled.</p><p>There are multiple ways this could be tested. The obvious way would be to query the dump for non-empty queues, but the underlying queue is a <strong>ConcurrentQueue</strong>, and <a href="https://github.com/microsoft/referencesource/blob/ec9fa9ae770d522a5b5f0607898044b7478574a3/mscorlib/system/collections/Concurrent/ConcurrentQueue.cs#L261">determining if a <strong>ConcurrentQueue</strong> is empty</a> is not as simple as reading a single field.</p><p>Since we set the State of a <strong>WorkItem </strong>to <strong>Scheduled </strong>when we enqueue it, and to <strong>Running </strong>as soon as we dequeue it, I figured I could just query the dump for <strong>WorkItem</strong> instances where <strong>State</strong> was set to <strong>Scheduled</strong>.</p><pre>using dump = Dump.Load(@&quot;d:\mydump.dmp&quot;);<br><br>var instances = dump.EnumerateHeapObjects(&quot;*.WorkItem&quot;)<br>      .Where(wi =&gt; wi<br>        .GetField(&quot;State&quot;)<br>        .ReadAs&lt;State&gt;() == State.Scheduled);<br><br>foreach (var instance in instances)<br>{<br>  Console.WriteLine(instance.ToString());<br>}</pre><p>To my big surprise, I found that such instances actually existed.</p><h4>Memory reorderings</h4><p>My previous reasoning for the lock-free code implicitly assumed sequential visibility of writes across cores. That assumption was wrong. On x64, writes performed on one core are not guaranteed to be immediately visible to other cores, so-called Store-Load reorderings are possible. So it was entirely possible for both threads to return without having called <strong>ScheduleQueue</strong>.</p><p>Explaining the x64 memory model is beyond the scope of this article, but to solve the issue, I inserted a memory barrier after each of the writes. This stalls the current core until its memory writes are globally visible.</p><pre>void ExecuteWorkItems()<br>{<br>  // Empty queue and execute all work items<br>  while (_queue.TryDequeue(out var workitem))<br>  {<br>    workitem.State = State.Running;<br>    workitem.Execute();<br>    workitem.State = State.Completed;<br>  }<br><br>  // Work queue is not being executed anymore<br>  _running = 0;<br><br>  // Make sure write to _running is visible to other threads before continuing<br>  Interlocked.MemoryBarrier();<br>  <br>  // Check if another thread has added items to queue<br>  if (_queue.IsEmpty)<br>    return;  <br><br>  // Only one thread should call ScheduleQueue<br>  if (Interlocked.CompareExchange(ref _running, 1, 0) == 0)<br>  {<br>    ScheduleQueue();<br>  }<br>}<br><br>void ScheduleWorkItem(WorkItem workitem)<br>{<br>  // Enqueue work item<br>  workitem.State = State.Scheduled;  <br>  _queue.Enqueue(workitem);<br><br>  // Make sure updates to _queue is visible to other threads before continuing<br>  Interlocked.MemoryBarrier();<br><br>  // If queue is already running, nothing more to do<br>  if (_running != 0)<br>    return;<br><br>  // Only one thread should call ScheduleQueue<br>  if (Interlocked.CompareExchange(ref _running, 1, 0) == 0)<br>  {<br>    ScheduleQueue();<br>  }<br>}</pre><h4>Was the dump needed?</h4><p>At first glance, it might not be obvious how the memory dump actually helped in this investigation: I thought <em>X</em> wasn’t possible. Then I found evidence that <em>X</em> was actually happening, and soon after, I realized how <em>X</em> could occur.</p><p>So, did the memory dump actually help me solve the second investigation? Absolutely! I don’t think I would have solved this issue without the aid of the memory dump.</p><p>This is actually something I have experienced several times in my career when debugging: I initially think something is not possible, then I find evidence that it is happening, and soon after, I realize how it can happen.</p><p>I cannot explain it, but narrowing down the possibility space often lets me see something I had previously missed. In this case, I did not have a good understanding of the x64 memory model before the investigation. Seeing the evidence forced me to dig deeper.</p><h3>Conclusion</h3><p>I have covered two examples of investigations, where I queried a memory dump to learn more about the state of the process, which in both cases helped me solve issues that would otherwise have been very hard to solve.</p><p>I hope this has given you some inspiration for how you can use this technique yourself. Querying memory dumps can both be really challenging and really fun. You need a deep knowledge of not only your own types, but also the .NET framework and third-party libraries you use, to know what different states look like. Coming up with ways to test your hypotheses requires creative thinking paired with deep technical knowledge.</p><p>But when you manage to validate your hypotheses, you can be confident that you are fixing the right problem.</p><p>If you want to give DumpLinq a try, you can find it here:<br><a href="https://github.com/anderspedersen/DumpLinq">GitHub</a> <a href="https://www.nuget.org/packages/DumpLinq/">NuGet</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7a73f1c136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diagnosing Latency in .NET: Background GC and the Large Object Heap]]></title>
            <link>https://medium.com/@anders_pedersen/diagnosing-latency-in-net-background-gc-and-the-large-object-heap-09449162b399?source=rss-6f9e8a8039e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/09449162b399</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Anders Pedersen]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 04:56:12 GMT</pubDate>
            <atom:updated>2025-07-01T04:54:55.515Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently encountered a performance issue where some requests occasionally took up to 20 seconds to complete. Usually these requests take at most a few milliseconds.</p><p>Interestingly, the slow requests would come in groups exactly every half hour, and only for certain combinations of request parameters. And while the slow requests of a group would start at different times, they would all finish at almost the same time.</p><h3>Initial analysis</h3><p>This, to me, suggested that something was running every half hour that held a lock (or similar) for a long time, which was needed for doing these requests. This would explain why the requests would all finish at almost the same time (when the lock was released).</p><p>Initially, I ruled out the Garbage Collector (GC) since GC pauses would affect all requests, not just a subset based on request parameters, and a GC is usually being performed when a thread runs out of memory — not on a schedule every half hour.</p><p>After a quick look through our code base and asking my colleagues if they knew of anything that ran every half hour and held a lock (neither of which provided any leads), I decided that I needed a minidump to see where the threads were blocked.</p><p>To get a minidump, I wrote some code that would create a minidump when the service was handling more than 100 requests at the same time. Our service handles thousands of requests per second, but most of them take at most a few milliseconds, so it is unusual for our service to handle more than a handful of requests concurrently, except for when things go bad. So, by creating a minidump when the service reaches 100 concurrent requests, there is a good chance that the call stacks will show where the threads are blocked.</p><p>Now I just had to wait for my changes to be deployed to our staging servers, where I could reproduce the problem. I decided not to rush the change out, so following our weekly release schedule, it would take a couple of days for my changes to be deployed to our staging servers.</p><h3>Discovering a strange GC pattern</h3><p>While I waited, I made another discovery. By looking at the .NET performance counters, I discovered that the <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap">Large Object Heap</a> (LOH) was growing and shrinking repeatedly every half hour, and the slow calls always happened around the same time as the LOH shrank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*E1igLpSZ3i4MlNVb-I7Rnw.png" /></figure><p>At this point, I was still convinced that the GC wasn’t to blame, but I also felt that the two events matched too well to be a coincidence. Maybe both were caused by another event? For example, it could be some clean-up code that ran every half hour, which made a lot of objects on the LOH unreachable, and which also held a lock that was needed for these requests.</p><p>So if I could just figure out what was causing LOH allocations, maybe that would point me in the right direction. So I decided to use <a href="https://github.com/microsoft/perfview">PerfView</a> to collect <a href="https://learn.microsoft.com/en-us/windows/win32/etw/about-event-tracing">ETW</a> events in our staging environment, while I repeatedly made requests of the type that was causing problems.</p><p>The .NET runtime emits <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/diagnostics/runtime-events">a wide range of ETW events</a>, which can be traced using tools like PerfView. To find the source of the LOH allocations, I am interested in the <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/diagnostics/runtime-garbage-collection-events#gcallocationtick_v3-event">GC/AllocationTick</a> event, which is emitted when approximately 100 KB has been allocated, along with information about the last object that was allocated, including the call stack of where it was allocated. If enough of these samples are collected, it will give you a fairly accurate picture of where memory was allocated.</p><p>The GC/AllocationTick can be viewed aggregated by call stacks in the <em>GC Heap Alloc</em> view in PerfView:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFkQNsV9Wg9V7bUf0okMQA.png" /></figure><p>Looking at the call stacks, I identified the source of the LOH allocations. It was a large dictionary that was used for the request. I wrote this code myself, and I remember I had assumed that the dictionary would only ever contain a few items, but now it contained over a thousand elements. The dictionary was only alive for the duration of the request, so that disproved my hypothesis about some clean-up code, which made the large objects unreachable.</p><p>In the light of this discovery, it would make sense to rewrite the code to allocate less and smaller objects, but this didn’t help me figure out what was blocking the slow requests… Or did it? At this point, I started to suspect that perhaps it was a background garbage collection (BGC), and perhaps something was blocking access to the LOH during BGC.</p><p>So I pulled out my copy of <a href="https://www.amazon.com/Pro-NET-Memory-Management-Performance/dp/B0D3PNGKZR"><em>Pro .NET Memory Management</em></a> to see if it mentioned something like this, and found the following passage:</p><blockquote>“If a user thread wants to allocate a large object during Concurrent Sweep of LOH, it is blocked until its end.”</blockquote><p>Perhaps this was what happened? The sweep phase is only part of the GC, and 20 seconds sounds like a lot to sweep an LOH that was a few GB large, but I had never measured how long it actually takes, so what did I know? At this point, all I could do was to wait for the minidump that would hopefully either confirm or disprove this hypothesis.</p><h3>Analyzing the minidump</h3><p>A few days later, my changes were deployed to our staging environment, and I reproduced the issue again to get a minidump. I opened the minidump in WinDbg and found one of the BGC threads:</p><pre>0:166&gt; kc<br> # Call Site<br>00 coreclr!SVR::CObjectHeader::GetMethodTable<br>01 coreclr!SVR::my_get_size<br>02 coreclr!SVR::gc_heap::background_mark_simple1<br>03 coreclr!SVR::gc_heap::background_mark_simple<br>04 coreclr!SVR::gc_heap::background_mark_object<br>05 coreclr!SVR::gc_heap::background_drain_mark_list<br>06 coreclr!SVR::gc_heap::background_mark_phase<br>07 coreclr!SVR::gc_heap::gc1<br>08 coreclr!SVR::gc_heap::bgc_thread_function<br>09 coreclr!&lt;lambda_49aa4b87d825ca15a3d8aaf393009812&gt;::operator()<br>0a kernel32!BaseThreadInitThunk<br>0b ntdll!RtlUserThreadStart</pre><p>The BGC threads did indeed show that a BGC was in progress, but to my surprise, the stacks showed that they were still in the middle of the mark phase, and not the sweep phase as my new hypothesis would have predicted. The next step was to find a blocked thread and see where exactly it was blocked:</p><pre>0:281&gt; kc<br> # Call Site<br>00 ntdll!NtWaitForSingleObject<br>01 KERNELBASE!WaitForSingleObjectEx<br>02 coreclr!GCEvent::Impl::Wait<br>03 coreclr!GCEvent::Wait<br>04 coreclr!WKS::gc_heap::user_thread_wait<br>05 coreclr!SVR::gc_heap::background_gc_wait<br>06 coreclr!SVR::gc_heap::wait_for_background<br>07 coreclr!SVR::gc_heap::allocate_uoh<br>08 coreclr!SVR::gc_heap::try_allocate_more_space<br>09 coreclr!SVR::gc_heap::allocate_more_space<br>0a coreclr!SVR::gc_heap::allocate_uoh_object<br>0b coreclr!SVR::GCHeap::Alloc<br>0c coreclr!Alloc<br>0d coreclr!AllocateSzArray<br>0e coreclr!JIT_NewArr1<br>[...]</pre><p>A method named <em>allocate_uoh</em> called <em>wait_for_background</em>. This sounded promising. Now I just had to figure out how the thread ended up in that state. Luckily, the .NET runtime is open source, so I headed over to GitHub to take a look at <a href="https://github.com/dotnet/runtime/blob/efd5742bb5dd1677fbbbeb277bcfb5c9025548e5/src/coreclr/gc/gc.cpp#L18559"><em>allocate_uoh</em></a>. This method contained the following logic, which could end up calling <em>wait_for_background</em>:</p><pre>int spin_for_allocation = (gen_number == loh_generation) ?<br>    bgc_loh_allocate_spin() :<br>    bgc_poh_allocate_spin();<br>    <br>if (spin_for_allocation &gt; 0)<br>{<br>    add_saved_spinlock_info (true, me_release, mt_alloc_large, msl_status);<br>    leave_spin_lock (&amp;more_space_lock_uoh);<br>    bool cooperative_mode = enable_preemptive();<br>    GCToOSInterface::YieldThread (spin_for_allocation);<br>    disable_preemptive (cooperative_mode);<br><br>    msl_status = enter_spin_lock_msl (&amp;more_space_lock_uoh);<br>    if (msl_status == msl_retry_different_heap) return a_state_retry_allocate;<br><br>    add_saved_spinlock_info (true, me_acquire, mt_alloc_large, msl_status);<br>    dprintf (SPINLOCK_LOG, (&quot;[%d]spin Emsl uoh&quot;, heap_number));<br>}<br>else if (spin_for_allocation &lt; 0)<br>{<br>    msl_status = wait_for_background (awr_uoh_alloc_during_bgc, true);<br>    check_msl_status (&quot;uoh a_state_acquire_seg&quot;, size);<br>}</pre><p>So the decision to call <em>wait_for_background</em> is made in <a href="https://github.com/dotnet/runtime/blob/efd5742bb5dd1677fbbbeb277bcfb5c9025548e5/src/coreclr/gc/gc.cpp#L18304C14-L18304C35"><em>bgc_loh_allocate_spin</em></a> (if its return value is negative). Let’s have a look:</p><pre>int gc_heap::bgc_loh_allocate_spin()<br>{<br>    size_t min_gc_size = dd_min_size (dynamic_data_of (loh_generation));<br>    size_t bgc_begin_size = bgc_begin_loh_size;<br>    size_t bgc_size_increased = bgc_loh_size_increased;<br>    size_t end_size = end_loh_size;<br><br>    return bgc_allocate_spin(min_gc_size, bgc_begin_size, bgc_size_increased, end_size);<br>}</pre><p><em>bgc_loh_allocate_spin</em> just fetches some fields related to the LOH and calls <a href="https://github.com/dotnet/runtime/blob/efd5742bb5dd1677fbbbeb277bcfb5c9025548e5/src/coreclr/gc/gc.cpp#L18276"><em>bgc_allocate_spin</em></a>:</p><pre>// We need to throttle the UOH allocations during BGC since we can&#39;t<br>// collect UOH when BGC is in progress (when BGC sweeps UOH allocations on UOH are disallowed)<br>// We allow the UOH heap size to double during a BGC. And for every<br>// 10% increase we will have the UOH allocating thread sleep for one more<br>// ms. So we are already 30% over the original heap size the thread will<br>// sleep for 3ms.<br>int bgc_allocate_spin(size_t min_gc_size, size_t bgc_begin_size, size_t bgc_size_increased, size_t end_size)<br>{<br>    if ((bgc_begin_size + bgc_size_increased) &lt; (min_gc_size * 10))<br>    {<br>        // just do it, no spinning<br>        return 0;<br>    }<br><br>    if ((bgc_begin_size &gt;= (2 * end_size)) || (bgc_size_increased &gt;= bgc_begin_size))<br>    {<br>        if (bgc_begin_size &gt;= (2 * end_size))<br>        {<br>            dprintf (3, (&quot;alloc-ed too much before bgc started&quot;));<br>        }<br>        else<br>        {<br>            dprintf (3, (&quot;alloc-ed too much after bgc started&quot;));<br>        }<br><br>        // -1 means wait for bgc<br>        return -1;<br>    }<br>    else<br>    {<br>        return (int)(((float)bgc_size_increased / (float)bgc_begin_size) * 10);<br>    }<br>}</pre><h3>Finding the reason for the blocked requests</h3><p>The source code for <em>bgc_allocate_spin</em> revealed what had happened:</p><p>During BGC, threads can still allocate. If a thread exceeds its allocation budget, the runtime is allowed to perform a blocking gen1/0 GC while the BGC is running (a so-called foreground GC). However, the GC is not allowed to perform a gen2 GC, and since the LOH is considered part of gen2, there is a real possibility that LOH allocations will result in an Out-of-Memory exception. To prevent this, the runtime throttles LOH allocations during BGC. It does this using the following rules:</p><ol><li>If the size of the LOH at the start of this BGC has doubled since it was last collected, then block until BGC is done</li><li>If the current size of the LOH has doubled since the start of this BGC, then block until BGC is done.</li><li>Otherwise, sleep for 1 ms, for every 10% the LOH has grown since the start of this BGC.</li></ol><p>Based on the LOH size reported by our .NET performance counters, our service triggered the first rule: The LOH had doubled in size since it was last collected, so LOH allocations were blocked until the BGC was done.</p><h3>Last piece of the puzzle</h3><p>At this point, I mostly had an understanding of what had happened, but there was still one thing that I couldn’t quite figure out. Why did the BGC run almost exactly every half hour?</p><p>To figure this out, I used PerfView to get a second trace. This time, I traced the service on a dev environment for half an hour to gather GC events emitted during the BGC.</p><p>First, we look at the <em>GC/Start</em> events, and find one for the process which has <em>Type=”BackgroundGC”</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Unh-s629mjylo7nYk1C5w.png" /></figure><p>We can see that the event has <em>Reason=“InducedNotForced”</em>. <em>Induced</em> means that the GC was asked to do a collection by some external (non-GC) code. <em>NotForced</em> means that the decision of whether to do a blocking collection or a background GC was left up to the GC. This could explain why a BGC was triggered every half hour. Now we just need to figure out who requested the GC.</p><p>To figure out who triggered the GC, we need a call stack from where the GC was triggered. The <em>GC/Start</em> event does not have a call stack (and it wouldn’t be of any use, as our service is running with ServerGC, so the <em>GC/Start</em> event is emitted by a GC thread). So, to get a call stack, we instead look at the <em>GC/Triggered</em> event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZMNGJooVo05ptR2p7VU6A.png" /></figure><p>We can see that the <em>GC/Triggered</em> event has <em>HasStack=”True”</em>, meaning that we can get the call stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*XeImInzDZVF5Db12XhIyuw.png" /></figure><p>From the call stack, we can see that the GC was triggered from the Finalizer thread from a method named <em>DoExtraWorkForFinalizer</em>.</p><h3>Another look at the runtime source code</h3><p>We head to the runtime repository to take a look at <a href="https://github.com/dotnet/runtime/blob/efd5742bb5dd1677fbbbeb277bcfb5c9025548e5/src/coreclr/vm/threads.cpp#L7117"><em>DoExtraWorkForFinalizer</em></a>:</p><pre>void Thread::DoExtraWorkForFinalizer()<br>{<br>    CONTRACTL {<br>        THROWS;<br>        GC_TRIGGERS;<br>    }<br>    CONTRACTL_END;<br><br>    _ASSERTE(GetThread() == this);<br>    _ASSERTE(this == FinalizerThread::GetFinalizerThread());<br><br>#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT<br>    if (RequiresCoInitialize())<br>    {<br>        SetApartment(AS_InMTA);<br>    }<br>#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT<br><br>    if (RequireSyncBlockCleanup())<br>    {<br>#ifndef TARGET_UNIX<br>        InteropSyncBlockInfo::FlushStandbyList();<br>#endif // !TARGET_UNIX<br><br>#ifdef FEATURE_COMINTEROP<br>        RCW::FlushStandbyList();<br>#endif // FEATURE_COMINTEROP<br><br>        SyncBlockCache::GetSyncBlockCache()-&gt;CleanupSyncBlocks();<br>    }<br>    if (SystemDomain::System()-&gt;RequireAppDomainCleanup())<br>    {<br>        SystemDomain::System()-&gt;ProcessDelayedUnloadLoaderAllocators();<br>    }<br><br>    if(m_DetachCount &gt; 0 || Thread::CleanupNeededForFinalizedThread())<br>    {<br>        Thread::CleanupDetachedThreads();<br>    }<br><br>    if (YieldProcessorNormalization::IsMeasurementScheduled())<br>    {<br>        GCX_PREEMP();<br>        YieldProcessorNormalization::PerformMeasurement();<br>    }<br><br>    ThreadStore::s_pThreadStore-&gt;TriggerGCForDeadThreadsIfNecessary();<br>}</pre><p>There is no call to<em> GarbageCollect</em>, but this is not unexpected. Various compiler optimizations (such as inlining) can make frames disappear from the call stack. However, one method name caught my attention, <em>TriggerGCForDeadThreadsIfNecessary</em>.</p><p>This method is quite large, so I will not repeat all of it here, but basically it finds the oldest generation that contains dead threads (threads that stopped executing, but where the managed <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread">Thread</a> object has not yet been collected), and then asks the GC to collect this generation (<a href="https://github.com/dotnet/coreclr/pull/10413">so the thread’s finalizer can run, and release some OS handles</a>). To prevent this logic from triggering too many GCs it contains <a href="https://github.com/dotnet/runtime/blob/efd5742bb5dd1677fbbbeb277bcfb5c9025548e5/src/coreclr/vm/threads.cpp#L5548">the following logic</a>:</p><pre>// Make sure that enough time has elapsed since the last GC of the desired generation. We don&#39;t want to trigger GCs<br>// based on this heuristic too often. Give it some time to let the memory pressure trigger GCs automatically, and only<br>// if it doesn&#39;t in the given time, this heuristic may kick in to trigger a GC.<br>SIZE_T gcLastMilliseconds = gcHeap-&gt;GetLastGCStartTime(gcGenerationToTrigger);<br>SIZE_T gcNowMilliseconds = gcHeap-&gt;GetNow();<br>if (gcNowMilliseconds - gcLastMilliseconds &lt; s_DeadThreadGCTriggerPeriodMilliseconds)<br>{<br>    return;<br>}</pre><p>So if less than <em>s_DeadThreadGCTriggerPeriodMilliseconds</em> milliseconds have passed, then this method will return without triggering a GC.</p><p>Next, we find where this variable is configured:</p><pre>RETAIL_CONFIG_DWORD_INFO(INTERNAL_Thread_DeadThreadGCTriggerPeriodMilliseconds, W(&quot;Thread_DeadThreadGCTriggerPeriodMilliseconds&quot;), 1000 * 60 * 30, &quot;In the heuristics to clean up dead threads, this much time must have elapsed since the previous max-generation GC before triggering another GC will be considered&quot;)</pre><p>And what do you know! The value is set to half an hour. This explains why our service was running a BGC every half hour.</p><h3>Conclusion</h3><p>To fix the issue, I rewrote the code to not allocate a huge dictionary when handling these requests, and I put an alarm in place that will alert us if the LOH ever doubles between GCs in the future, so we will know we have introduced an unhealthy allocation pattern.</p><p>To my surprise, I have not found anyone describing this behavior of the GC and the problems it can cause online. And it is also not mentioned in the <a href="https://www.amazon.com/Pro-NET-Memory-Management-Performance/dp/B0D3PNGKZR"><em>Pro .NET Memory Management</em></a><em> book</em>.</p><p>Part of the reason is probably that our use pattern is unusual: Our service caches a lot of data, so it has a huge managed heap that needs to be marked when doing a BGC. And it handles thousands of requests per second, so BGC is probably being interrupted a lot by foreground GCs. I believe it is rather unusual for BGCs to take over 10 seconds.</p><p>Another reason might also be that people are not aware that this is happening. After learning of this behavior, I revisited an old case of unexplained pauses, where we had not been able to find the cause, and based on the available evidence, I concluded that it was likely also caused by LOH allocations being blocked during BGC.</p><p>So I hope this article will help other people trying to diagnose similar problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09449162b399" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>