Skip to content

Dispose endpoint rate limiter on application shutdown - #69914

Open
SENESO wants to merge 2 commits into
dotnet:mainfrom
SENESO:fix/ratelimiting-dispose-66434
Open

SENESO wants to merge 2 commits into
dotnet:mainfrom
SENESO:fix/ratelimiting-dispose-66434

Conversation

@SENESO

@SENESO SENESO commented Oct 18, 2026

Copy link
Copy Markdown

Fixes #66434 (also closes #69061 as a duplicate).

RateLimitingMiddleware creates its own PartitionedRateLimiter<HttpContext> (_endpointLimiter) in CreateEndpointLimiter() but never disposes it. The limiter's internal timer infrastructure keeps the host rooted, so every WebApplicationFactory-based test class leaks roughly one host (~100MB). Verified with a WeakReference repro: the host is not collectable with UseRateLimiter before this change, and collectable after.

The fix registers the middleware-owned limiter for disposal on IHostApplicationLifetime.ApplicationStopped. Design notes:

  • Only _endpointLimiter is disposed — it is created inside the middleware, so the middleware is its sole owner. _globalLimiter comes from RateLimiterOptions.GlobalLimiter (user-provided) and is deliberately left alone: the user may share it across hosts or dispose it themselves.
  • GetService (not GetRequiredService) keeps this null-safe for non-host scenarios; the callback is a static lambda so the registration can't root the middleware instance.

Tests:

  • EndpointLimiterIsDisposedWhenApplicationStops — fails without the fix, passes with it.
  • GlobalLimiterIsNotDisposedWhenApplicationStops — documents the ownership decision.

Note: I couldn't execute the repo's own test suite in my environment (it needs the source-built targeting pack from a near-full repo build), so CI is the real gate here. The change is minimal, additive, and null-safe.

@SENESO
SENESO requested a review from BrennanConroy as a code owner October 18, 2026 07:01
@github-actions github-actions Bot added the area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares label Oct 18, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 18, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @SENESO. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@SENESO

SENESO commented Oct 18, 2026

Copy link
Copy Markdown
Author

@dotnet-policy-service agree

@MohamedAliTera

Copy link
Copy Markdown

Any update on this? 👀

@SENESO

SENESO commented Oct 25, 2026

Copy link
Copy Markdown
Author

Hi @MohamedAliTera, thanks for checking in. The fix is complete and all CI checks are green — it's currently waiting on a maintainer review. Hopefully it gets picked up soon.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Nov 2, 2026
@SENESO SENESO closed this Nov 2, 2026
@SENESO SENESO reopened this Nov 2, 2026
@hobleyd

hobleyd commented Nov 16, 2026

Copy link
Copy Markdown

This still reproduces on .NET 11.0.0 (Microsoft.AspNetCore.App 11.0.0). A minimal standalone repro, with no test host and no global limiter, only AddRateLimiter + UseRateLimiter and one endpoint:

// repro.csproj: <Project Sdk="Microsoft.NET.Sdk.Web">, net11.0, ImplicitUsings enabled
using System.Runtime.CompilerServices;

foreach (var useRateLimiter in new[] { false, true })
{
    var refs = new List<WeakReference>();
    for (var i = 0; i < 20; i++)
    {
        refs.Add(await StartAndDisposeAsync(useRateLimiter));
    }

    for (var i = 0; i < 3; i++)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

    Console.WriteLine($"UseRateLimiter={useRateLimiter}: {refs.Count(r => r.IsAlive)}/20 disposed apps still alive");
}

[MethodImpl(MethodImplOptions.NoInlining)]
static async Task<WeakReference> StartAndDisposeAsync(bool useRateLimiter)
{
    var builder = WebApplication.CreateBuilder();
    builder.WebHost.UseUrls("http://127.0.0.1:0");
    builder.Services.AddRateLimiter(_ => { });
    var app = builder.Build();
    app.UseRouting();
    if (useRateLimiter)
    {
        app.UseRateLimiter();
    }

    app.MapGet("/", () => "ok");
    await app.StartAsync();
    var weak = new WeakReference(app.Services);
    await app.StopAsync();
    await app.DisposeAsync();
    return weak;
}

Output on macOS arm64, .NET 11.0.0:

UseRateLimiter=False: 1/20 disposed apps still alive
UseRateLimiter=True: 20/20 disposed apps still alive

For scale: in an endpoint test suite that starts a fresh in-memory host per test (~1,000 hosts), every host stayed reachable and the managed heap grew steadily to ~3.7 GB over the run. Bisecting the pipeline pointed at UseRateLimiter() alone. With RateLimiterOptions.GlobalLimiter unset it still leaks, which matches the endpoint limiter created in CreateEndpointLimiter() being the root, as this PR describes. It would be great to get this reviewed.

@SENESO

SENESO commented Nov 16, 2026

Copy link
Copy Markdown
Author

Thanks for the independent repro — especially the standalone .NET 11 case without a test host, and the 1,000-host heap measurement. That matches what I found: with GlobalLimiter unset it still leaks, which points at the endpoint limiter created in CreateEndpointLimiter().

@BrennanConroy — ready for review whenever you have a moment. Per the policy note above, CI validation needs a rerun (I do not have commit rights for /azp run), so I will close and reopen to retrigger it.

@SENESO SENESO closed this Nov 16, 2026
@SENESO SENESO reopened this Nov 16, 2026
@gdoron

gdoron commented Nov 16, 2026

Copy link
Copy Markdown

@BrennanConroy it's a very big issue for us, can you please push it forward?
If there is anything we can help with, please let me know:

We're hitting this too, at scale, on ASP.NET Core 10. Adding numbers in case they help get #69914 reviewed.

Our test projects start a test host per test class, and 22 of our services call UseRateLimiter(). None of those hosts is ever collected: at the end of a test run, after every host has been stopped and disposed, a heap dump shows each of them still reachable through the same chain described here:

TimerQueue > TimerQueueTimer > TimerAwaitable
  > DefaultPartitionedRateLimiter<HttpContext, DefaultKeyType> (the endpoint limiter)
  > Func<HttpContext, RateLimitPartition<DefaultKeyType>>
  > RateLimitingMiddleware > RequestDelegate > ... > IServiceProvider

We confirmed the chain in a dump of one of them, which has one live endpoint-limiter timer for each live host. That project holds 4.5 GB after a full GC at the end of its CI run; most of our other test projects end at about 80 MB.

main still creates _endpointLimiter in the constructor and never disposes it, so this isn't fixed yet. Until #69914 ships, we're working around it the same way #69914 does: we construct the middleware ourselves and dispose its endpoint limiter on IHostApplicationLifetime.ApplicationStopped. That needs reflection on the private field, which is why an upstream fix would be much better.

@gdoron

gdoron commented Nov 16, 2026

Copy link
Copy Markdown

A workaround until this (or a different) PR land:

public static class RateLimiterApplicationBuilderExtensions {
    /// <summary>
    ///     <c>UseRateLimiter()</c>. In unit tests it also disposes the middleware's endpoint limiter when the app
    ///     stops. Use it instead of <c>UseRateLimiter()</c>.
    /// </summary>
    /// <remarks>
    ///     The stock middleware never disposes the endpoint limiter it creates, and that limiter's timer keeps the
    ///     whole stopped app reachable (https://github.com/dotnet/aspnetcore/issues/66434). Production runs one app
    ///     per process, so only tests, which start one per test class, pay for it, and only tests get the
    ///     reflection-based workaround. Remove this once the fix (https://github.com/dotnet/aspnetcore/pull/69914)
    ///     ships. If the middleware's internals change, this falls back to <c>UseRateLimiter()</c> and
    ///     DisposedAppIsCollected fails.
    /// </remarks>
    public static IApplicationBuilder UseRateLimiterDisposedOnStop(this IApplicationBuilder app) {
        if (!UnitTestContext.IsInTest || !Middleware.CanDisposeEndpointLimiter)
            return app.UseRateLimiter();

        return app.Use(next => {
            var middleware = ActivatorUtilities.CreateInstance(app.ApplicationServices, Middleware.Type!, next);
            var endpointLimiter = (IDisposable)Middleware.EndpointLimiterField!.GetValue(middleware)!;
            app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>()
                .ApplicationStopped.Register(endpointLimiter.Dispose);
            return Middleware.InvokeMethod!.CreateDelegate<RequestDelegate>(middleware);
        });
    }

    // A separate class so production, which never gets past the IsInTest check, never runs these lookups.
    private static class Middleware {
        public static readonly Type? Type = typeof(RateLimiterOptions).Assembly
            .GetType("Microsoft.AspNetCore.RateLimiting.RateLimitingMiddleware");

        public static readonly FieldInfo? EndpointLimiterField =
            Type?.GetField("_endpointLimiter", BindingFlags.Instance | BindingFlags.NonPublic);

        public static readonly MethodInfo? InvokeMethod =
            Type?.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public, [typeof(HttpContext)]);

        public static bool CanDisposeEndpointLimiter => EndpointLimiterField != null && InvokeMethod != null;
    }
}

This branch has not been deployed

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

Labels

area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares community-contribution Indicates that the PR has been added by a community member pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

4 participants