Skip to content

Reduce per-call overhead in UserValidator - #70224

Merged
davidfowl merged 3 commits into
mainfrom
perf/identity-user-validator
Nov 16, 2026
Merged

davidfowl merged 3 commits into
mainfrom
perf/identity-user-validator

Conversation

@davidfowl

@davidfowl davidfowl commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Reduce per-call overhead in UserValidator

  • 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.

Cache SearchValues for user name checks; reuse EmailAddressAttribute

Description

UserValidator<TUser>.ValidateAsync runs on every CreateAsync/UpdateAsync and on user name and email changes. It had two avoidable costs:

  1. Allowed characters check. The check was userName.Any(c => !manager.Options.User.AllowedUserNameCharacters.Contains(c)). This allocates a closure and delegate per call. It also re-reads the options and does a linear string.Contains over the 65-character default set for every character of the user name.
  2. Email format check. new EmailAddressAttribute() was constructed on every call when RequireUniqueEmail is enabled. The attribute's constructor does a resource lookup for its default error message.

Change:

  • On .NET 8+, the allowed-characters check uses ContainsAnyExcept(SearchValues<char>). The SearchValues is cached in a static field, keyed by the configured AllowedUserNameCharacters string with an ordinal comparison. If the option changes, the cache is rebuilt, and a new test covers this. The cache is static because UserValidator is registered as scoped. It only holds data derived from configuration, never user input, and isn't reachable by callers. On netstandard2.0/net462, a plain loop with string.IndexOf(char) replaces the LINQ closure.
  • The EmailAddressAttribute is now a static readonly instance. EmailAddressAttribute.IsValid is stateless.
  • No public API or behavior changes. Matching is still ordinal per UTF-16 code unit, and null/empty AllowedUserNameCharacters still disables the check.

Benchmark

Interleaved A/B on the same machine, 3 rounds. Each round runs main then this PR, using Release builds of Microsoft.Extensions.Identity.Core (net12.0) and BenchmarkDotNet's in-process toolchain. The benchmark calls the real UserValidator<TUser>.ValidateAsync with a UserManager over a no-op store whose FindByName/FindByEmail return null. The user name/email is [email protected].

Method Round main Mean PR Mean main Alloc PR Alloc
Validate_Default 1 142.8 ns 83.05 ns 320 B 296 B
Validate_Default 2 144.0 ns 85.00 ns 320 B 296 B
Validate_Default 3 145.7 ns 83.49 ns 320 B 296 B
Validate_RequireUniqueEmail 1 277.3 ns 166.52 ns 544 B 520 B
Validate_RequireUniqueEmail 2 282.5 ns 167.33 ns 544 B 520 B
Validate_RequireUniqueEmail 3 278.1 ns 168.40 ns 544 B 520 B

That's about −42% time with default options and −40% with RequireUniqueEmail. Most of the remaining time and allocation is the async state machine and store calls.

In isolation on .NET 10, the allowed-characters check for this user name drops from 52.7 ns to 2.5 ns. Constructing and running EmailAddressAttribute drops from 60 ns / 88 B to 6.7 ns / 0 B. I also measured an uncached IndexOfAnyExcept(string): it was slower than main (79 ns) because it rebuilds a probabilistic map for the 65-character set on every call, which is why the SearchValues is cached.

Benchmark code
[MemoryDiagnoser]
public class UserValidatorBench
{
    readonly UserValidator<TestUser> _v = new();
    readonly UserManager<TestUser> _default = Mgr.Create(_ => { });
    readonly UserManager<TestUser> _uniqueEmail = Mgr.Create(o => o.User.RequireUniqueEmail = true);
    readonly TestUser _user = new(); // UserName = Email = "[email protected]"

    [Benchmark] public Task<IdentityResult> Validate_Default() => _v.ValidateAsync(_default, _user);
    [Benchmark] public Task<IdentityResult> Validate_RequireUniqueEmail() => _v.ValidateAsync(_uniqueEmail, _user);
}

static class Mgr
{
    public static UserManager<TestUser> Create(Action<IdentityOptions> configure)
    {
        var o = new IdentityOptions(); configure(o);
        return new UserManager<TestUser>(new NoopStore(), Options.Create(o), null!, null!, null!,
            new UpperInvariantLookupNormalizer(), null!, null!, NullLogger<UserManager<TestUser>>.Instance);
    }
}

Tests

  • New UsesCurrentAllowedUserNameCharacters test. It changes AllowedUserNameCharacters between calls on the same validator, including non-ASCII characters, and checks that the current value is always honored.
  • Microsoft.AspNetCore.Identity.Test: 566 passed, 0 failed, 1 skipped. The 16 IdentityUIScriptsTest CDN tests were excluded locally because they need network access the sandbox does not have.
  • Microsoft.AspNetCore.Identity.InMemory.Test (user manager specification tests): 226/226 passed.
  • Microsoft.Extensions.Identity.Core builds cleanly for net12.0, netstandard2.0 and net462.

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

Check allowed user name characters with a SearchValues<char> cached by the
configured string instead of a LINQ Any + string.Contains per character,
and reuse a single EmailAddressAttribute instance.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 15:18
@github-actions github-actions Bot added the area-identity Includes: Identity and providers label Nov 1, 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.

🔵 Needs a closer look

The required frozen review bundle was not supplied, preventing verification of the head/base revision identities and existing-feedback snapshot.

No open issues 🎉

What changed in this PR

Reduces per-call overhead in Identity’s UserValidator<TUser> while preserving existing username and email validation behavior.

Changes:

  • Caches SearchValues<char> for allowed username characters on .NET 8+, with a loop-based fallback for older targets.
  • Reuses a single EmailAddressAttribute instance.
  • Adds coverage for changes to allowed username characters, including non-ASCII characters.
File Description
src/​Identity/​test/​Identity.Test/​UserValidatorTest.cs Tests that validation honors updated allowed-character settings.
src/​Identity/​Extensions.Core/​src/​UserValidator.cs Optimizes character checks and reuses the email validation attribute.

Review effort: Balanced

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent

Copy link
Copy Markdown
Member Author

The aspnetcore-ci failures on e983d13 (build 1667824) are a known WebApplicationFactory flake and aren't caused by this PR.

Failing tests (Windows.Amd64.VS2026.Open, same exception):

  • Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.CanResolveServices (0.92% failure rate)
  • Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.RetrievesDataFromRealServer (0.12%)

InvalidOperationException: IServerAddressesFeature.Addresses cannot be modified after the server has started. at WebApplicationFactory.TryConfigureServerPort

Why it's unrelated

I didn't retrigger CI because main E2E is currently flaky. A maintainer can rerun the failed job if needed.

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

@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 7, 2026 — with Copilot SWE Agent

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit, so the new head is 0f8298f. The PR diff is unchanged.

Failing tests (aspnetcore-ci build 1667824 on e983d13):

  • Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.CanResolveServices
  • Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.RetrievesDataFromRealServer

Why they're unrelated: This PR only touches Identity's UserValidator and UserValidatorTest. These MVC functional tests don't use Identity. They fail because of the WebApplicationFactory Kestrel port race tracked in #67340, and the fix for it is still open in #67714.

Cross-PR evidence: CanResolveServices also fails on #70172 and #70177, and it failed once on main (86c0eb5). The newer main run (5718eb0) passed, so main isn't consistently broken.

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

@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 7, 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 14, 2026

Copy link
Copy Markdown
Member Author

Merge assessment

Verdict: Lean merge, low priority. The change is small and behavior-preserving, but UserValidator<TUser>.ValidateAsync only runs on CreateAsync/UpdateAsync/user name and email changes, so the win is on a cold path.

Size S: +45/−4 production lines, +23 test, +0 benchmark; 2 files, 1 shipping assembly (Microsoft.Extensions.Identity.Core, net462/netstandard2.0/net); no src/Shared
Impact Low: Validate_Default ~144 → 84 ns, Validate_RequireUniqueEmail ~279 → 167 ns, −24 B per call (3 interleaved rounds)
Risk Medium: Identity helper (Low) raised for a static SearchValues<char> cache that outlives the call
Tests New UsesCurrentAllowedUserNameCharacters checks the cache follows option changes; passes on main (guard, not a fix). Existing CanAllowNonAlphaNumericUserName covers the fast path
Review No approvals (REVIEW_REQUIRED); no review threads; no human review yet
CI Green on 0f8298ff (Nov 7). Mergeable, 469 commits behind main
Complexity Adds #if NET8_0_OR_GREATER split, a nested cache class and a static field (+41 net lines)
Reversibility Easy; single file
Security sensitivity Not assessed (repo review guidance excludes it)
Encoding/escaping parity n/a (validation only; matching stays ordinal per UTF-16 unit, same as string.Contains(char))
Behavior / public API change None

Reasons to merge

  • ~40% faster validation and no closure allocation.
  • Reusing one EmailAddressAttribute drops a resource lookup per call.
  • Null/empty AllowedUserNameCharacters still disables the check.

Reasons not to merge yet

  • Runs only on user create/update, so app-level impact is near zero.
  • Two hosts in one process with different AllowedUserNameCharacters would rebuild SearchValues on alternating calls, likely slower than main (unmeasured).
  • Adds a framework-conditional code path for a cold-path gain.

What would change this verdict: an Identity owner preferring to keep the simpler code would make this "Don't merge: cold path".

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

@davidfowl
davidfowl merged commit 4914767 into main Nov 16, 2026
34 checks passed
@davidfowl
davidfowl deleted the perf/identity-user-validator branch November 16, 2026 23:57
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 18, 2026
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