Skip to content

Cache Identity UserManager/SignInManager metrics per IMeterFactory - #70174

Open
davidfowl wants to merge 6 commits into
mainfrom
perf/identity-metrics-cache
Open

davidfowl wants to merge 6 commits into
mainfrom
perf/identity-metrics-cache

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Cache Identity UserManager/SignInManager metrics per IMeterFactory

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Avoid rebuilding Identity metrics per scoped UserManager/SignInManager

Description

Avoid rebuilding the Identity metrics objects on every scoped UserManager / SignInManager construction.

UserManager<TUser> and SignInManager<TUser> are registered as scoped, so they are constructed per request whenever Identity is used. That includes every cookie-authenticated request that reaches SecurityStampValidator. Each constructor created a new UserManagerMetrics / SignInManagerMetrics, which:

  • calls IMeterFactory.Create(...), which allocates MeterOptions and does a lookup in the factory's cache, and
  • re-creates 6 instruments. Meter.Create* looks up and returns the already-existing instrument, but it still allocates advice and other options objects each time.

Both the meter (per factory) and the instruments (per meter) are already cached, so every instance built from the same IMeterFactory is functionally identical.

Change: each metrics class gets a static GetOrCreate(IMeterFactory) backed by a private static ConditionalWeakTable<IMeterFactory, T>.

  • The cached object holds only the meter and instruments that the factory already shares.
  • It holds no per-user or per-request state, and it isn't reachable from user code.
  • The factory is weakly held, so nothing is kept alive past the factory's lifetime.
  • Different factories (e.g. different hosts or test servers) still get separate metrics.
  • No public API changes.

Benchmark

Local BenchmarkDotNet run, A/B against main, 3 rounds. The benchmark resolves the manager in a new DI scope with AddIdentityCore<object>().AddSignInManager().AddDefaultTokenProviders() and a no-op store.

Method Round main Mean PR Mean main Alloc PR Alloc
ResolveUserManager 1 1.830 us ± 0.036 1.166 us ± 0.010 4,336 B 2,864 B
ResolveUserManager 2 2.189 us ± 0.043 1.378 us ± 0.027 4,336 B 2,864 B
ResolveUserManager 3 2.221 us ± 0.044 1.409 us ± 0.028 4,336 B 2,864 B
ResolveSignInManager 1 2.559 us ± 0.045 1.490 us ± 0.028 5,232 B 3,072 B
ResolveSignInManager 2 2.929 us ± 0.057 1.701 us ± 0.034 5,232 B 3,072 B
ResolveSignInManager 3 3.043 us ± 0.060 1.514 us ± 0.029 5,232 B 3,072 B

That's about −37% time and −34% allocations for UserManager, and about −45% time and −41% allocations (−2,160 B per scope) for SignInManager.

Benchmark code
[MemoryDiagnoser]
public class IdentityResolveBenchmark
{
    private ServiceProvider _services;

    [GlobalSetup]
    public void Setup()
    {
        var services = new ServiceCollection();
        services.AddLogging();
        services.AddMetrics();
        services.AddAuthentication();
        services.AddScoped<IUserStore<object>, FakeStore>(); // all members throw NotImplementedException
        services.AddIdentityCore<object>().AddSignInManager().AddDefaultTokenProviders();
        _services = services.BuildServiceProvider();
    }

    [Benchmark]
    public object ResolveUserManager()
    {
        using var scope = _services.CreateScope();
        return scope.ServiceProvider.GetRequiredService<UserManager<object>>();
    }

    [Benchmark]
    public object ResolveSignInManager()
    {
        using var scope = _services.CreateScope();
        return scope.ServiceProvider.GetRequiredService<SignInManager<object>>();
    }
}

Tests

  • New tests:
    • MultipleUserManagersWithSameMeterFactory_RecordMetrics and UserManagersWithDifferentMeterFactories_RecordMetricsToOwnFactory in UserManagerTest.
    • MultipleSignInManagersWithSameMeterFactory_RecordMetrics in SignInManagerTest.
    • Together they check that multiple managers sharing a factory all record, and that separate factories stay isolated.
  • Microsoft.AspNetCore.Identity.Test: 568 passed. The only failures were the 16 IdentityUIScriptsTest CDN tests, which need network access that the local sandbox doesn't have.
  • Microsoft.AspNetCore.Identity.FunctionalTests (MapIdentityApiTests, including the metrics tests): 81/81 passed.

Benchmark (3 interleaved rounds)

New src/Security/perf/Microbenchmarks/IdentityManagerResolveBenchmark.cs (same setup as the code above). Release builds.

Method Round main Mean ± Error PR Mean ± Error main Alloc PR Alloc
ResolveUserManager 1 1.828 µs ± 0.034 1.214 µs ± 0.090 4,336 B 2,864 B
ResolveUserManager 2 1.803 µs ± 0.055 1.164 µs ± 0.019 4,336 B 2,864 B
ResolveUserManager 3 1.773 µs ± 0.057 1.221 µs ± 0.062 4,336 B 2,864 B
ResolveSignInManager 1 2.578 µs ± 0.075 1.631 µs ± 0.379 5,232 B 3,072 B
ResolveSignInManager 2 2.836 µs ± 0.403 1.468 µs ± 0.029 5,232 B 3,072 B
ResolveSignInManager 3 2.525 µs ± 0.039 1.537 µs ± 0.073 5,232 B 3,072 B

Averaged over rounds: about −34% time / −1,472 B for UserManager and −42% time / −2,160 B for SignInManager.

Machine: AMD EPYC 9V74, 2 cores, Linux; .NET SDK 12.0.100-alpha.1.26521.103, .NET 12.0.0 (12.0.26.52911) X64 RyuJIT, Server GC. BenchmarkDotNet in-process toolchain, --warmupCount 3 --iterationCount 10, [MemoryDiagnoser]. "main" is this PR's merge base (4f556f7); both builds use identical benchmark source. Runs were interleaved: main, PR, main, PR, main, PR.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

UserManager and SignInManager are scoped and constructed on every request that
uses Identity (e.g. SecurityStampValidator). Each construction created a new
metrics object that re-resolved the meter from the factory and re-created all
instruments. Meters and instruments are already cached by the meter factory and
meter, so cache the metrics wrapper per IMeterFactory in a private
ConditionalWeakTable.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 08:01
@github-actions github-actions Bot added the area-identity Includes: Identity and providers label Oct 31, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the per-factory metrics caching change.

No open issues 🎉

What changed in this PR

Reduces repeated metrics setup during scoped Identity manager construction by caching metrics instances per IMeterFactory, without changing public APIs.

Changes:

  • Adds weak-key caches for UserManagerMetrics and SignInManagerMetrics.
  • Updates both managers to reuse cached metrics instances.
  • Adds tests for recording through shared factories and isolating UserManager metrics across different factories.
File Description
src/​Identity/​test/​Identity.Test/​UserManagerTest.cs Tests shared-factory recording and separate-factory isolation.
src/​Identity/​test/​Identity.Test/​SignInManagerTest.cs Tests recording from multiple managers sharing a factory.
src/​Identity/​Extensions.Core/​src/​UserManagerMetrics.cs Adds a weak-key, per-factory metrics cache.
src/​Identity/​Extensions.Core/​src/​UserManager.cs Uses the cached UserManager metrics instance.
src/​Identity/​Core/​src/​SignInManagerMetrics.cs Adds a weak-key, per-factory metrics cache.
src/​Identity/​Core/​src/​SignInManager.cs Uses the cached SignInManager metrics instance.

Review effort: Balanced

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Source-only review of frozen head 5c5d461e4067b8a47e88e2b6b80d7112020d8805 found one new P3 test-coverage issue: the added shared-factory tests do not distinguish cached metrics wrappers from the previous per-manager construction.

The prepared existing feedback contained no equivalent finding; no candidates remain unresolved. docs/CrossCuttingGuidance.md completed with all in-scope checks assessed by the required independent gpt-5.6-sol worker. Runtime/test execution and security assessment were explicitly excluded. No Identity-specific specialist guide was routed, so that domain remains uncovered beyond cross-cutting review.

Provenance: PR 70174, merge base/base tip 4f556f73a610b386e5ec29355a300e493d30c4c5, immutable reviewer guidance from 4f556f73a610b386e5ec29355a300e493d30c4c5. Proof is source-only; target code, tests, CI, post-preparation feedback, and symlink/submodule/LFS targets were not observed.

Generated by ASP.NET Core Pull Request Review for #70174 · copilot · gpt56 · 140.5 AIC · ⌖ 11.4 AIC · ⊞ 20.2K
Comment /review to run again

davidfowl and others added 2 commits November 1, 2026 18:07
…per factory

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (3385859) because the only failure on the previous run looks like an unrelated flake.

  • Failing test: Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.Tests.NamedPipeConnectionListenerTests.AcceptAsync_ParallelConnections_ClientConnectionsSuccessfullyAccepted (Helix work item BadExit on Windows.Amd64.VS2026.Open)
  • Build: 1658782
  • Historical failure rate: ~0.19%; Build Analysis matched no known issue
  • Unrelated to this PR, which only touches Identity SignInManager/UserManager metrics and their tests

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@davidfowl
davidfowl requested a review from halter73 as a code owner November 2, 2026 22:03
# Conflicts:
#	src/Security/perf/Microbenchmarks/Microsoft.AspNetCore.Security.Microbenchmarks.csproj
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@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 13, 2026

Copy link
Copy Markdown
Member Author

Merge assessment

Verdict: Lean merge. 20 production lines remove ~1 µs and 2,160 B from every scope that builds SignInManager, which in AddIdentity apps is every cookie-authenticated request via SecurityStampValidator<TUser>.

Size S: +20/−2 production lines, +95 test, +69 benchmark; 9 files, 2 shipping assemblies (Microsoft.AspNetCore.Identity, Microsoft.Extensions.Identity.Core); no src/Shared
Impact Medium: ResolveSignInManager ~2.65 → 1.55 µs, 5,232 → 3,072 B; ResolveUserManager ~1.80 → 1.20 µs, 4,336 → 2,864 B (3 interleaved rounds)
Risk Medium: Identity (Low) raised for 2 assemblies and a static ConditionalWeakTable<IMeterFactory, …> cache
Tests Same-factory tests assert IMeterFactory.Create is called once (fail on main with Expected: 1, Actual: 2 per thread); a separate-factory test checks isolation
Review No approvals (REVIEW_REQUIRED); one bot thread, fixed and resolved; no human review yet
CI Green on d0fe92b0 (Nov 6). Mergeable, 441 commits behind main
Complexity Low: two one-line GetOrCreate helpers
Reversibility Easy
Security sensitivity Not assessed (repo review guidance excludes it)
Encoding/escaping parity n/a
Behavior / public API change None; managers never dispose the metrics object, and meter/instruments were already shared per factory

Reasons to merge

  • Per-request saving for Identity cookie apps, not just a cold path.
  • Change is two call sites plus two static helpers.
  • Tests fail without the cache and check per-factory isolation.

Reasons not to merge yet

  • Adds process-wide static state keyed by IMeterFactory, which reviewers must reason about for multi-host processes.
  • The gain is in DI resolution; it is unmeasured end-to-end.
  • CI is 10 days old.

What would change this verdict: evidence that an IMeterFactory can be reused after disposal would move this to Hold.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

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-identity Includes: Identity and providers pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants