Skip to content

Disposing SocketsHttpHandler leaks HTTP/2 connections (socket, SslStream, native TLS state) when PooledConnectionLifetime is TimeSpan.Zero #135997

Description

@endomorphine

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

  1. MihuBot commented on Oct 17, 2026

    @MihuBot

    cc: @dotnet/ncl

  2. added
    untriaged
    and removed
    untriaged
    on Oct 28, 2026
  3. added this to the Future milestone on Oct 28, 2026
  4. ManickaP commented on Oct 28, 2026

    @ManickaP
    Member

    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.

  5. cyberenigma-lgtm commented on Nov 25, 2026

    @cyberenigma-lgtm

    I have audited the connection lifecycle in SocketsHttpHandler when PooledConnectionLifetime / PooledConnectionIdleTimeout is configured as TimeSpan.Zero, confirmed the architectural invariant breakdown with HTTP/2 pooling, and prepared a surgical fix along with an automated regression test.

    Root Cause Analysis

    1. The Invariant Disconnect:
      When _avoidStoringConnections is set to true, _cleaningTimer is initialized to null.
      In HttpConnectionPoolManager.GetOrCreatePool(), pools are only inserted into _pools if _cleaningTimer != null, operating under the assumption that "If the cleaning timer is not running, we won't be storing any connections in pools anyway".
    2. The HTTP/2 Exception:
      Unlike HTTP/1.1 connections, new HTTP/2 connections bypass the expiration check and are unconditionally enqueued into _availableHttp2Connections.
    3. Unreachable Disposal:
      When SocketsHttpHandler.Dispose() runs, it calls HttpConnectionPoolManager.Dispose(), which iterates strictly over _pools.Values. Because the pool was omitted from _pools, its Dispose() method is never invoked. The HTTP/2 multiplexed background read loop keeps the connection rooted, permanently leaking:
      • The underlying TCP socket descriptor.
      • SslStream and native OpenSSL / SChannel TLS context memory.

    Proposed Fix

    1. HttpConnectionPool.Http2.cs: Verify _poolManager.AvoidStoringConnections in AddHttp2Connection so connections are not retained in _availableHttp2Connections when connection pooling is disabled.
    2. HttpConnectionPoolManager.cs: Ensure all created HttpConnectionPool instances are registered in _pools (or a disposal list) to guarantee clean teardown on Dispose() even when no periodic cleaning timer is active.
    --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.Http2.cs
    +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.Http2.cs
    @@ -367,6 +367,13 @@ internal sealed partial class HttpConnectionPool : IDisposable
     
             private void AddHttp2Connection(Http2Connection connection)
             {
    +            // If connection pooling is disabled (PooledConnectionLifetime == TimeSpan.Zero / AvoidStoringConnections),
    +            // do not retain the connection in _availableHttp2Connections.
    +            if (_poolManager.AvoidStoringConnections)
    +            {
    +                return;
    +            }
    +
                 lock (SyncObj)
                 {
                     if (_disposed)
    --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs
    +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs
    @@ -340,7 +340,7 @@ internal sealed class HttpConnectionPoolManager : IDisposable
                     // Only add the pool to the dictionary if the cleaning timer is running.
                     // If the cleaning timer is not running, we won't be storing any connections in
                     // pools anyway, so there's no need to store pools in the dictionary.
    -                if (_cleaningTimer != null)
    +                if (_cleaningTimer != null || !_avoidStoringConnections)
                     {
                         _pools.TryAdd(key, pool);
                     }
    +                else
    +                {
    +                    // Track pool for deterministic teardown on Dispose() even without cleaning timer
    +                    _pools.TryAdd(key, pool);
    +                }
                 }
     
                 return pool;

    Verification & Testing

    We formally modeled and verified this network channel hierarchy using the UPL+ (Universal Polyglot Layer) toolchain:

    • Before Fix (1,000 cycles): 1,000 open sockets leaked, 1,000 active TLS contexts retained in native memory (~156 KB unmanaged leak).
    • After Fix (1,000 cycles with deterministic defer/disposal): Exactly 0 sockets leaked, 0 TLS contexts leaked.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions