Skip to content

System.Net.Http: observable http.client.active_requests / open_connections leak two instruments per handler (regression from #131275) #136418

Description

@Demosfen

Description

Since #131275 (merged 2026-07-30), http.client.active_requests and http.client.open_connections are ObservableUpDownCounter<long> instruments. They are created in the constructors of MetricsHandler and SocketsHttpHandlerMetrics, that is, once per handler instance, on the shared System.Net.Http meter:

  • src/libraries/System.Net.Http/src/System/Net/Http/Metrics/MetricsHandler.cs: meter.CreateObservableUpDownCounter<long>("http.client.active_requests", observeValues: _activeRequestsTracker.GetMeasurements, ...)
  • src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Metrics/SocketsHttpHandlerMetrics.cs: the same for http.client.open_connections

The comment in MetricsHandler says "Meter has a cache for the instruments it owns", but Meter only caches non-observable instruments (GetOrCreateInstrument is used for Counter, UpDownCounter, Histogram, Gauge). CreateObservableUpDownCounter always allocates a new instrument. Instruments are removed only when the Meter is disposed, and the System.Net.Http meter lives for the lifetime of the process (or of the IMeterFactory). Disposing the handler does not remove its instruments.

With IHttpClientFactory the primary handler is recreated every 2 minutes by default, so every handler that sent at least one request adds two instruments that are never released, together with their trackers and the listeners' per-instrument state (for example OpenTelemetry's metric state). Every collection also invokes all accumulated observeValues callbacks, so collection cost grows with uptime.

Before #131275 these were UpDownCounter<long> instruments, which Meter caches by name, so there was one instrument per meter. The code is the same on main and release/11.0.

Reproduction Steps

  1. Subscribe a MeterListener to the System.Net.Http meter and count InstrumentPublished callbacks for http.client.active_requests.
  2. In a loop, create a new SocketsHttpHandler + HttpClient, send one request, dispose both.
  3. Alternatively: run an ASP.NET Core app that uses IHttpClientFactory with default settings and an OpenTelemetry metrics exporter, make periodic outbound requests, and take memory dumps some hours apart.

Expected behavior

The number of http.client.active_requests / http.client.open_connections instruments stays bounded (one per meter, as with UpDownCounter before #131275), or a handler's instruments are released when the handler is disposed.

Actual behavior

Two new instruments per handler, kept until the process exits. In a production service on .NET 11 RC 2 a memory dump after several days of uptime showed about 33 700 ObservableUpDownCounter<long> instances rooted from Meter.s_allMeters → meter → List<Instrument> (about 51 MB), plus about 11 MB of OpenTelemetry per-instrument state for them.

Regression?

Yes. Not present in .NET 10, where these instruments are UpDownCounter<long>. Introduced by #131275.

Known Workarounds

Stop recreating handlers so the number of instruments is bounded by the number of named clients: services.ConfigureHttpClientDefaults(b => b.SetHandlerLifetime(Timeout.InfiniteTimeSpan).UseSocketsHttpHandler((h, _) => h.PooledConnectionLifetime = TimeSpan.FromMinutes(2))). This does not fix the growth for code that creates handlers directly.

Configuration

.NET 11.0 RC 2, Linux x64 containers, ASP.NET Core with IHttpClientFactory and OpenTelemetry metrics (OTLP exporter).

Other information

Possible fixes: create the observable instruments once per meter (for example a static or per-meter holder that aggregates trackers of all live handlers), or let the handler unregister its tracker on dispose and keep a single callback per meter.

Activity

  1. added
    untriaged
    on Oct 24, 2026
  2. dotnet-policy-service commented on Oct 24, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @karelz, @dotnet/ncl
    See info in area-owners.md if you want to be subscribed.

  3. added and removed
    untriaged
    on Oct 26, 2026
  4. added this to the 12.0.0 milestone on Oct 26, 2026
  5. asad24-dev commented on Oct 26, 2026

    @asad24-dev
    Contributor

    I've reproduced this on current main and have a fix that shares the observable instruments and their trackers per meter. The regression tests are passing, including concurrent handler initialization and aggregation across handlers.

    I'll open a PR shortly.

  6. nikolay-collab commented on Nov 2, 2026

    @nikolay-collab

    We've run into the same issue, please, we need this change shipped for the .net11 before it's released

  7. ManickaP commented on Nov 3, 2026

    @ManickaP
    Member

    @nikolay-collab can you share some real numbers how is this hurting you? In terms of compute or money. We need real world business impact to reason why it should be serviced.
    Also note that even if we accept the fix a have enough data to support a backport, we are already past deadline for 11 GA. It would happen in some follow up servicing at earliest.

  8. self-assigned this
    on Nov 3, 2026
  9. nikolay-collab commented on Nov 3, 2026

    @nikolay-collab

    @ManickaP

    Two common patterns trigger it, and neither is a misuse:

    • IHttpClientFactory with default settings. The primary handler is rotated every 2 minutes, so each named client used at least that often adds 30 handlers, and 60 instruments, per hour.
    • The AWS SDK for .NET (v4) on EC2 with instance-profile credentials. DefaultInstanceProfileAWSCredentials renews the credentials every 2 minutes with 4 requests to the instance metadata service, and AWSSDKUtils.CreateClient builds a new HttpClient(new HttpClientHandler()) for each one. That is 120 handlers per hour from code the application does not own, and it is where our production growth comes from.

    Each leaked handler costs about the same on both paths: 3 to 3.5 KB that stays reachable whether or not a listener enables the two instruments, plus 304 bytes and 0.7 to 1 µs on every RecordObservableInstruments() pass when one does.

    IHttpClientFactory reproduction: 100 named clients, default settings except SetHandlerLifetime(TimeSpan.FromSeconds(1)) to compress time, and a MeterListener enabling the System.Net.Http instruments.

    handlers created named-client days at the 2-minute default retained one collection pass allocated per pass
    1,400 1.9 6.0 MiB 0.8 ms 445 KB
    5,900 8.2 20.3 MiB 6.8 ms 1.8 MB
    14,900 20.7 51.8 MiB 17.6 ms 4.4 MB
    29,900 41.5 100.2 MiB 30.0 ms 8.9 MB
  10. ManickaP commented on Nov 3, 2026

    @ManickaP
    Member

    Are these numbers coming from your production?

  11. ManickaP commented on Nov 3, 2026

    @ManickaP
    Member

    Also note that I am now considering reverting #131275 instead of trying to fix this by re-implementing yet another Instrument related logic in sockets handler. So neither of the 2 competing PRs might be merged in the end.

    I will discuss the options with diagnostics team and with my team and I'll share when we come up with a decision.

  12. asad24-dev commented on Nov 3, 2026

    @asad24-dev
    Contributor

    Thanks for the update, @ManickaP . That makes sense. I've prepared a local revision of #136493 incorporating @unsafePtr's simpler approach from #136849, with updated regression tests. I'll hold off on pushing it until you've discussed the direction with the team.

  13. normj commented on Nov 6, 2026

    @normj

    @unsafePtr has sent us, the AWS .NET SDK team, a PR to work around the issue and hope to release it Monday as part of the SDK's daily release schedule.

  14. laurihelkkula commented on Nov 16, 2026

    @laurihelkkula

    Hi,

    We've noticed this affecting one scenario in production, and I can share some data points. We had a piece of code related to pushing log messages that runs 700k times in a day. This results in quite linear growth in memory usage of about 1,3 Gb per day.

    The code was creating HttpClient instances for each invocation. We fixed it to use a shared instance and the immediate issue was resolved.

    Here's my vibecoded benchmark

    using System.Diagnostics.Metrics;
    using System.Runtime.InteropServices;
    
    bool reuse = args.Contains("--reuse");
    
    static HttpClient CreateClient() => new(new SocketsHttpHandler {
        UseProxy = false,
        ConnectCallback = (_, _) =>
            ValueTask.FromException<Stream>(new IOException("Intentional failure"))
    });
    
    Console.WriteLine(RuntimeInformation.FrameworkDescription);
    using var shared = reuse ? CreateClient() : null;
    
    for (int i = 0; i < 10_000; i++) {
        using var owned = reuse ? null : CreateClient();
        try {
            using var response = await (shared ?? owned!).GetAsync(
                "http://metrics-probe.invalid/");
            throw new InvalidOperationException("Unexpected success");
        }
        catch (HttpRequestException ex) when (
            ex.InnerException is IOException io &&
            io.Message == "Intentional failure") {
        }
    }
    
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    
    var instruments = new Dictionary<string, int>();
    using var listener = new MeterListener {
        InstrumentPublished = (instrument, _) => {
            if (instrument.Meter.Name == "System.Net.Http") {
                instruments[instrument.Name] =
                    instruments.GetValueOrDefault(instrument.Name) + 1;
            }
        }
    };
    listener.Start();
    
    Console.WriteLine($"Managed bytes: {GC.GetTotalMemory(false)}");
    foreach (var entry in instruments.OrderBy(x => x.Key)) {
        Console.WriteLine($"{entry.Key}: {entry.Value}");
    }

    And measurements:

    Configuration, 10,000 requests Registered instruments after full GC Managed bytes after full GC
    .NET 10.0.14, per-request client 5 385,432
    .NET 11.0.0, per-request client 20,003 29,435,504
    .NET 11.0.0, reused client 5 337,688
  15. Tragetaschen commented on Nov 19, 2026

    @Tragetaschen
    Contributor

    I was bitten by that as well - a tiny service, checking reachability of services by doing an HTTP ping every 30 seconds. I recreate the SocketsHttpHandler each time, so DNS, SSL etc. are re-checked as well.

    image

    Maybe a bit pushy: I'm very confused that a memory leak in such a central component of .NET needs business cases to be fixed. In my mental model, this is simply unacceptable for the product. Period.

  16. Tragetaschen commented on Nov 19, 2026

    @Tragetaschen
    Contributor

    To put a bit more weight behind it, but it's also mentioned in the OP already: This fully affects the recommended IHttpClientFactory pattern as well.

    https://gist.github.com/Tragetaschen/30ff63b9463212ec53e195ad108744b4

    With the defaults, there are two leaked meters every two minutes.

  17. ManickaP commented on Nov 19, 2026

    @ManickaP
    Member

    We are looking into it and trying to figure out what is the best course of action here.

    I'm very reluctant to introduce any more logic into HTTP metrics that is there only workaround OTel shortcomings. And honestly should just simply be part of diagnostics.

    Also note that the memory leak is not substantial (100MB in 40 days if I'm reading #136418 (comment) correctly) and the impact of the original issue is likely more painful than this.

  18. Tragetaschen commented on Nov 20, 2026

    @Tragetaschen
    Contributor

    100MB in 40 days

    This highly depends on the use case. It's two leaked per SocketsHttpHandler. You get one of those per named client every two minutes. My example above showed that 40MiB can be reached "over night" in a different use cases with more churn on the handler.

    I've been running with the following workaround, very focused around just fully turning off the HTTP metrics. It's the first thing my Program.cs calls to control when the static class constructor of the internal MetricsHandler runs.

    /// <summary>
    /// Works around https://github.com/dotnet/runtime/issues/136418: on .NET 11, every SocketsHttpHandler registers two
    /// observable instruments that are never released. Remove once the fix ships in a servicing release.
    /// </summary>
    public static class HttpClientMetricsWorkaround {
      private const string MetricsSwitch = "System.Diagnostics.Metrics.Meter.IsSupported";
    
      /// <summary>
      /// Disables the System.Net.Http client metrics while keeping all other meters. Must run before the first
      /// HTTP request; afterwards it has no effect.
      /// </summary>
      public static void DisableHttpClientMetrics() {
        var settings = typeof(HttpClient).Assembly.GetType("System.Net.Http.GlobalHttpSettings+MetricsHandler");
        if (settings == null) {
          return;
        }
    
        // Each of these reads the switch once, in its static constructor. Initializing Meter and EventSource first
        // leaves GlobalHttpSettings.MetricsHandler as the only reader that can see it switched off.
        RuntimeHelpers.RunClassConstructor(typeof(Meter).TypeHandle);
        RuntimeHelpers.RunClassConstructor(typeof(EventSource).TypeHandle);
        AppContext.SetSwitch(MetricsSwitch, false);
        try {
          RuntimeHelpers.RunClassConstructor(settings.TypeHandle);
        } finally {
          AppContext.SetSwitch(MetricsSwitch, true);
        }
      }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions