Skip to content

Improve SignalR hot paths and add regression benchmarks - #69189

Merged
BrennanConroy merged 4 commits into
mainfrom
davidfowl-performance-improvements
Sep 29, 2026
Merged

BrennanConroy merged 4 commits into
mainfrom
davidfowl-performance-improvements

Conversation

@davidfowl

@davidfowl davidfowl commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Improve SignalR hot paths and add regression benchmarks

  • Read the Contributor Guide and Code of Conduct.
  • Include unit tests for the changed behavior.
  • Include inline documentation where applicable.
  • Link an existing issue. No issue is linked to this PR.

Reduce SignalR send, reconnect, authorization, and SSE overhead.

Description

This changes five paths without introducing public APIs:

  • Use indexed connection lookup for SendConnectionsAsync with at most 16 target IDs, with allocation-free duplicate suppression and shared serialization. Larger lists retain the original scan to avoid target-sized allocations and unbounded deduplication work.
  • Track the last MessageBuffer block so appends no longer traverse the retained reconnect backlog. This is shared by the server and .NET client.
  • Cache successful combined hub-method authorization policies per method and provider identity, only when AllowsCachingPolicies permits it. A ConditionalWeakTable avoids retaining scoped/transient providers. Authorization is still evaluated against the current user, resource, and scoped services on every invocation; failed/canceled combinations are not cached.
  • Initialize per-invocation cancellation tracking only when needed. Unknown cancellation messages do not initialize it; ConnectionAborted remains independent of this dictionary.
  • Format multiline SSE messages into a pooled contiguous buffer and perform one output write. A per-segment LF count gives a safe size upper bound; only the actual formatted bytes are written. The rental remains owned until the output completes and is returned on success, failure, or cancellation.

Adds 10 benchmark classes covering 58 scenarios, including adverse inputs and serial/concurrent group churn. Group membership code is unchanged; those benchmarks establish controls and future optimization coverage.

The merge of main preserves its expanded authorization metadata support (IAuthorizeData, AuthorizationPolicy, and IAuthorizationRequirementData). Metadata that produces no policy remains allowed; null results are not inserted into the cache.

Before / after

Benchmark provenance after merging main: These tables compare original production code at c4d061a54c669a55ca9aa18982b416e9d3ff4d2b against pre-merge PR commit 78bfc6342eea99f4c5494ffea08ea758505e6ce0, including the simplified authorization cache and LF-count SSE sizing. They have not been rerun after merging main at ef51aa77663661cb9162820b67e89488372dd473 and adapting the cache to its expanded authorization-metadata API. They are retained as measurements of that earlier revision, not claims about the merged code or updated SDK/runtime.

Representative scenario Before After Time change Allocated B/op before -> after
Send to 1 of 1,000 connections 26.65 us 179.22 ns -99.3% 321 -> 256
Send to all 10 of 10 connections 710.38 ns 878.80 ns +23.7% 320 -> 256
Reconnect append, 1,000 retained messages 225.03 ns 134.13 ns -40.4% 0 -> 0
Reconnect burst, 1,000 retained messages, per message 181.43 ns 82.21 ns -54.7% 0 -> 0
Authorized invocation, cacheable singleton provider 1,090.39 ns 871.11 ns -20.1% 2,528 -> 1,872
Authorized invocation, cacheable fresh scoped provider 1,138.68 ns 1,331.92 ns +17.0% 2,576 -> 2,602
Connection creation/cleanup, unused cancellation tracking 280.04 ns 168.35 ns -39.9% 2,272 -> 1,408
Connection creation/cleanup, used cancellation tracking 298.67 ns 301.41 ns +0.9% 2,320 -> 2,352
Large multiline SSE, synchronous output 60.90 us 8.51 us -86.0% 259,171 -> 0
Large multiline SSE, forced asynchronous output 86.04 us 25.52 us -70.3% 259,474 -> 354
SSE, one-byte segments 71.12 us 75.81 us +6.6% 16,338 -> 2

Tradeoffs and uncertainty

  • Dense small fanout is slower. The 10-of-10 case is +23.7% in the full run and +3.6% in the reverse-order repeat (785.52 -> 813.77 ns). The magnitude varies; this is not an across-the-board send improvement.
  • One-use cacheable scoped providers pay for cache insertion without reuse: +17.0% / +14.7% in the two pairs, with about 26 additional allocated bytes per invocation. The simple, provider-correct cache deliberately does not add an admission heuristic. Warm singleton authorization improves 20.1% / 17.4%, saving 656 B per invocation.
  • Used cancellation tracking costs 32 B more per connection. Savings apply only to connections that never need per-invocation tracking, not merely those that never receive cancellation.
  • One-byte SSE segmentation is not a demonstrated throughput win: +6.6% in the full run, -0.3% in the repeat. Allocation falls substantially in both.
  • LF-count sizing can over-reserve for CRLF. Each trimmed CR leaves an extra reserved byte; at an array-pool boundary this can select the next bucket, potentially doubling rented capacity. Only actual output is sent. Pooling also trades repeated managed allocations for pool-retained capacity; the allocation column is not a peak-memory measurement.
  • Concurrent group timings are noisy controls, not optimization claims. No production group code changed. The 8-worker/1,024-member shared case changes +10.1% then -3.8%; the independent case changes +1.2% then +14.8% with high variance in the latter run. Small control differences, including non-cacheable authorization, should not be interpreted as reliable gains.

Methodology

Apple M2 Max, Arm64, 12 physical/logical cores; macOS 26.6.2 (25G83). SDK 11.0.100-preview.6.26318.108, runtime .NET 11.0.0 (11.0.26.36017), BenchmarkDotNet 0.13.0, Release builds. --config debug selects the repository's in-process benchmark toolchain; it does not mean Debug compilation.

Both builds use identical new benchmark sources and dependencies. A temporary MSBuild compile-item overlay supplies the six production files from the baseline commit, including the shared buffer in both server/client and the formatter linked into the benchmark assembly. Separate output snapshots prevent loading current dependencies into the baseline. Source fingerprints, substitution manifests, and baseline/current assembly markers were checked.

Each case uses 10 warmups, 7 measured iterations, and a 200 ms target iteration time. All 58 scenarios were run before then after, sequentially with no overlapping builds. A 24-case subset was then rerun after then before. Tables below retain the complete primary results and the separate repeat, rather than selecting the fastest run. Percentages are (after / before - 1) * 100; negative is faster.

Results are mean time and managed allocation per operation, not end-to-end network throughput. Reconnect burst results are per appended message (OperationsPerInvoke = 32). Group results are per add/remove pair (concurrent batches contain 1,024 pairs and include scheduling costs). The authorization benchmark waits for successful invocation completion, not just dispatch enqueueing. The SSE output benchmark verifies bytes written and exercises both actual synchronous and forced asynchronous sinks.

OriginalScan is a copied original-algorithm control; IndexedSend invokes the actual lifetime-manager API in each build (and takes the original-scan fallback for these >16-target adverse cases). Compare each method across builds, not the two methods as if they were the before/after pair. Small nonzero allocations in longer-running cases can include measurement/background noise. Concurrent group allocation totals also vary between runs; compare within a pair.

All 58 primary before/after results (time in ns)
Benchmark Parameters Before ns After ns Time change Before B/op After B/op
HubConnectionContextCreationBenchmark.CreateAndCleanup TrackCancellation=False 280.04 168.35 -39.9% 2272.00 1408.00
HubConnectionContextCreationBenchmark.CreateAndCleanup TrackCancellation=True 298.67 301.41 +0.9% 2320.00 2352.00
HubGroupListBenchmark.AddAndRemove ConnectionsPerGroup=0 403.31 416.80 +3.3% 1080.00 1080.00
HubGroupListBenchmark.AddAndRemove ConnectionsPerGroup=1 206.85 212.64 +2.8% 96.00 96.00
HubGroupListBenchmark.AddAndRemove ConnectionsPerGroup=1024 8240.03 8545.20 +3.7% 96.00 96.00
HubGroupListBenchmark.AddAndRemove ConnectionsPerGroup=32 614.38 647.93 +5.5% 96.00 96.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1&SharedGroup=False 228.54 234.97 +2.8% 226.00 226.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1&SharedGroup=True 229.32 230.05 +0.3% 226.00 226.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1024&SharedGroup=False 8292.47 8176.32 -1.4% 226.00 226.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1024&SharedGroup=True 8257.72 8339.89 +1.0% 226.00 226.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1&SharedGroup=False 186.13 160.67 -13.7% 227.00 227.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1&SharedGroup=True 567.96 566.06 -0.3% 228.00 228.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1024&SharedGroup=False 4114.45 4165.21 +1.2% 227.00 227.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1024&SharedGroup=True 10778.64 11870.68 +10.1% 227.00 227.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=False&ProviderLifetime=Scoped 1207.08 1174.48 -2.7% 2576.00 2576.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=False&ProviderLifetime=Singleton 1083.24 1104.76 +2.0% 2528.00 2528.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=True&ProviderLifetime=Scoped 1138.68 1331.92 +17.0% 2576.00 2602.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=True&ProviderLifetime=Singleton 1090.39 871.11 -20.1% 2528.00 1872.00
HubMethodAuthorizationBenchmark.Unprotected AllowsCachingPolicies=False&ProviderLifetime=Scoped 209.66 207.31 -1.1% 496.00 496.00
HubMethodAuthorizationBenchmark.Unprotected AllowsCachingPolicies=False&ProviderLifetime=Singleton 209.46 211.51 +1.0% 496.00 496.00
HubMethodAuthorizationBenchmark.Unprotected AllowsCachingPolicies=True&ProviderLifetime=Scoped 206.89 205.47 -0.7% 496.00 496.00
HubMethodAuthorizationBenchmark.Unprotected AllowsCachingPolicies=True&ProviderLifetime=Singleton 211.02 205.71 -2.5% 496.00 496.00
MessageBufferBenchmark.AppendAndAcknowledge UnacknowledgedMessages=0 131.98 133.02 +0.8% 0.00 0.00
MessageBufferBenchmark.AppendAndAcknowledge UnacknowledgedMessages=10 135.31 132.21 -2.3% 0.00 0.00
MessageBufferBenchmark.AppendAndAcknowledge UnacknowledgedMessages=100 138.35 132.61 -4.2% 0.00 0.00
MessageBufferBenchmark.AppendAndAcknowledge UnacknowledgedMessages=1000 225.03 134.13 -40.4% 0.00 0.00
MessageBufferBenchmark.BurstAndAcknowledge UnacknowledgedMessages=0 84.02 81.11 -3.5% 0.00 0.00
MessageBufferBenchmark.BurstAndAcknowledge UnacknowledgedMessages=10 85.72 83.01 -3.2% 0.00 0.00
MessageBufferBenchmark.BurstAndAcknowledge UnacknowledgedMessages=100 89.85 81.94 -8.8% 0.00 0.00
MessageBufferBenchmark.BurstAndAcknowledge UnacknowledgedMessages=1000 181.43 82.21 -54.7% 0.00 0.00
SendConnectionsAdverseBenchmark.IndexedSend Scenario=Dense 1194651.63 1182957.61 -1.0% 266.00 266.00
SendConnectionsAdverseBenchmark.IndexedSend Scenario=DuplicateHeavy 307.18 310.98 +1.2% 232.00 232.00
SendConnectionsAdverseBenchmark.IndexedSend Scenario=Empty 62.62 64.16 +2.5% 64.00 64.00
SendConnectionsAdverseBenchmark.IndexedSend Scenario=Missing 776787.71 809639.19 +4.2% 86.00 87.00
SendConnectionsAdverseBenchmark.OriginalScan Scenario=Dense 1463412.13 1438611.10 -1.7% 307.00 307.00
SendConnectionsAdverseBenchmark.OriginalScan Scenario=DuplicateHeavy 270.48 262.25 -3.0% 232.00 232.00
SendConnectionsAdverseBenchmark.OriginalScan Scenario=Empty 60.85 61.41 +0.9% 64.00 64.00
SendConnectionsAdverseBenchmark.OriginalScan Scenario=Missing 772574.08 772294.91 -0.0% 86.00 87.00
SendConnectionsBenchmark.SendAsync Connections=10&TargetConnections=1 348.72 181.53 -47.9% 320.00 256.00
SendConnectionsBenchmark.SendAsync Connections=10&TargetConnections=10 710.38 878.80 +23.7% 320.00 256.00
SendConnectionsBenchmark.SendAsync Connections=10&TargetConnections=2 403.29 256.38 -36.4% 320.00 256.00
SendConnectionsBenchmark.SendAsync Connections=1000&TargetConnections=1 26652.53 179.22 -99.3% 321.00 256.00
SendConnectionsBenchmark.SendAsync Connections=1000&TargetConnections=10 54827.76 879.63 -98.4% 322.00 256.00
SendConnectionsBenchmark.SendAsync Connections=1000&TargetConnections=2 30424.01 243.74 -99.2% 321.00 256.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=DenseNewlines 265401.13 153958.64 -42.0% 131104.00 5.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=Fragmented 71119.43 75813.37 +6.6% 16338.00 2.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=LateNewline 63815.51 8623.43 -86.5% 197275.00 0.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=Tiny 118.69 67.06 -43.5% 344.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=32&LineCount=1&Segmented=False 23.08 18.83 -18.4% 0.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=32&LineCount=1&Segmented=True 42.23 39.95 -5.4% 0.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=32&LineCount=16&Segmented=False 929.02 543.89 -41.5% 1928.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=32&LineCount=16&Segmented=True 930.33 558.61 -40.0% 1928.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=4096&LineCount=1&Segmented=False 138.76 135.21 -2.6% 0.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=4096&LineCount=1&Segmented=True 166.12 158.12 -4.8% 0.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=4096&LineCount=16&Segmented=False 61691.43 7785.46 -87.4% 259171.00 0.00
ServerSentEventsFormattingBenchmark.WriteMessage LineLength=4096&LineCount=16&Segmented=True 62999.90 7763.59 -87.7% 259170.00 0.00
ServerSentEventsOutputBenchmark.WriteMessage ForceAsync=False 60895.95 8507.34 -86.0% 259171.00 0.00
ServerSentEventsOutputBenchmark.WriteMessage ForceAsync=True 86043.25 25521.90 -70.3% 259474.00 354.00
All 24 reverse-order confirmation results (time in ns)
Benchmark Parameters Before ns After ns Time change Before B/op After B/op
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1&SharedGroup=False 221.40 218.72 -1.2% 290.00 290.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1&SharedGroup=True 222.86 215.10 -3.5% 290.00 290.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1024&SharedGroup=False 8424.06 8080.24 -4.1% 290.00 290.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=1&ConnectionsPerGroup=1024&SharedGroup=True 8258.17 8292.86 +0.4% 290.00 290.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1&SharedGroup=False 163.24 163.65 +0.3% 291.00 291.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1&SharedGroup=True 669.29 662.99 -0.9% 292.00 292.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1024&SharedGroup=False 4017.54 4611.76 +14.8% 291.00 291.00
HubGroupListConcurrencyBenchmark.AddAndRemove Workers=8&ConnectionsPerGroup=1024&SharedGroup=True 10963.75 10547.09 -3.8% 292.00 292.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=False&ProviderLifetime=Scoped 1020.68 1090.44 +6.8% 2576.00 2576.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=False&ProviderLifetime=Singleton 972.63 1018.52 +4.7% 2528.00 2528.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=True&ProviderLifetime=Scoped 1040.10 1192.47 +14.7% 2576.00 2602.00
HubMethodAuthorizationBenchmark.Authorized AllowsCachingPolicies=True&ProviderLifetime=Singleton 959.39 792.92 -17.4% 2528.00 1872.00
SendConnectionsBenchmark.SendAsync Connections=10&TargetConnections=1 333.66 165.10 -50.5% 320.00 256.00
SendConnectionsBenchmark.SendAsync Connections=10&TargetConnections=10 785.52 813.77 +3.6% 320.00 256.00
SendConnectionsBenchmark.SendAsync Connections=10&TargetConnections=2 391.65 221.86 -43.4% 320.00 256.00
SendConnectionsBenchmark.SendAsync Connections=1000&TargetConnections=1 26036.40 166.09 -99.4% 321.00 256.00
SendConnectionsBenchmark.SendAsync Connections=1000&TargetConnections=10 58764.50 807.47 -98.6% 322.00 256.00
SendConnectionsBenchmark.SendAsync Connections=1000&TargetConnections=2 28196.23 228.07 -99.2% 321.00 256.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=DenseNewlines 258454.12 152135.32 -41.1% 131103.00 10.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=Fragmented 68265.78 68091.83 -0.3% 16338.00 2.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=LateNewline 42953.95 8609.75 -80.0% 197261.00 0.00
ServerSentEventsAdverseBenchmark.WriteMessage Scenario=Tiny 117.05 65.97 -43.6% 344.00 0.00
ServerSentEventsOutputBenchmark.WriteMessage ForceAsync=False 47644.88 8700.08 -81.7% 259156.00 0.00
ServerSentEventsOutputBenchmark.WriteMessage ForceAsync=True 78495.42 23565.26 -70.0% 259463.00 335.00

Reproduction

Build once for each production revision while keeping the benchmark sources identical, then run each captured output separately with the same SDK/runtime:

source activate.sh
./src/SignalR/build.sh -c Release --no-restore \
  --projects "$PWD/src/SignalR/perf/Microbenchmarks/Microsoft.AspNetCore.SignalR.Microbenchmarks.csproj" \
  --verbosity quiet

dotnet artifacts/bin/Microsoft.AspNetCore.SignalR.Microbenchmarks/Release/net11.0/Microsoft.AspNetCore.SignalR.Microbenchmarks.dll \
  --config debug \
  --filter '*AdverseBenchmark*' '*ServerSentEventsFormattingBenchmark*' \
           '*ServerSentEventsOutputBenchmark*' '*HubConnectionContextCreationBenchmark*' \
           '*HubMethodAuthorizationBenchmark*' '*SendConnectionsBenchmark*' \
           '*MessageBufferBenchmark*' '*HubGroupList*Benchmark*' \
  --warmupCount 10 --iterationCount 7 --iterationTime 200 \
  --memory --exporters json --artifacts "$PWD/artifacts/benchmark-results"

The repeat filters were *SendConnectionsBenchmark*, *HubMethodAuthorizationBenchmark.Authorized*, *ServerSentEventsAdverseBenchmark*, *ServerSentEventsOutputBenchmark*, and *HubGroupListConcurrencyBenchmark*. Use distinct artifact directories for each run. The baseline commit alone does not contain these new benchmark classes.

Validation

After the final test-only reduction, the focused run covered 321 SignalR server cases (320 passed and 1 skipped) and 34 SSE formatter/transport cases (all passed). Every retained theory row executed successfully. No pre-existing tests, production code, or benchmarks were changed by the reduction.

The added test set now has 13 methods across six files. The latest trim reduced it from 28 methods and 998 added lines to 13 methods and 514 added lines (484 fewer lines, about 49%), following the earlier 97-line reduction. It consolidates targeting and serialization checks, keeps one ACK/append/replay scenario, and removes redundant authorization permutations, GC/concurrency stress scaffolding, and pool-capacity assertions.

Retained regression coverage checks duplicate/missing/case-sensitive recipients and shared serialization on both sides of the 16/17-target boundary; pending writes and existing cancellation behavior; ordered replay after partial/full ACKs and block reuse; policy-cache opt-in, provider/method isolation, mixed metadata, null/failure retries, and authorization with fresh scoped services/resources on every invocation; the handler-level no-allocation path; explicit CR/LF and Unicode framing with contiguous/fragmented input, one exact-length write, and buffer ownership until asynchronous output completes or cancels.

Before these test-only reductions, the shared .NET client multi-target build (net11.0, netstandard2.0, netstandard2.1, and net462), Release microbenchmark build, and authorization benchmark smoke run succeeded with the merged dependencies. Performance measurements were not rerun; all before/after tables and their pre-merge provenance remain unchanged.

No linked issue.

Optimize small targeted sends, stateful reconnect appends, reusable authorization policies, connection cancellation tracking, and multiline SSE formatting. Add focused correctness coverage and normal/adverse microbenchmarks.

Co-authored-by: Copilot App <[email protected]>
Copilot AI lite review requested due to automatic review settings September 10, 2026 06:19
@github-actions github-actions Bot added the area-signalr Includes: SignalR clients and servers label Sep 10, 2026

Copilot AI commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

One or more custom setup steps configured for this repository failed during this Copilot code review run:

Build solution

Setup steps run before each review. If the review above is missing context, or no review was posted at all, the failing step above may be the cause. See the workflow run for failure details, fix your setup steps configuration, and re-request a review.

Note

You can configure setup steps for Copilot code review separately from Copilot cloud agent with a copilot-code-review.yml file. Read the docs for details.

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.

Copilot review overview

🔵 Needs a closer look

It changes multiple high-impact SignalR hot paths (send, reconnect buffering, authorization, SSE) and adds substantial new benchmark/test surface area that warrants careful final human validation.

Review tier: Lite
Findings: 2 Low severity

New issues introduced by this change (2)
Severity Finding
Low severity src/​SignalR/​perf/​Microbenchmarks/​HubMethodAuthorizationBenchmark.cs — Unnecessary using directive: Microsoft.Extensions.DependencyInjection.Extensions isn't referenced…
Low severity src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionHandlerTests.Authorization.cs — Unnecessary using directive: Microsoft.Extensions.DependencyInjection.Extensions isn't referenced…
What changed in this PR

This PR optimizes several SignalR hot paths (targeted connection sends, reconnect buffering, hub-method authorization, cancellation tracking, and SSE formatting) and adds a comprehensive set of regression microbenchmarks and tests to validate correctness and performance characteristics.

Changes:

  • Optimizes DefaultHubLifetimeManager.SendConnectionsAsync for small target lists (≤16) with bounded duplicate suppression and single serialization per protocol.
  • Improves reconnect buffering by tracking the MessageBuffer tail, and reduces per-connection overhead by lazily allocating invocation-cancellation tracking.
  • Reworks SSE message formatting to use pooled contiguous buffers with a single output write, and adds microbenchmarks covering send/reconnect/auth/SSE and group churn scenarios.
File Description
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​Internal/​MessageBufferTests.cs Adds ordering regression coverage across ACK + append cycles for buffered reconnect messages.
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​Internal/​HubMethodDescriptorTests.cs Adds unit tests for composed-authorization policy caching behavior (provider identity/lifetime, failures, concurrency, GC).
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionHandlerTests.Cancellation.cs Validates that “unknown cancellation” and typical invocations don’t allocate cancellation-source tracking.
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionHandlerTests.Authorization.cs Adds functional tests ensuring authorization still uses per-invocation scoped services and resource data; validates no cross-provider caching for scoped/transient.
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​HubConnectionContextTests.cs Adds tests for lazy cancellation dictionary initialization, unknown-cancel behavior, and concurrent first-init publishing.
src/​SignalR/​server/​SignalR/​test/​Microsoft.AspNetCore.SignalR.Tests/​DefaultHubLifetimeManagerTests.cs Adds send-to-connections behavioral tests for dedupe/missing IDs/case sensitivity/serialization sharing/waiting for writes/cancellation interaction.
src/​SignalR/​server/​Core/​src/​Internal/​HubMethodDescriptor.cs Introduces per-provider composed-policy caching via ConditionalWeakTable gated by AllowsCachingPolicies.
src/​SignalR/​server/​Core/​src/​Internal/​DefaultHubDispatcher.cs Uses cached policy composition path; avoids allocating cancellation tracking for unknown cancellation messages.
src/​SignalR/​server/​Core/​src/​HubConnectionContext.cs Lazily initializes active invocation cancellation tracking and adds a non-allocating lookup path.
src/​SignalR/​server/​Core/​src/​DefaultHubLifetimeManager.cs Adds small-target indexed send fast-path with bounded dedupe and shared serialization.
src/​SignalR/​common/​Shared/​MessageBuffer.cs Tracks a tail buffer to avoid traversing retained reconnect backlog on appends; adjusts ACK/resend to use head tracking.
src/​SignalR/​common/​Http.Connections/​src/​ServerSentEventsMessageFormatter.cs Switches multiline SSE formatting to a pooled contiguous buffer with a single write and precise written-length control.
src/​SignalR/​common/​Http.Connections/​test/​ServerSentEventsMessageFormatterTests.cs Adds coverage for newline/CR trimming behavior, single-write multiline behavior, sizing, buffer lifetime across async writes, and failure/cancellation cases.
src/​SignalR/​perf/​Microbenchmarks/​Microsoft.AspNetCore.SignalR.Microbenchmarks.csproj Adds required reference for authorization benchmarks and links SSE formatter source into benchmarks.
src/​SignalR/​perf/​Microbenchmarks/​SendConnectionsBenchmark.cs Adds baseline/regression benchmarks for small/large connection stores with targeted sends.
src/​SignalR/​perf/​Microbenchmarks/​SendConnectionsAdverseBenchmark.cs Adds adverse-input microbenchmarks (dense fanout, duplicates, missing IDs, empty) and preserves original-scan control.
src/​SignalR/​perf/​Microbenchmarks/​MessageBufferBenchmark.cs Adds reconnect-buffer microbenchmarks for append + ack under varying backlog sizes.
src/​SignalR/​perf/​Microbenchmarks/​HubMethodAuthorizationBenchmark.cs Adds dispatcher + authorization benchmarks across provider caching + lifetime combinations.
src/​SignalR/​perf/​Microbenchmarks/​HubConnectionContextCreationBenchmark.cs Adds benchmark for connection creation/cleanup with/without cancellation tracking initialization.
src/​SignalR/​perf/​Microbenchmarks/​HubGroupListBenchmark.cs Adds benchmark for group churn (add/remove) under varying steady-state membership sizes.
src/​SignalR/​perf/​Microbenchmarks/​HubGroupListConcurrencyBenchmark.cs Adds concurrent group churn benchmarks across worker counts and shared vs independent groups.
src/​SignalR/​perf/​Microbenchmarks/​ServerSentEventsFormattingBenchmark.cs Adds SSE formatting microbenchmarks for line count/length and segmented vs contiguous inputs.
src/​SignalR/​perf/​Microbenchmarks/​ServerSentEventsOutputBenchmark.cs Adds SSE output microbenchmark verifying sync vs forced-async output behavior and correctness.
src/​SignalR/​perf/​Microbenchmarks/​ServerSentEventsAdverseBenchmark.cs Adds SSE adverse microbenchmarks for fragmented, dense-newline, and large-message scenarios.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Adapt composed-policy caching to the expanded authorization metadata API. Preserve the no-policy path, cache only non-null results, and cover mixed metadata and uncached null policies.

Co-authored-by: Copilot App <[email protected]>
@davidfowl

Copy link
Copy Markdown
Member Author

Me waiting for a review 🥱

@BrennanConroy BrennanConroy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, testing is a bit overboard, so could pair it down a bit.

Keep boundary, lifetime, and cancellation checks while replacing randomized SSE framing with explicit examples, consolidating output checks, and reducing duplicate test paths and input permutations.

Co-authored-by: Copilot App <[email protected]>
@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 Sep 26, 2026
@davidfowl

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

Keep representative targeting, cache isolation, invocation authorization, lazy tracking, reconnect ordering, and SSE ownership tests. Remove redundant scenario matrices and runtime primitive stress tests.

Co-authored-by: Copilot App <[email protected]>
@davidfowl

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@BrennanConroy

Copy link
Copy Markdown
Member

/ba-g Known test issue with quic, unrelated to PR

@BrennanConroy
BrennanConroy merged commit cfa866b into main Sep 29, 2026
27 of 29 checks passed
@BrennanConroy
BrennanConroy deleted the davidfowl-performance-improvements branch September 29, 2026 17:58
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-signalr Includes: SignalR clients and servers 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.

5 participants