Slow but constant memory increase in .net web services on Linux
Description
We deploy an Asp.Net web service on AKS Linux nodes (.Net version 8.0). The service behavior is pretty standard: it accepts incoming https requests and makes outbound https requests. All outbound requests use the HttpClient class and the IHttpClientFactory pattern. The factory creates a SocketsHttpHandler periodically and eventually replaces the old one. Http clients are created by the factory on the fly and always disposed. As far as I can tell the code always disposes the HttpResponseMessage objects it gets from HttpClient.SendAsync() calls. We don't see any SNAT port exhaustion.
Yet over time, the total memory consumed by the application pods steadily increases to the maximum allowed by the AKS deployment configuration; then eventually the pods are killed. It takes a few days to get there, but the pods invariably reach that limit. Memory goes up, garbage collector occasionally brings it down, but over time there's a steady increase. The service caches some data, but all caches eventually expire.
I captured full dumps with tools like dotnet-dump and dotnet-gcdump, but they have not been useful. All the stats reported by dotnet-dump show that the heap and the total memory consumed by the CLR (under 250MB) is much smaller than the total process memory (inching closer to 4GB)
We have not been able to identify the cause of this leak and it's affecting production services. Any ideas what we should look at? Are there any environment variables to enable so we can see more details in those dumps? It almost looks like there's an unmanaged memory leak, but I have no data yet to back this up.
Reproduction Steps
The repro consists of typically accepting inbound calls and making outbound http calls. I know it's a but vague, but I don't have something to pinpoint it now.
Expected behavior
The total memory is expected to go up and down, but it should not increase steadily over time.
Actual behavior
Total memory constantly increasing, while .net managed heap stays small.
Regression?
Unclear.
Known Workarounds
No response
Configuration
The service runs
- Standard asp.net application on .net 8.0, current sdk version 8.0.415
- Docker image mcr.microsoft.com/dotnet/aspnet:8.0-azurelinux3.0
Other information
No response
There is a suggestion to use non-Server GC k8s in this article https://blog.markvincze.com/troubleshooting-high-memory-usage-with-asp-net-core-on-kubernetes/. You could also take memory dump of running app using:
$ kubectl exec -it <pod-name> -- dotnet-dump collect --process-id <pid> --output /tmp/dump.dmp
or attach profiler via VS or Rider etc. to see large object retention (and dispose them as appropriate).
@am11 - thanks for following up. The puzzling part is that the dumps taken with dotnet-dump or dotnet-gcdump show a CLR memory footprint much smaller than the total process memory (200 of MB vs 4GB). There are a handful of objects on the LOH, not much to worry about. We are investigating what other tools can be used to get more diagnostic information on where that memory is used. Hopefully this group has some hints.
it could be related to some native memory leaks in the networking layer like this one: https://github.com/dotnet/runtime/issues/108557
Can anyone advise what approaches are generally best used to investigate this kind of issues? There's a plethora of memory investigation tools available for Linux; it's not clear to me which ones are most likely to produce results.
I found similar issues reported in this older thread https://github.com/dotnet/runtime/issues/89776 that talks about /memfd:doublemapper (deleted) memory sections. While I definitely see a lot of those (1600+ after a day or so), the vast majority of memory seems to be associated to segments reported as [ anon ] by pmap, approximately 3.5GB out of a total of 3.8GB.
Things we have tried over the last few days, with help from @janvorli from the .net runtime team:
- The memory dumps we investigated did not show any obvious sign of a memory leak. The managed heap is running fine at merely a couple of hundred MB, while the total memory grows continuously, quickly hitting 2GB. If pods are left to run longer, eventually they hit 4GB, the limit configured in AKS for the pod, and are restarted.
- Initially the usage of StackExchange.Redis raised some red flags, but after fully disabling the Redis cache the behavior did not change, so that was ruled out
- Experimented with different values for MALLOC_MMAP_THRESHOLD_ and MALLOC_ARENA_MAX - while some improvement is noticed, the large unmanaged memory leak is still there
- Added unmanaged memory counters retrieved via the mallinfo2() API in Pinvoke - these have shown that there's a large amount of managed space that is technically free, but likely very fragmented, and can't be released
- Reverted back from the mcr.microsoft.com/dotnet/aspnet:8.0-azurelinux3.0 image to the prior mcr.microsoft.com/dotnet/aspnet:8.0-cbl-mariner2.0 image. The slow memory growth is present in the old image, however, much less prominent. The azurelinux3.0 image seems much more memory hungry.
- I've seen the suggestion to disable client certificate revocation check via CRL. In the
ConfigureKestrel()settingsHttpsConnectionAdapterOptions.CheckCertificateRevocationis left to its default false value, so I assume that's already the case, unless CRL checks are turned on by some other option. The same goes for the outbound calls, which useHttpClient. The CRL check is not enabled explicitly on theSocketsHttpHandlerthat is managed by theIHttpClientFactory. - heaptrack was mentioned too; I was able to build the tool, as it cannot be installed with the tdnf package manager on azurelinux, but I have not yet been able to run it. Would it provide some insights?
Here's a profile of the unmanaged memory counters inspired from this post on the azurelinux3.0 image (with relatively low traffic in a test environment). The total unmanaged memory quickly shoots towards 2GB and beyond
And here is a similar run with the (now-obsolete) mariner2.0 image. The memory increases steadily as well, but the total unmanaged heap is smaller.
When I set MALLOC_ARENA_MAX to 2, the allocation profile changed dramatically. The total space stayed flat for a while under 1GB (exactly 941,244,416), then jumped to about 1.13GB (exactly 1,138,155,520) where it stayed for the past 3 hours. The allocated and free space fluctuate, but barely. I did not see any errors in the application, the service seems to operate as expected.
How should we understand this memory profile? What is the difference in behavior when MALLOC_ARENA_MAX is set? If this stabilizes the service, does it make sense to run with this setting?
@rzikm / @janvorli / @jkotas - any idea where we should look next or how we should approach this in order to stabilize the services?
From https://github.com/dotnet/runtime/issues/122027#issuecomment-3598799519
Non-mmapped space allocated (bytes): 1,376,210,944 (arena)
[...]
Total free space (bytes): 1,337,742,528 (fordblks)
Top-most, releasable space (bytes): 113,584 (keepcost)
Pretty much all allocated memory is unutilized and just hanging in the malloc internally, and since the keepcost is low, we can't easily trigger its release. One thing you may explore is replacing the malloc implementation using e.g. jemalloc or tcmalloc. I have seen it help in some cases.
I much like the writeup in https://www.epsio.io/blog/out-of-memory-shenanigans, starting about in the middle under "Malloc And Its Shenanigans" which I believe describes the same situation we are encountering here.
Previously, I have seen this much memory fragmentation only when large CRLs were being checked by the application, but since you claim you don't have revocation checking enabled, I wonder what is triggering the issue in this particular case and whether we can do something to prevent it.
@rzikm - thanks for getting back to me. Since this is an Asp.Net application we don't have control over the code that allocates the unmanaged memory, so replacing malloc isn't really an option, unless this can be tested with environment variables. I tried various values for MALLOC_MMAP_THRESHOLD_ but it didn't seem to change this behavior much; the mmapped memory remains a small portion of the heap.
As for disabling or controlling the CRL checks, can you suggest what else we should do? For inbound connections Kestrel controls it:
.ConfigureKestrel((context, options) =>
{
var adapterOptions = new HttpsConnectionAdapterOptions();
adapterOptions.ClientCertificateMode = endpoint.ClientCertificateMode;
adapterOptions.CheckCertificateRevocation = false; // This is the default value
....
listenOptions.UseHttps(adapterOptions);
}
On the outbound path, a SocketsHttpHandler is created by the IHttpClientFactory
var handler = new SocketsHttpHandler()
handler.SslOptions.ClientCertificates ??= new X509CertificateCollection();
handler.SslOptions.ClientCertificates.Add(certificate);
handler.SslOptions.CertificateRevocationCheckMode = X509RevocationMode.NoCheck; // This is the default value
Is there anything else we should look at to confirm whether CRL checks are indeed enabled or disabled?
Can you also clarify - if the memory counters show that almost all the memory allocated is unused, how does the application still perform normally after we set MALLOC_ARENA_MAX to 2 and the total memory is mostly flat? It looks like it the app does not need much unmanaged memory (we see no errors), but if left alone it will keep allocating.
This is the unmanaged memory profile of one pod after a day of running. You can see the total memory has only increased three times and it's mostly flat. During this time, the allocated space (blue line at the bottom) shows a very slight increasing slope (from 23MB at the beginning to 49MB). Could some of those objects cause the fragmentation?
I am a Microsoft FTE, I can provide additional details like core dumps, etc, if anyone can help.
I am running the application with jemalloc instead, and initial data seems promising. The total memory reported by kubectl top pod is not growing like it was, it stays in the low 400MB for now. Nothing else was changed. However, the unmanaged heap counters retrieved via mallinfo2() are now all zero. Based on the jemalloc docs, I would have to use mallctl() instead. @rzikm - I added logic do dump those values periodically similar to the ones for mallinfo2, I'll get a profile when it has run enough.
This is what I added in my dockerfile before starting the application; it seems to have worked:
RUN tdnf install -y jemalloc jemalloc-devel
ENV LD_PRELOAD=/usr/lib/libjemalloc.so
There has been a noticeable change after I switched to the jemalloc library. I added a periodic capture of memory stats as described in the jemalloc wiki. Everything else is unchanged, still using the azurelinux3.0 image, https traffic levels are moderate. Before the change the allocated (but free) space would quickly explode towards 1GB, but we don't see this yet. At this time, about 1 hour after deployment with jemalloc, kubectl top pod shows an average of 470MB per pod, which must include both managed and unmanaged memory.
The unmanaged memory jemalloc stats captured so far:
I don't fully understand which of those stats values most closely maps to RSS, but clearly not even the highest counter stats.mapped is near the old values. I'll follow up with an update in the morning.
All this saga raises several important questions:
- If jemalloc solves this, why was the behavior so aggressive and wasteful with the default allocator?
- We still don't know what causes the original fragmentation, but if it's OpenSSL I couldn't find a good way to disable
OpenSslCrlCache.AddCachedCrl()which shows prominently on AzureProfiler traces. Copilot indicates CRL chain caching can't be prevented from Asp.Net Kestrel settings since it happens in the interop layer; it can only be disabled globally by making changes to openssl.cnf. - We are .Net application developers, we shouldn't have to do any of this, right? We should not have to configure a different unmanaged memory allocator just to prevent our services from tipping over. Who in Microsoft should we follow-up with to escalate for a permanent fix?
If jemalloc solves this, why was the behavior so aggressive and wasteful with the default allocator?
In short, it's because of the way glibc allocator is implemented.
I don't have hard data on this, but I am not aware of it being an industry-wide known problem, so something specific to .NET is triggering this. My best guess is that async/await model may cause tasks working with one SslStream instance to move between threadpool threads (as a result of asynchronously waiting for network response), leading to related allocations being distributed across multiple malloc arenas is what causes there always being some live allocation which glibc malloc from consolidating the memory and shriking down.
CRL is usually the trigger becuase with large CRLs, OpenSSL ends up allocating lots of small objects when parsing CRLs (especially with large CRLs which are associated with some CAs).
We still don't know what causes the original fragmentation, but if it's OpenSSL I couldn't find a good way to disable OpenSslCrlCache.AddCachedCrl()
By default, CRL checking is disabled, some part of your application code must be enabling it.
Copilot indicates CRL chain caching can't be prevented from Asp.Net Kestrel settings since it happens in the interop layer; it can only be disabled globally by making changes to openssl.cnf.
Disabling caching will not fix the problem, the "Cached" part of AddCachedCrl refers to cache on the disk so that CRL (which may in extreme cases be up to 10MBs) does not need to be downloaded every time it is needed. Currently, we don't cache parsed CRLs in memory, although it is one of the suggested experiments to improve the situation (see https://github.com/dotnet/runtime/issues/108557).
We are .Net application developers, we shouldn't have to do any of this, right?
In ideal world, I would agree with you, but since the problem is not due to a bug in source code we control and any change in .NET runtime we do affects lots of applications. Individual application developers are sometimes in better position to apply workarounds like malloc tunables or changing malloc implementation, since they can evaluate the specific workaround in the context of their application.
That being said, we have been seeing this issue more frequently lately, since there is a shift from OCSP back to CRLs for revocation checking, for example
- https://github.com/dotnet/runtime/issues/92490
- https://github.com/dotnet/runtime/issues/57213
- https://github.com/dotnet/runtime/issues/52577
- https://github.com/dotnet/runtime/issues/108557
- https://github.com/dotnet/runtime/issues/101552
I will start the conversation internally to see if there is something we can do to address this issue in future releases
@fstugren I'd like to confirm one thing, do I read it correctly that with jemalloc you managed to cut the app memory consumption from 4GB to 400MB?
@rzikm - here are the stats of running with jemalloc. These stats are from one of the pods that shows the largest memory consumption.
- Run time: approximately 10 hours
- Pod memory consumption reported by
kubectl top pod: 1GB (increased from 800MB when I last looked yesterday) - RSS memory of the dotnet application as reported by
ps aux: 601MB (where is the difference between this value and the one reported by kubectl??? Not much else runs on the pod) - RSS reported by
pmap- same as that by ps, I assume it comes from the same data in /proc/[PID]/smaps - Total bytes consumed by the CLR, reported after taking a core dump and running
eeheap: 192MB - Is there anything else that would be interesting?
This is the memory profile according to jemalloc stat counters obtained with mallctl() - it looks incredibly stable!... assuming I collected the correct stats. If you are familiar with jemalloc please chime in.
stats.resident (which I think means RSS) hovers about 100MB, while total stats.mapped is about 150MB, while stats.allocated rarely goes over 35MB. Adding to that the roughly 200MB of the CRL we get at most 400MB. How can we account for the difference to 600MB? Is it memory that hasn't been freed? Am I missing a counter?
I am not sure if CRL checks for client certificates are happening despite being disabled; from what I can gather .NET OpenSSL interop layer caches CRLs when a certificate chain includes CRL distribution points, regardless of the application's RevocationMode setting, which only controls managed chain validation, not the native OpenSSL handshake.
We can see the method OpenSslCrlCache.AddCrlForCertificate() called often on the flame Graph in Azure Profiler; could this be the cause of this small leak that leads to fragmentation?
Since jemalloc is an archived project (previously supported by Facebook) that hasn't seen updates in years I don't think it's appropriate for production services. I have run the same experiment with tcmalloc, another memory allocator library recommended by @rzikm. This library is backed by Google, although not officially endorsed and released by them. I replaced the library at runtime by adding this in my Dockerfile:
RUN tdnf install -y gperftools-libs gperftools-devel
ENV LD_PRELOAD=/usr/lib/libtcmalloc.so
The application memory grew and reached a plateau where it stabilized for each pod (about 11 hours of running with moderate traffic). I do not have granular memory counters like for the other allocators, these are RSS values retrieved with Process.GetCurrentProcess().WorkingSet64. These values match what is reported by kubectl top pod. Tcmalloc is also looking better than the default allocator.
I don't know if it is related, but we are seeing consistently high native memory usage across our .NET 8 and .NET 9 workloads (both glibc and musl), and this is preventing us from moving from Windows to Linux containers for cost reason. https://github.com/dotnet/runtime/discussions/122180
Is there anything we can do to provide more details? Would using a Native AOT build make any difference?
You can check if yours is a similar issue to this one by checking
- whether you have certificate revocation checking enabled for client certificates, or outbound service requests
- whether mallocs fordblocks is where the excess memory is, you can use e.g. This gist to expose those metrics as counters and ingest them as other .NET telemetry
NativeAOT may lower memory footprint, but it will not help with this issue. The discussion here and in linked issues mentions several workarounds you may consider to see if it helps in your scenarios.
Meanwhile, we are discussing internally if there is something we can do in runtime/libraries to help with this specific issue.
Disabling the component that validates inbound client certificates did not produce different results, the unmanaged memory still shows a large unused space, and the total heap is growing, at first faster, then slower. This is back on the original memory allocator, no arena customizations.
In an attempt to isolate the cause further I will deploy a version that does not accept calls with client certificates but still makes outbound calls with client certificates.
I have managed to slim down the repro to X509Chain.Build with an on-the-spot generated certificate with a large CRL
[00:00:20.8533808] i: 65, hops: 51, GC MEM: 3,011,760, RES: 2,915,958,784, arena: 2,319,314,944, uordblks: 12,902,896, fordblks: 2,306,412,048
we continue to investigate the problem and will post updates here.