Repository navigation
Description
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
RateLimitingMiddleware creates its endpoint limiter in the constructor
(_endpointLimiter = CreateEndpointLimiter(), a DefaultPartitionedRateLimiter
from PartitionedRateLimiter.Create) and nothing ever disposes it: the
middleware implements no IDisposable/IAsyncDisposable and registers no
ApplicationStopping/ApplicationStopped callback. RateLimiterOptions.GlobalLimiter
is likewise never disposed, though that one is arguably user-owned.
DefaultPartitionedRateLimiter runs a RunTimer loop (TimerAwaitable,
100 ms period) that only ends on Dispose(). The timer is rooted by the
process-wide TimerQueue; the loop's async state machine holds the limiter;
the limiter's partitioner delegate captures the middleware; the middleware's
_next reaches EndpointMiddleware → RouteOptions.EndpointDataSources →
RouteGroupBuilder → WebApplication → Host → the root ServiceProvider
and every singleton in it.
Result: after StopAsync() + DisposeAsync() a host that ever built a
request pipeline containing UseRateLimiter() is never garbage-collected.
In production this is one host for the process lifetime and invisible. In a
test suite using WebApplicationFactory<T> it is one leaked host per test
class, forever. In our suite (~400 hosts per run, ~100 MB each because each
host parses a set of XML data dictionaries) the test process grew to 22 GB
locally and exhausted a 16 GB CI runner, which surfaced as SQL Server error
596 in a sidecar container rather than as anything pointing at the limiter.
gcroot of the disposed Host in a one-host dump, all three roots identical:
System.Threading.TimerQueue (static)
-> System.Threading.TimerQueueTimer
-> System.Threading.RateLimiting.TimerAwaitable
-> AsyncStateMachineBox<DefaultPartitionedRateLimiter<HttpContext,DefaultKeyType>.RunTimer>
-> DefaultPartitionedRateLimiter<HttpContext,DefaultKeyType>
-> Func<HttpContext,RateLimitPartition<DefaultKeyType>>
-> Microsoft.AspNetCore.RateLimiting.RateLimitingMiddleware
-> Microsoft.AspNetCore.Http.RequestDelegate
-> Microsoft.AspNetCore.Routing.EndpointMiddleware
-> Microsoft.AspNetCore.Routing.RouteOptions
-> ObservableCollection<EndpointDataSource>
-> RouteGroupBuilder+GroupEndpointDataSource
-> Microsoft.AspNetCore.Routing.RouteGroupBuilder
-> Microsoft.AspNetCore.Builder.WebApplication
-> Microsoft.Extensions.Hosting.Internal.Host
Disposing _endpointLimiter via reflection on ApplicationStopped makes the
same host collectable within a second, so the limiter is the only thing
holding it.
Expected Behavior
A WebApplication that used UseRateLimiter() becomes collectable after
StopAsync() and DisposeAsync(), like one that did not. Concretely: the
middleware disposes the limiters it created when the application stops (for
example by taking IHostApplicationLifetime and registering on
ApplicationStopped, or by the hosting layer disposing middleware that
implement IDisposable).
Steps To Reproduce
Console app, net10.0, Microsoft.NET.Sdk.Web, one package reference
(Microsoft.AspNetCore.TestHost). Two files, public gist:
https://gist.github.com/chris-fixportal/a36174da57a31565c647879f74f23d5d.
The core:
static async Task<WeakReference> BuildServeStopAsync(bool useRateLimiter)
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
builder.Logging.ClearProviders();
builder.Services.AddRateLimiter(_ => { });
var app = builder.Build();
if (useRateLimiter) app.UseRateLimiter();
app.MapGet("/", () => "ok");
await app.StartAsync();
using (var client = app.GetTestClient())
(await client.GetAsync("/")).EnsureSuccessStatusCode();
var weak = new WeakReference(app.Services);
await app.StopAsync();
await app.DisposeAsync();
return weak;
}
// then: GC.Collect(); GC.WaitForPendingFinalizers(); up to 20 times, 100 ms apartOutput on Windows 11, .NET SDK 10 / shared framework 10.0.12, Release:
without UseRateLimiter: host collectable: True
with UseRateLimiter: host collectable: False
Exceptions (if any)
None. The failure mode is silent growth; in CI it appeared as an unrelated
process being starved of memory.
.NET Version
10.0.12 (Microsoft.AspNetCore.App 10.0.12). main at the time of writing has the same constructor-created limiter and no disposal path.
Anything else?
-
ASP.NET Core version: 10.0.12 (
Microsoft.AspNetCore.App) -
IDE: none; CLI (
dotnet run -c Release) -
Repro gist: https://gist.github.com/chris-fixportal/a36174da57a31565c647879f74f23d5d
-
dotnet --info(trimmed to the relevant lines):.NET SDK: Version: 10.0.401 Commit: e34a38d2ae Workload version: 10.0.400-manifests.b0700452 MSBuild version: 18.9.11+e34a38d2a Runtime Environment: OS Name: Windows OS Version: 10.0.26200 OS Platform: Windows RID: win-x64 Host: Version: 10.0.12 Commit: 95017c711e .NET runtimes installed: Microsoft.AspNetCore.App 10.0.12 Microsoft.NETCore.App 10.0.12 -
Workaround we ship in tests: an
IStartupFilterthat captures the built
pipeline, walks it toRateLimitingMiddlewareby reflection and disposes
_endpointLimiter/_globalLimiteronApplicationStopped. Fragile by
construction (private field names,AuthorizationMiddlewareInternal
hiding_nexton its base class), which is why a framework fix is the
right home. -
Skipping
UseRateLimiter()in tests is not a workaround:EndpointMiddleware
throws for any endpoint carryingRequireRateLimitingmetadata when the
middleware is absent. -
Related but distinct:
Microsoft.AspNetCore.Mvc.Testing'sHostingListener
AsyncLocal is captured by every timer started fromProgram.Main, which adds
a second path to the same host; clearing it alone does not release the host
because the pipeline path above remains.
Activity