Skip to content

Reduce allocations when serializing authentication tickets - #70172

Open
davidfowl wants to merge 5 commits into
mainfrom
perf/ticket-serializer-write
Open

davidfowl wants to merge 5 commits into
mainfrom
perf/ticket-serializer-write

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Reduce allocations when serializing authentication tickets

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

Reduce allocations when serializing authentication tickets and properties.

Description

Motivation: TicketSerializer.Serialize runs on every cookie sign-in and on every sliding-expiration or ShouldRenew refresh of the cookie. PropertiesSerializer.Serialize runs for the OAuth/OIDC state on every challenge. Both write through a MemoryStream and a BinaryWriter, then copy the result with ToArray(). That means a BinaryWriter, its internal buffers, several MemoryStream growth arrays and the final copy. identity.Claims is also enumerated twice, once for Count() and once for writing.

This is the write-side counterpart of #70165 (the read side). The two PRs are independent; this one touches only the Serialize/Write code paths.

Change (internal only, no public API or behavior change):

  • New internal BinaryPayloadWriter ref struct. It writes the same format as BinaryWriter(Stream):
    • little-endian Int32 and 1-byte booleans;
    • 7-bit length-prefixed strings encoded with Encoding.UTF8, using the same replacement fallback for invalid surrogates.
  • The writer's buffer is rented from ArrayPool<byte>.Shared. It never leaves the writer, and the used portion is cleared before being returned to the pool, so claim data can't linger in shared buffers. The result is copied once into an exact-size byte[].
  • TicketSerializer.Serialize and PropertiesSerializer.Serialize use this path only when GetType() is exactly the base type. Subclasses that might override the virtual Write/WriteIdentity/WriteClaim methods keep the existing BinaryWriter path.
  • Identity and claim counts are written as a placeholder and patched after a single enumeration of Identities/Claims, which avoids the second Count() enumeration. The count is a fixed 4-byte Int32, so the format is unchanged.
  • ArgumentNullException parameter names are unchanged (ticket, properties, value).
  • The output is byte-for-byte identical. The tests compare against the BinaryWriter path directly.

Benchmarks

Local BenchmarkDotNet run in-process, 3 rounds, main vs PR. The ticket mimics a typical Identity application cookie: 7 claims (2 roles, 3 well-known types) and properties with Issued, Expires and IsPersistent.

Method main (r1 / r2 / r3) PR (r1 / r2 / r3) main alloc PR alloc
SerializeTicket 931.7 / 926.8 / 900.7 ns (±12–19) 627.5 / 640.6 / 641.6 ns (±5–12) 2,680 B 768 B (−71%)
SerializeProperties 144.6 / 141.2 / 136.6 ns (±3) 119.9 / 121.8 / 118.4 ns (±2) 512 B 184 B (−64%)

That is about −30% time for tickets and −15% for properties. The remaining ticket allocations are the result array plus the Claim.Properties dictionaries, which the public Claim.Properties getter creates lazily.

The benchmark is added as src/Security/perf/Microbenchmarks/TicketSerializerWriteBenchmark.cs.

Tests

New tests in TicketSerializerTests:

  • Byte equality against TicketSerializer.Write(BinaryWriter, …) and against a subclass, which takes the BinaryWriter path. Tickets cover 0, 10 and 500 extra claims, which exercises buffer growth. They include:
    • a 20,000-char claim (multi-byte 7-bit length prefixes) and Unicode/emoji values;
    • claim properties, bootstrap context and nested actors;
    • a second identity, default-placeholder values and custom name/role claim types.
  • Empty principal, round trip, null-argument parameter names, and an invalid lone surrogate producing identical bytes.
  • PropertiesSerializer byte equality, including a null item value, plus the null-argument case.

Microsoft.AspNetCore.Authentication.Test: 721 passed, 3 skipped (pre-existing), 0 failed.

Benchmark (3 interleaved rounds)

src/Security/perf/Microbenchmarks/TicketSerializerWriteBenchmark.cs (added in this PR), Release builds.

Method Round main Mean ± Error PR Mean ± Error main Alloc PR Alloc
SerializeTicket 1 970.7 ns ± 58.7 634.4 ns ± 12.5 2,680 B 768 B
SerializeTicket 2 913.7 ns ± 63.0 653.1 ns ± 44.8 2,680 B 768 B
SerializeTicket 3 892.7 ns ± 21.0 624.5 ns ± 6.3 2,680 B 768 B
SerializeProperties 1 137.7 ns ± 5.3 119.8 ns ± 4.0 512 B 184 B
SerializeProperties 2 138.6 ns ± 3.5 120.4 ns ± 5.3 512 B 184 B
SerializeProperties 3 140.5 ns ± 6.0 119.9 ns ± 3.2 512 B 184 B

Averaged over rounds: about −31% time / −71% allocations for tickets and −13% time / −64% allocations for properties, consistent with the run above.

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)

When TicketSerializer/PropertiesSerializer are not subclassed, write the
payload directly into a private pooled buffer (cleared before return) and
copy it once into the result. Byte-for-byte identical to the BinaryWriter
output; claim/identity counts are patched in after a single enumeration.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 07:33
@github-actions github-actions Bot added the area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation 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.

🟡 Changes recommended

The inserted overload leaves Read(BinaryReader) without its inherited documentation, introducing a CS1591 error that fails CI builds.

1 open issue
What changed in this PR

Reduces write-side allocations for authentication tickets and properties, complementing the separate deserialization optimization in #70165.

Changes:

  • Adds a pooled binary writer and base-type serialization fast paths while preserving virtual methods for subclasses.
  • Writes identity and claim counts after a single enumeration.
  • Adds byte-compatibility tests and serialization microbenchmarks.
File Description
src/​Security/​perf/​Microbenchmarks/​TicketSerializerWriteBenchmark.cs Adds ticket and properties serialization benchmarks.
src/​Security/​perf/​Microbenchmarks/​Microsoft.AspNetCore.Security.Microbenchmarks.csproj References the authentication project for benchmarks.
src/​Security/​Authentication/​test/​TicketSerializerWriteTests.cs Tests byte compatibility, round trips, and edge cases.
src/​Security/​Authentication/​Core/​src/​TicketSerializer.cs Adds pooled serialization and single-pass counting.
src/​Security/​Authentication/​Core/​src/​PropertiesSerializer.cs Adds a pooled serialization fast path.
src/​Security/​Authentication/​Core/​src/​BinaryPayloadWriter.cs Implements binary encoding, buffer growth, and pooled-buffer cleanup.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit, 4a76c30.

The only failure was BlazorTemplates.Tests.BlazorWebTemplateTest.BlazorWebTemplate_ConditionalPasskeyRegistration on Windows (Templates.Blazor.Tests). Build Analysis puts its failure rate at 7.61%, and it's tracked as flaky in #69494 (the test reads the response body after navigation). Every other leg passed, including the Authentication, Identity and functional test legs that exercise this serializer.

This PR's serialized output is byte-identical to BinaryWriter. TicketSerializerWriteTests checks this for 0, 10 and 500 claims, 20 KB claim values, invalid surrogates and large properties.

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

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

# 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
@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 failure on 17c91e8 (build 1667853) is a known WebApplicationFactory flake and isn't caused by this PR.

Failing test: Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.CanResolveServices on OSX.26.Arm64.Open (Build Analysis: 0.85% failure rate)
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 mentioned this pull request Nov 6, 2026
3 of 4 tasks
@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: Merge after an Authentication owner accepts the second copy of the ticket writer and aspnetcore-ci is rerun green. The win is real but limited to sign-in, cookie renewal and OIDC/OAuth challenge, and it costs ~110 lines of duplicated wire-format logic in a high-risk component.

Size M: +247/−0 production lines, +127 test, +46 benchmark; 6 files, 1 shipping assembly (Microsoft.AspNetCore.Authentication) plus test and microbenchmark projects; no src/Shared
Impact Medium: SerializeTicket ~926 → 637 ns (−31%), 2,680 → 768 B; SerializeProperties ~139 → 120 ns, 512 → 184 B (3 interleaved rounds). Runs on sign-in/renewal/challenge, not every request
Risk High: auth ticket and state serialization; a format bug breaks every cookie and OIDC round trip
Tests Byte-equality against the BinaryWriter path (0/10/500 claims, 20,000-char claim, emoji, lone surrogate, actors, bootstrap context, subclass). They pin parity; they pass on main by design
Review No approvals (REVIEW_REQUIRED); one Copilot thread, fixed and resolved (thread); no human review yet
CI Red: aspnetcore-ci Helix (build 1667853), RealServerUsingMinimalBackedIntegrationTests.CanResolveServices, the WebApplicationFactory port race in #67340, unrelated. Mergeable, 441 commits behind main
Complexity Adds BinaryPayloadWriter (103 lines) and static WriteTicket/WriteIdentity/WriteClaim that must track the virtual BinaryWriter methods
Reversibility Easy; independent of the read-side PR #70165
Security sensitivity Not assessed (repo review guidance excludes it)
Encoding/escaping parity Same 7-bit length prefix and Encoding.UTF8 replacement fallback as BinaryWriter(Stream); parity tests exist
Behavior / public API change None; subclasses keep the BinaryWriter path via GetType() check

Reasons to merge

  • Cuts 1,912 B and ~290 ns per ticket serialization.
  • Output is byte-identical to main and the tests compare both paths directly.
  • Subclassed serializers keep the old virtual path.

Reasons not to merge yet

  • Any future ticket-format change must be made in two places.
  • Gain is on a per-sign-in path, not per request.
  • CI head is red and 10 days old; needs a rerun.
  • No human review yet in a high-risk area.

What would change this verdict: an owner preferring a single writer path would make this a "Don't merge" in its current shape.

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

@halter73

halter73 commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

I opened #70820 as a combined alternative to this and #70165. It keeps buffer-based read and write paths for TicketSerializer.Default and PropertiesSerializer.Default, but implements the ticket and properties format once and shares it with the BinaryReader/BinaryWriter paths. Future format changes then don't need to be kept in sync across separate optimized and legacy copies. It retains main's count-then-enumerate behavior for custom enumerables, and preserves virtual overrides and caller-provided writer encodings.

In a head-to-head comparison built against the same main commit, #70820 matches this PR's serialization gains while also optimizing deserialization. For a typical Identity cookie ticket:

Default path main #70165 this PR #70820
Serialize 2,680 B / 1,209 ns 2,680 B / 1,199 ns 768 B / 862 ns 728 B / 919 ns
Deserialize 3,592 B / 1,932 ns 2,288 B / 959 ns 3,592 B / 1,883 ns 2,896 B / 1,125 ns

Full measurements and limitations are in #70820. Its reader also needs a compatibility fix for incomplete UTF-8 at the end of long strings (also present in #70165, not in this write-only PR); I have a fix with regression tests ready.

I think the shared implementation is the better direction.

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-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation 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.

4 participants