Skip to content

net11.0: explain the higher CPU per request (thread-pool spinning), start the client writer inline - #5078

Merged
marcschier merged 1 commit into
masterfrom
romanett/net11-threadpool-spin
Nov 13, 2026
Merged

marcschier merged 1 commit into
masterfrom
romanett/net11-threadpool-spin

Conversation

@romanett

@romanett romanett commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Why net11.0 costs more CPU per request than net10.0

The net10 → net11 table in #5072 showed equal allocations but +14–68 % CPU per request. The cause is the .NET 11 thread pool, not our code:

  • The .NET 11 LowLevelLifoSemaphore lets an idle worker spin for 1024 units of exponential backoff before blocking (UnfairSemaphoreSpinLimit; .NET 10: 70 iterations). This comes from decompiling CoreLib 10.0.15 against 11.0.0.
  • A worker that is woken for a work item another thread already took also spins its full budget, unless more than ⅔ of the processors are busy (new SpuriousDispatchNoSpinThreshold, 16 on 24 cores).
  • Request/response traffic causes many such spurious wake-ups. The commonest is ThreadPool.UnsafeQueueUserWorkItem(..., preferLocal: true): the issuing thread runs the item itself, but the enqueue still signals a second worker.

Harness evidence (24 logical processors, 20 sessions, medians of 4 rotated rounds; runs with foreign CPU load discarded):

  • Same work, more spinning. Allocations and thread-pool work items per request are identical on net10 and net11. The extra CPU is all user mode; kernel time per request is unchanged.

  • The spin settings remove all of it. With DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0 on net11, compared with net11 defaults:

    • server CPU/request: Read −14 %, Write −40 %;
    • client CPU/request: Read −23 %, Write −58 %, Browse −54 %;
    • throughput: +6 to +9 %, at or above net10.

    UnfairSemaphoreSpinLimit=0x46 gives the same CPU recovery but not the throughput gain. UnfairSemaphoreWakeCooldown=0 has no effect.

  • The new signalling path spins too. EventPipe samples show LowLevelLifoSemaphore.MaybeWakeWaiterSlow at 22 % (client) and 6 % (server) of on-CPU samples on net11. That is the signalling side's CAS loop with backoff.

  • Ruled out. Runtime-async: our assemblies have no runtime-async methods; only CoreLib and Sockets do. GC: counts and allocations are unchanged.

Changes

  • Client channel: SendRequestAsync now starts the channel writer on its own thread once it has released the gate (BeginWriteMessageDeferred + StartWriterInline). Before, it queued the writer with preferLocal: true. The writer still never runs under the gate or SendOrder. The connect-replay path still schedules the writer on the pool. The server writer is unchanged (A1 measured the inline start there as −30 % encrypted on 4 cores).
  • Load harness: server: and client-process: now report userMs and workItems (ThreadPool.CompletedWorkItemCount).
  • Docs: docs/ServerScalability.md gets a new section, Thread-pool spinning on .NET 11, with the two runtime settings and their measured effect.

Paired A/B, this change against the #5072 tip (same harness)

Client CPU µs per request, median of 4 rounds:

Scenario net10 base → change net11 base → change Throughput net11
Read 1 value 36.2 → 37.3 (+3 %) 45.1 → 41.4 (−8 %) +3 %
Write 100 values 116.6 → 101.6 (−13 %) 216 → 175.8 (−19 %) +3 %
Browse 81.4 → 76.6 (−6 %) 147.2 → 127.4 (−13 %) +3 %
Read 100, encrypted 99.9 → 98.2 (−2 %) 116.6 → 109.8 (−6 %) +2 %

Client work items per request go from 3.0 to 2.0. Server CPU is unchanged within noise. This change recovers about a quarter to a third of the client regression; the runtime settings recover the rest.

Tests

  • Opc.Ua.Core.Tests Stack.Transport/Client/Tcp (net10.0): 1295 passed.
  • Opc.Ua.Client.Tests (net11.0): 3839 passed, 2 skipped.
  • Opc.Ua.Core builds for all TFMs with 0 warnings.

Upstream

Reported as dotnet/runtime#137494: on .NET 11.0.0 (Windows x64, 24 logical processors), request/response traffic over loopback with ~20 connections uses 40–85 % more CPU per request than on .NET 10. The cause is the full-budget spin after spurious dispatch when fewer than ⅔ of the processors are busy. Setting SpuriousDispatchNoSpinThreshold=0 removes the extra CPU and raises throughput. That suggests a lower default threshold, or a spin budget that adapts to the recent spurious-wake rate. The MaybeWakeWaiterSlow backoff on the signalling path is also worth a look.

Follow-ups (not in this PR)

  • Client: the response continuation (ManualResetValueTaskSourceCore with RunContinuationsAsynchronously, queued preferLocal from the receive loop) causes the same spurious wake-up. The receive loop could run completed continuations inline when its next socket receive goes pending.
  • Server: start the response writer when the request worker parks, which is when the preferLocal item ran anyway, instead of queuing it.

🤖 Generated with Claude Code

Copilot AI balanced review requested due to automatic review settings November 13, 2026 08:51

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 was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

…read-pool spinning

On .NET 11 the server and client use 15-85 % more CPU per request than on
.NET 10 with identical allocations and thread-pool work items. The extra time
is user-mode spinning of thread-pool workers: the .NET 11 pool spins idle
workers for 1024 backoff units (UnfairSemaphoreSpinLimit, 70 iterations on
.NET 10), also after a wake-up that found no work, unless more than two
thirds of the processors are busy (SpuriousDispatchNoSpinThreshold).

The client queued its channel writer with preferLocal: the requesting thread
ran the item itself when it awaited the response, but the enqueue also woke
a pool worker that found nothing and spun. SendRequestAsync now starts the
writer on its own thread once it released the channel gate. Client work
items per request drop from 3 to 2; client CPU per request on .NET 11
-6 to -19 %, on .NET 10 0 to -13 %, throughput unchanged or +2-3 %.

ServerScalability.md documents the runtime settings that restore the .NET 10
CPU cost; the load harness reports user-mode CPU and thread-pool work items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@romanett

Copy link
Copy Markdown
Contributor Author

@marcschier Your take on this?

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 are reported for the writer-scheduling and diagnostics changes.

No open issues 🎉

Review effort: Balanced

@romanett

Copy link
Copy Markdown
Contributor Author

@marcschier agree with opening an issue against dotnet/runtime?

@marcschier
marcschier enabled auto-merge (squash) November 13, 2026 11:08
@marcschier marcschier added the ready Ready to merge once CI Passes label Nov 13, 2026
@marcschier
marcschier merged commit f1c928f into master Nov 13, 2026
184 checks passed
@github-actions

Copy link
Copy Markdown

Code coverage

✅ Coverage gate passed.

Check Result Threshold
✅ Project line rate 89.20% (493739/553520 lines) >= 70.00%
✅ Project branch rate 79.74% >= 60.00%
✅ Patch coverage 82.93% (34/41 changed lines) >= 60.00% (<= 100 changed lines, advisory)
ℹ️ Baseline delta (advisory) +15.60 pp 73.60% recorded
Uncovered changed lines
  • src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs: 1707, 1708
  • src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs: 478, 479, 480, 2009, 2011

Coverage is above the recorded baseline - consider ratcheting coverage-thresholds.json.

Thresholds live in coverage-thresholds.json. Whole report before exclusions: line 88.53%, branch 79.08%.

@codecov

codecov Bot commented Nov 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.04878% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.60%. Comparing base (70919c3) to head (c1d9d6b).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
...c/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs 73.91% 5 Missing and 1 partial ⚠️
src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs 83.33% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##           master    #5078   +/-   ##
=======================================
  Coverage   83.59%   83.60%           
=======================================
  Files        3780     3780           
  Lines      553499   553520   +21     
  Branches    94437    94442    +5     
=======================================
+ Hits       462723   462765   +42     
+ Misses      59563    59555    -8     
+ Partials    31213    31200   -13     
Flag Coverage Δ
actions 83.60% <78.04%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs 86.48% <83.33%> (-0.19%) ⬇️
...c/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs 69.35% <73.91%> (-0.21%) ⬇️

... and 50 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

romanett added a commit that referenced this pull request Nov 14, 2026
… waits (.NET 11 spurious wake-ups) (#5084)

Follow-up to #5078 (.NET 11 thread-pool spinning after spurious
wake-ups, dotnet/runtime#137494).

## Change

A request waits for its response on a `ManualResetValueTaskSourceCore`
with `RunContinuationsAsynchronously` (the receive loop completes it
under the channel gate). The BCL queues that continuation with
`preferLocal: true`, so either the receive loop's thread runs it once
its next receive goes pending, or a worker that the enqueue woke takes
it. When the loop's thread runs it, the woken worker found no work, and
on .NET 11 it spins up to 1024 backoff units before it blocks.

The receive loop now defers the completion of a response
(`ResponseContinuationDeferral`, a thread-static slot filled in a scope
around the synchronous part of `OnChunkReceivedAsync`) and completes it
on its own thread when one of its waits (write capacity, next receive,
chunk dispatch) goes pending:

- The loop's awaits use an awaiter that **first registers the loop's
continuation** on the pending wait and **then** runs the deferred
continuation inline. The loop no longer depends on the thread at that
point, so a continuation that blocks (for example a synchronous call on
the same channel) cannot stall the receive loop; this is the same
exposure as a pool thread today.
`BlockingContinuationDoesNotStallTheLoopAsync` covers it (it fails when
the two steps are swapped).
- Never under the gate or a lock: completions run after
`OnChunkReceivedAsync` returned.
- A thread holds **at most one** deferred completion. A later response
completes the held one on the pool, as before this change: a
continuation run inline may block until another of its requests
completes, and that one must not wait behind the blocked thread
(`ContinuationBlockingOnTheNextResponseDoesNotDeadlockAsync`).
- A held completion also goes to the pool once the loop dispatched 4
more chunks without its receive going pending, so a channel whose
receives keep completing synchronously does not hold a response back.
- A loop that ends completes the held one on the pool, in a `finally` of
the loop method itself (it runs on the thread that dispatched the last
chunk).
- A loop that resumed inside another loop's dispatch on the same thread
leaves the inline completion to the outer loop, which may hold locks.
- Timeouts, cancellation and `Dispose` still complete the wait directly.

Client thread-pool work items per request: 2 → 1.

## Measurements

**After the review fixes** (one held completion; run 4, medians of 4
rotated rounds, vs #5078 tip):

| Scenario | net11 client CPU/op | net11 throughput | net10 client
CPU/op | net10 throughput |
|---|---|---|---|---|
| Read 1 value | 43.6 → 40.5 (−7 %) | +2 % | 38.7 → 35.7 (−8 %) | +3 % |
| Write 100 | 175.1 → 140.4 (−20 %) | +1 % | 114.9 → 99.4 (−13 %) | +2 %
|
| Browse | 133.1 → 95.2 (−28 %) | +2 % | 79.2 → 70.7 (−11 %) | −2 % |
| Read 100, encrypt | 113.8 → 109.5 (−4 %) | +1 % | 97.3 → 92.0 (−5 %) |
+2 % |
| Read 100, encrypt, 4 cores | 140.2 → 139.4 (−1 %) | 0 % | 113.6 →
105.1 (−7 %) | +1 % |

Client work items per request 2.0 → 1.0 in every case. Earlier runs of
the first version (up to 16 held completions) follow.

Load harness, 24 logical processors, 20 sessions, 12 s + 6 s warm-up,
medians of 4 rotated rounds per side, runs with more than 3 cores of
foreign CPU discarded. Baseline = #5078 branch tip (c1d9d6b). Client
CPU in µs per operation, `usr` = user-mode µs/op, `wi` = thread-pool
work items/op. "4 cores" = `--client-cores 20` (server on the remaining
4 processors, encrypted).

**.NET 11** (run 2 / confirming run 3):

| Scenario | Client CPU/op | Client usr/op | Client wi/op | Throughput |
Server CPU/op |
|---|---|---|---|---|---|
| Read 1 value | 42.4 → 40.3 (−5 %) / 44.2 → 40.8 (−8 %) | −7 % / −10 %
| 2.0 → 1.0 | +1 % / +2 % | +1 % / +3 % |
| Write 100 | 159.8 → 130.9 (−18 %) | −20 % | 2.0 → 1.0 | 0 % | 0 % |
| Browse | 131.3 → 99.8 (−24 %) / 129.6 → 99.3 (−23 %) | −26 % / −27 % |
2.0 → 1.0 | +8 % / +2 % | +1 % / −3 % |
| Read 100, encrypt | 115.2 → 108.2 (−6 %) / 123.6 → 111.6 (−10 %) | −10
% / −6 % | 2.0 → 1.0 | −2 % / +1 % | +4 % / −4 % |
| Read 100, encrypt, 4 cores | 141.5 → 139.3 (−2 %) / 148.2 → 136.4 (−8
%) | +18 % / −7 % | 2.0 → 1.0 | +1 % / +2 % | −2 % / −2 % |

**.NET 10** (run 2):

| Scenario | Client CPU/op | Client wi/op | Throughput |
|---|---|---|---|
| Read 1 value | 37.6 → 34.9 (−7 %) | 2.0 → 1.0 | +1 % |
| Write 100 | 95.3 → 91.4 (−4 %) | 2.0 → 1.0 | +2 % |
| Browse | 76.9 → 68.1 (−11 %) | 2.0 → 1.0 | +1 % |
| Read 100, encrypt | 101.7 → 98.9 (−3 %) | 2.0 → 1.0 | −1 % |
| Read 100, encrypt, 4 cores | 103.2 → 99.2 (−4 %) | 2.0 → 1.0 | −1 % |

The encrypted scenario moves ±5 % between identical builds (A/A spread
in these runs), so −2 %/−1 % there is noise; the confirming .NET 11 run
was +1 %.

## Dropped: server writer started at the worker's park point

The second follow-up of #5078 was implemented and measured, and is
**not** included. `BeginWriteSymmetricMessage` deferred
`ScheduleWriter()` while a request worker ran a request synchronously;
the worker started the deferred writers inline when it found no request
(before the fair queue spins), when a request went asynchronous, when it
handed back its permit (per-request dispatch), or after 1–2 more
requests, and only on threads the pool dispatched it on.

Server work items per request fell by 32–53 %, but .NET 11 server CPU
per request did not follow:

| .NET 11, vs #5078 | Read 1 | Browse | Read 100 encrypt | Read 100
encrypt, 4 cores | Write 100 |
|---|---|---|---|---|---|
| Server CPU/op, bound 2 (run 1 / run 2) | −8 % / −8 % | +11 % / +7 % |
−2 % / −3 % | 0 % | 0 % / +3 % |
| Throughput, bound 2 | −5 % / −5 % | +7 % / +4 % | −2 % / −5 % | +1 % /
+3 % | 0 % / −2 % |
| Server CPU/op / throughput, bound 1 | −7 % / −2 % | 0 % / +1 % | −1 %
/ −1 % | +1 % / +1 % (p99 +73 %) | – |
| Server CPU/op / throughput, park only | −3 % / −5 % | +3 % / −2 % | 0
% / −1 % | 0 % / +1 % | – |

It also raised client CPU per Read by 11–30 % (responses leave later and
in bursts). Write kept 4 work items per request: its responses are sent
after the handler went asynchronous. So the queued writer is not where
the server's .NET 11 spin cost is, and deferring it costs latency and
closed-loop throughput.

## Tests

- New `ResponseContinuationDeferralTests` (deferral in and out of scope,
inline completion, completion on loop exit, one held completion, the
4-chunk bound, blocking continuation vs. loop, continuation blocking on
the next response).
- After the review fixes: Opc.Ua.Core.Tests (Stack.*) 3411 and
Opc.Ua.Client.Tests 3842 passed on net10.0 and net11.0.
- `Opc.Ua.Core.Tests` (Stack.Transport/Server/Client/Tcp/Bindings): 3409
passed on net10.0 and net11.0.
- `Opc.Ua.Client.Tests`: 3839 passed on net10.0 and net11.0.
- `Opc.Ua.Server.Tests`: 11034 passed; 8 failures in
`PhysicalFileSystemProviderConfinementTests` on both runtimes, all
"insufficient privileges" creating symbolic links on the local machine,
unrelated to this change.
- net48 build of Opc.Ua.Core.Tests.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready Ready to merge once CI Passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants