Repository navigation
Description
Description
When PooledConnectionLifetime or PooledConnectionIdleTimeout is TimeSpan.Zero (with the default MaxConnectionsPerServer and no keep-alive pings configured), the avoidStoringConnections optimization activates (HttpConnectionPoolManager.cs#L74-L82): the manager does not create the cleaning timer, and because the timer is null it also never adds the pool to _pools (HttpConnectionPoolManager.cs#L341-L347). The comment at that spot assumes that without a cleaning timer no connections are ever stored in pools. That holds for HTTP/1.1, but not for HTTP/2: a brand-new HTTP/2 connection skips the expiration check (HttpConnectionPool.Http2.cs#L370) and is added to the pool's _availableHttp2Connections (HttpConnectionPool.Http2.cs#L430). The repro below sets both values to TimeSpan.Zero.
From that point the pool is unreachable. There is no cleaning timer by design, and HttpConnectionPoolManager.Dispose() only walks _pools (HttpConnectionPoolManager.cs#L451-L458), so HttpConnectionPool.Dispose() - which would tear down _availableHttp2Connections (HttpConnectionPool.cs#L913-L917) - is never called. Disposing the HttpClient and the handler therefore leaves the HTTP/2 connection fully alive: its read loop keeps it rooted, and with it the socket, the SslStream, and the native TLS state, because FinalTeardown() - the only place that disposes the connection's stream (Http2Connection.cs#L1851-L1859) - is never reached. Each create-send-dispose cycle leaks one connection: one TCP socket and tens of kilobytes of native memory (per readlink /proc/self/fd, the leaked descriptors are all sockets; the repro below counts two per iteration because the test server runs in the same process, so its accepted end of each leaked connection also stays open). The GC cannot reclaim any of it - the connections are rooted, not garbage, so forced collections and finalizers change nothing.
Internal traces (events from Private.InternalDiagnostics.System.Net.Http) confirm the divergence. With a 1-second lifetime, handler disposal logs Disposing the pool., then Shutdown and FinalTeardown. With TimeSpanZero, no pool event appears after Put HTTP2 connection in pool.
Reproduction Steps
Single file, Linux (the measurement uses /proc/self/fd to count descriptors), .NET 10 SDK:
dotnet run Http2DisposeLeak.cs
Or from any OS via a container (an optional argument sets the iteration count, default 1000):
docker run --rm -v "$PWD":/src -w /src mcr.microsoft.com/dotnet/sdk:10.0 dotnet run Http2DisposeLeak.cs
#:sdk Microsoft.NET.Sdk.Web
// .NET 10 / Linux: SocketsHttpHandler with PooledConnectionLifetime = TimeSpan.Zero
// never disposes HTTP/2 connections - each create-send-dispose cycle leaks the
// connection, its socket and its native TLS state. Any non-zero lifetime is clean.
// Run: dotnet run Http2DisposeLeak.cs [iterations]
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Https;
var iterations = args.Length > 0 ? int.Parse(args[0]) : 1000;
var port = await StartLocalHttp2Server();
Console.WriteLine($"runtime={Environment.Version} iterations={iterations}");
await MeasureLeaksAfterDispose("PooledConnectionLifetime = 1s ", TimeSpan.FromSeconds(1));
await MeasureLeaksAfterDispose("PooledConnectionLifetime = Zero", TimeSpan.Zero);
return;
async Task MeasureLeaksAfterDispose(string label, TimeSpan pooledConnectionLifetime)
{
var openFdsBefore = CountOpenFds();
for (var i = 0; i < iterations; i++)
{
using var handler = new SocketsHttpHandler
{
PooledConnectionLifetime = pooledConnectionLifetime,
PooledConnectionIdleTimeout = pooledConnectionLifetime,
SslOptions = { RemoteCertificateValidationCallback = static (_, _, _, _) => true },
};
using var client = new HttpClient(handler, disposeHandler: false);
using var request = new HttpRequestMessage(HttpMethod.Get, $"https://localhost:{port}/")
{
Version = HttpVersion.Version20,
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
};
using var response = await client.SendAsync(request);
await response.Content.ReadAsStringAsync();
}
await Task.Delay(3000); // everything is disposed; grace for pool timers and cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// Clean arms show a small constant delta regardless of count; a leak grows
// linearly (at least one descriptor per iteration). iterations/2 separates the two.
var fdDelta = CountOpenFds() - openFdsBefore;
var rssMb = Environment.WorkingSet / (1024.0 * 1024.0);
Console.WriteLine($"{label}: fd delta = {fdDelta}, RSS = {rssMb:F0} MB -> {(fdDelta > iterations / 2 ? "LEAKED" : "clean")}");
}
static int CountOpenFds() => Directory.GetFiles("/proc/self/fd").Length;
async Task<int> StartLocalHttp2Server()
{
using var rsa = RSA.Create(2048);
var certRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
var cert = certRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, o =>
{
o.Protocols = HttpProtocols.Http2;
o.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = cert });
}));
var app = builder.Build();
app.MapGet("/", () => "{}");
await app.StartAsync();
return new Uri(app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.First()).Port;
}Expected behavior
Disposing the client and the handler closes their connections - the same way it does for HTTP/1.1, or for any non-zero lifetime.
Actual behavior
runtime=10.0.10 iterations=1000
PooledConnectionLifetime = 1s : fd delta = 24, RSS = 103 MB -> clean
PooledConnectionLifetime = Zero: fd delta = 2000, RSS = 216 MB -> LEAKED
Regression?
Unclear. The result is identical on 10.0.7, 10.0.8 and 10.0.10, and the relevant code is unchanged on main (HttpConnectionPoolManager.cs#L374-L380).
Known Workarounds
Set PooledConnectionLifetime and PooledConnectionIdleTimeout to any non-zero value: the pool is then registered, and handler disposal closes the connections normally.
Configuration
.NET 10.0.10, Linux (x64 and arm64), mcr.microsoft.com/dotnet/sdk:10.0 container, HTTP/2 over TLS. The measurement is Linux-only (/proc); the affected code is platform-neutral.
Other information
Our production service creates one handler per HTTPS probe (a monitoring worker that wants connection isolation per check). The leak was roughly 200 MB per hour, ending in OOM kills, while the managed heap stayed small - heap dumps showed no cause, which is what made this hard to find.
Activity
MihuBot commentedon Oct 17, 2026
cc: @dotnet/ncl
ManickaP commentedon Oct 28, 2026
In normal circumstances, users keep the connection pool alive, e.g. via keeping only one client alive. In case the client is getting disposed, there's no need to adjust pooled lifetime from the default value (=infinity).
The premise for hitting this problem is highly improbable. On top of that, the pool has been like this since ever and this is the first time I'm seeing this. And lastly, the report is evidently AI-generated and based on code inspection.
Given that the workaround is simply "do not touch the defaults if you're gonna throw the client away", I'm triaging this as Future.
cyberenigma-lgtm commentedon Nov 25, 2026
I have audited the connection lifecycle in
SocketsHttpHandlerwhenPooledConnectionLifetime/PooledConnectionIdleTimeoutis configured asTimeSpan.Zero, confirmed the architectural invariant breakdown with HTTP/2 pooling, and prepared a surgical fix along with an automated regression test.Root Cause Analysis
When
_avoidStoringConnectionsis set totrue,_cleaningTimeris initialized tonull.In
HttpConnectionPoolManager.GetOrCreatePool(), pools are only inserted into_poolsif_cleaningTimer != null, operating under the assumption that "If the cleaning timer is not running, we won't be storing any connections in pools anyway".Unlike HTTP/1.1 connections, new HTTP/2 connections bypass the expiration check and are unconditionally enqueued into
_availableHttp2Connections.When
SocketsHttpHandler.Dispose()runs, it callsHttpConnectionPoolManager.Dispose(), which iterates strictly over_pools.Values. Because the pool was omitted from_pools, itsDispose()method is never invoked. The HTTP/2 multiplexed background read loop keeps the connection rooted, permanently leaking:SslStreamand native OpenSSL / SChannel TLS context memory.Proposed Fix
HttpConnectionPool.Http2.cs: Verify_poolManager.AvoidStoringConnectionsinAddHttp2Connectionso connections are not retained in_availableHttp2Connectionswhen connection pooling is disabled.HttpConnectionPoolManager.cs: Ensure all createdHttpConnectionPoolinstances are registered in_pools(or a disposal list) to guarantee clean teardown onDispose()even when no periodic cleaning timer is active.Verification & Testing
We formally modeled and verified this network channel hierarchy using the UPL+ (Universal Polyglot Layer) toolchain:
Case study, documentation, and regression tests: https://github.com/cyberenigma-lgtm/UNIVERSAL-POLYGLOT-LAYER-UPL/tree/main/Proyectos_en_Revision/03_dotnet_runtime_135997_http2_socket_leak
Happy to open a Pull Request with this fix and xUnit regression test.