Repository navigation
Conversation
Compute the exact payload size up front and write the session into one byte[] instead of growing a MemoryStream and copying it with ToArray(). Deserialize directly from the cached byte[] instead of wrapping it in a MemoryStream and reading byte-by-byte through virtual Stream calls. The wire format is unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
The required frozen review bundle was missing, preventing validation of head/base identities, routed guidance, and existing-feedback coverage.
No open issues 🎉
What changed in this PR
Reduces allocation and CPU overhead in DistributedSession commit and load operations while preserving the existing wire format and malformed-payload behavior.
Changes:
- Replaces growable stream serialization with one exactly sized byte array and span-based writes.
- Reads cached payloads directly through a private byte-array reader.
- Adds tests for exact serialized bytes, value round trips, truncated payloads, and unknown revisions.
| File | Description |
|---|---|
src/Middleware/Session/test/SessionTests.cs |
Adds serialization compatibility and error-handling tests. |
src/Middleware/Session/src/DistributedSession.cs |
Replaces stream-based serialization and deserialization with direct byte-array operations. |
Review effort: Balanced
|
/azp run aspnetcore-components-e2e The 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
No pipelines are associated with this pull request. |
|
/azp run aspnetcore-components-e2e Update: Build Analysis shows that the E2E failures are known flaky tests unrelated to session:
The session-based E2E tests ( 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
No pipelines are associated with this pull request. |
|
/azp run aspnetcore-components-e2e Retrying now that the previous run has completed. The failures are the known flaky tests listed above. 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
No pipelines are associated with this pull request. |
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
Retriggered CI with an empty commit, a94373e, because Evidence that the failure is flaky. Build Analysis shows only known flaky Blazor E2E tests failed:
Neither touches session. Every other check, including the session-based E2E tests and all Helix test legs, passed. 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
/review |
|
Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime. |
Merge assessmentVerdict: Lean merge. One-file change in
Reasons to merge
Reasons not to merge yet
What would change this verdict: a Session owner objecting to the hand-written reader would move this to Hold. 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
Reduce allocations when serializing DistributedSession
Reduce allocations and CPU when committing and loading
DistributedSession.Description
Motivation: every request that modifies session state calls
DistributedSession.CommitAsync. It serializes into a growableMemoryStream, writing one byte at a time for the length prefixes, and then copies the result withToArray(). For a session holding a few KB, that allocates the payload about three times: the doubling buffers plus the final copy. Loading wraps the cachedbyte[]in aMemoryStreamand reads every length prefix byte by byte through virtualStream.ReadBytecalls.Change (internal implementation only, no public API or behavior change):
Serializecomputes the exact payload size first, then writes into a single right-sizedbyte[]with span copies andBinaryPrimitives.ArgumentOutOfRangeExceptions are thrown.Deserializereads straight from the cachedbyte[]through a small private struct reader that mirrorsMemoryStreamsemantics:ReadBytereturns-1past the end.ReadBytesallocates first, so negative lengths still throwOverflowException, then throwsEndOfStreamExceptionwhen data is short.Benchmarks
Local BenchmarkDotNet run in-process, 3 rounds, main vs PR. The setup is
DistributedSessionwith an in-memoryIDistributedCachestub.Commitcreates a session,Sets N entries and callsCommitAsync.Loadcreates a session, callsLoadAsyncand does oneTryGetValue. Means are shown as round 1 / round 2 / round 3.Round 1 used a different job configuration than rounds 2–3, so its absolute numbers run higher; compare within a round.
Commitis roughly 20–37% faster with 27–50% less allocation.Loadis neutral to about 10% faster, saving theMemoryStream. None of the cases regressed. Error was ≤ ~10% of the mean in all rounds.Benchmark code (not included in the PR)
Tests
SessionTests:DistributedSession_CommitWritesExpectedFormat: an exact byte-for-byte golden payload, including a multi-byte UTF-8 key and an empty value.DistributedSession_RoundTripsValues: 100 KB value, empty value, 1,000-char key.DistributedSession_TruncatedPayload_LoadAsyncThrowsEndOfStream:LoadAsyncstill throwsEndOfStreamException, and the sync path still marks the session unavailable.DistributedSession_UnknownRevision_IsTreatedAsEmptyAndRewritten.mainimplementation, which confirms identical format and failure behavior.Microsoft.AspNetCore.Session.Tests: 32/32 passed.🤖 Posted by ASP.NET Core Perf 2 (AI Agent)