Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/ServerScalability.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Use this guide to size a reference server, limit overload, and configure its run
- [Dynamic GC heap count (DATAS)](#dynamic-gc-heap-count-datas)
- [Hybrid CPUs and processor affinity](#hybrid-cpus-and-processor-affinity)
- [Small Windows machines and thread priority boost](#small-windows-machines-and-thread-priority-boost)
- [Thread-pool spinning on .NET 11](#thread-pool-spinning-on-net-11)
- [JIT warm-up](#jit-warm-up)
- [Verifying the effective configuration](#verifying-the-effective-configuration)
- [Configuration](#configuration)
Expand Down Expand Up @@ -175,6 +176,19 @@ if (OperatingSystem.IsWindows())

`Process.PriorityBoostEnabled` calls the Win32 `SetProcessPriorityBoost` function and applies to the existing and future threads of the process. On other platforms the setter has no effect; on .NET Framework, which runs only on Windows, omit the `OperatingSystem.IsWindows()` check. These measurements cover Windows only.

### Thread-pool spinning on .NET 11

The .NET 11 thread pool lets an idle worker spin much longer before it blocks: the default of the `UnfairSemaphoreSpinLimit` setting changed from 70 spin iterations to 1024 units of exponential backoff. A worker that is woken for a work item that another thread has already taken spins that whole budget, unless more than two thirds of the processors are busy (the new `SpuriousDispatchNoSpinThreshold` setting). Request/response traffic causes many such wake-ups. On 24 logical processors with 20 sessions on loopback, CPU time per request rose by up to 47 % on the server (Write; Read +4–16 %, Browse unchanged) and by 17–85 % on the client compared with .NET 10, while allocations and thread-pool work items per request stayed the same and the extra time was all user-mode spinning. Throughput moved between −10 % (single-value Read) and +5–10 % (Write, Browse).

Two runtime settings bring CPU per request back to the .NET 10 level (medians of 4 rotated rounds per scenario and configuration, Windows, harness scenarios Read 1 value, Write 100 values, Browse):

| Runtime setting (environment variable) | Server CPU/request | Client CPU/request | Throughput |
|---|---|---|---|
| `System.Threading.ThreadPool.SpuriousDispatchNoSpinThreshold` = 0 (`DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0`) | −14 % (Read), −40 % (Write), ±0 (Browse) | −23 %, −58 %, −54 % | +9 %, +6 %, +7 % |
| `System.Threading.ThreadPool.UnfairSemaphoreSpinLimit` = 70 (`DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=46`, hexadecimal) | −13 %, −40 %, −1 % | −18 %, −55 %, −51 % | −1 %, +2 %, +1 % |

The changes are relative to .NET 11 with default settings. `SpuriousDispatchNoSpinThreshold=0` stops the spinning only after a wake-up that found no work, so it also kept the throughput gains of .NET 11. Neither setting is among the documented [threading settings](https://learn.microsoft.com/dotnet/core/runtime-config/threading), and both can change between releases; measure before and after with the [server load harness](../perf/README.md) (`SERVER_DOTNET_ThreadPool_…` for the server child, `DOTNET_ThreadPool_…` for the client). The client channel starts its writer on the requesting thread instead of queuing a work item for it, which removes one of these wake-ups per request on every runtime.

### JIT warm-up

With tiered compilation enabled, .NET initially uses quick-JIT or ReadyToRun code and optimizes frequently called methods in the background. Short measurements can include that transition. With the external open62541 benchmark client of [o6-automation/opcua-benchmarks](https://github.com/o6-automation/opcua-benchmarks) (10 clients with 100 single-value Reads each in flight, server restricted to 4 logical processors), the reported server cost was about 28–31 µs of CPU time per Read in 3-second runs and 8.8 µs at steady state. The single-threaded open62541 result was 8.1 µs on the same machine; with Basic256Sha256 SignAndEncrypt, the recorded costs were 8.8 µs and 12.2 µs respectively.
Expand Down
3 changes: 2 additions & 1 deletion perf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,8 @@ the scenario and all arguments.
| Latency | `client:` percentiles `p50`/`p90`/`p99`; `write->notify latency` (`sub`), `event->notify latency` (`events`) |
| CPU and allocation per operation | `per-op:` `cpuUs`, `allocB` per request or notification; `per-op2:` per written value or generated event |
| GC | `server:` `gen0`/`gen1`/`gen2` collections and `pauseMs` in the window; `client-process:` the same for the client |
| CPU use | `server:` `cpuMs` and `cpuCores` (average busy cores) |
| CPU use | `server:` `cpuMs` and `cpuCores` (average busy cores), `userMs` (user-mode part of `cpuMs`); `client-process:` the same for the client |
| Thread-pool hand-offs | `server:`, `client-process:` `workItems` (`ThreadPool.CompletedWorkItemCount` in the window); divide by the operations for the work items per operation. Thread-pool spinning shows as user-mode CPU that grows without more work items, see [Thread-pool spinning on .NET 11](../docs/ServerScalability.md#thread-pool-spinning-on-net-11) |

### Artifacts

Expand Down
12 changes: 9 additions & 3 deletions perf/ServerLoadHarness/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,9 @@ internal sealed record ProcessStats(
long Timestamp,
int Threads,
long WorkingSet,
long Heap)
long Heap,
TimeSpan UserCpu,
long WorkItems)
{
public static ProcessStats Capture()
{
Expand All @@ -825,7 +827,9 @@ public static ProcessStats Capture()
Stopwatch.GetTimestamp(),
ThreadPool.ThreadCount,
process.WorkingSet64,
GC.GetGCMemoryInfo().HeapSizeBytes);
GC.GetGCMemoryInfo().HeapSizeBytes,
process.UserProcessorTime,
ThreadPool.CompletedWorkItemCount);
}

public string Delta(ProcessStats mark)
Expand All @@ -839,7 +843,9 @@ public string Delta(ProcessStats mark)
FormattableString.Invariant(
$"cpuMs={cpu.TotalMilliseconds:F0} cpuCores={cpu.TotalSeconds / seconds:F2} ") +
FormattableString.Invariant(
$"contention={Contention - mark.Contention} threads={Threads} wsMB={WorkingSet / 1048576} heapMB={Heap / 1048576}");
$"contention={Contention - mark.Contention} threads={Threads} wsMB={WorkingSet / 1048576} heapMB={Heap / 1048576} ") +
FormattableString.Invariant(
$"userMs={(UserCpu - mark.UserCpu).TotalMilliseconds:F0} workItems={WorkItems - mark.WorkItems}");
}
}

Expand Down
68 changes: 64 additions & 4 deletions src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1535,6 +1535,24 @@ protected void BeginWriteMessage(BufferCollection buffers, object? state)
QueueWrite(new PendingWrite(transport, buffers, state));
}

/// <summary>
/// Queues a message like <see cref="BeginWriteMessage(BufferCollection, object)"/> but
/// leaves starting the writer to a caller that holds the gate: it starts the writer
/// with <see cref="StartWriterInline"/> after it released the gate.
/// </summary>
/// <returns>True if the caller must start the writer.</returns>
private protected bool BeginWriteMessageDeferred(BufferCollection buffers, object? state)
{
IUaSCByteTransport? transport = m_transport;
if (transport == null)
{
BeginWriteMessage(buffers, state);
return false;
}
Interlocked.Increment(ref m_activeWriteRequests);
return TryQueueWrite(new PendingWrite(transport, buffers, state));
}

/// <summary>
/// Queues a write so that it runs off the caller's stack but still in
/// the order the caller issued it.
Expand All @@ -1552,6 +1570,21 @@ protected void BeginWriteMessage(BufferCollection buffers, object? state)
/// before it has finished.
/// </remarks>
private void QueueWrite(PendingWrite write)
{
if (TryQueueWrite(write))
{
ScheduleWriter();
}
}

/// <summary>
/// Queues a write like <see cref="QueueWrite"/> but leaves starting the writer to the
/// caller.
/// </summary>
/// <returns>True if the writer is not running and the caller must start it, with
/// <see cref="StartWriterInline"/> once it holds neither the gate nor
/// <see cref="SendOrder"/>, or with <see cref="ScheduleWriter"/>.</returns>
private bool TryQueueWrite(PendingWrite write)
{
long retained = write.RetainedBytes;
lock (m_writeQueueLock)
Expand All @@ -1560,12 +1593,11 @@ private void QueueWrite(PendingWrite write)
Volatile.Write(ref m_queuedWriteBytes, m_queuedWriteBytes + retained);
if (m_writerRunning)
{
return;
return false;
}
m_writerRunning = true;
return true;
}

ScheduleWriter();
}

/// <summary>
Expand Down Expand Up @@ -1653,10 +1685,38 @@ private void ReportWriteQueueOverflow(IUaSCByteTransport transport, long queued)
_ = Task.Run(() => OnTransportError(transport, failure, CancellationToken.None));
}

/// <summary>
/// Starts the writer that <see cref="TryQueueWrite"/> left to the caller on the
/// calling thread. The caller must hold neither the gate (the write completes
/// through <see cref="HandleWriteComplete"/>, which enters it) nor
/// <see cref="SendOrder"/>.
/// </summary>
/// <remarks>
/// A work item queued for the writer wakes a pool worker even when the issuing
/// thread runs the item itself as it returns to the pool. That woken worker finds no
/// work, and since .NET 11 a worker spins much longer before it blocks again
/// (UnfairSemaphoreSpinLimit 70 to 1024), which cost 40 to 70 % more CPU per
/// request. A caller that holds nothing sends on its own thread before it awaits the
/// response, which is where the queued item ran as well.
/// </remarks>
private protected void StartWriterInline()
{
// the pool item did not flow the execution context either
if (ExecutionContext.IsFlowSuppressed())
{
_ = RunWritesAsync();
return;
}
using (ExecutionContext.SuppressFlow())
{
_ = RunWritesAsync();
}
}

/// <summary>
/// Starts the writer on the thread pool.
/// </summary>
private void ScheduleWriter()
private protected void ScheduleWriter()
{
// The execution context is not needed by the write and is not flowed.
// The write goes to the local queue of the issuing thread, which picks
Expand Down
66 changes: 43 additions & 23 deletions src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -449,37 +449,50 @@ public async ValueTask<IServiceResponse> SendRequestAsync(

using Activity? activity = CachedActivitySource.StartActivity();
WriteOperation? operation = null;
bool startWriter = false;

// a request that waits for the gate (another request or a response is being
// processed) must not block its thread: a blocking wait spins first, and with
// many concurrent requests on one channel the spinning took a fifth of the CPU.
using (await Gate.EnterAsync(ct).ConfigureAwait(false))
try
{
// Queue the operation while connecting and it will be played once connected.
if (State == TcpChannelState.Connecting)
{
operation = BeginOperation(timeout, null, null);
QueueConnectOperation(operation, timeout, request);
}
else
using (await Gate.EnterAsync(ct).ConfigureAwait(false))
{
if (State != TcpChannelState.Open)
// Queue the operation while connecting and it will be played once connected.
if (State == TcpChannelState.Connecting)
{
throw new ServiceResultException(StatusCodes.BadConnectionClosed);
operation = BeginOperation(timeout, null, null);
QueueConnectOperation(operation, timeout, request);
}
else
{
if (State != TcpChannelState.Open)
{
throw new ServiceResultException(StatusCodes.BadConnectionClosed);
}

m_logger.UaSCClientLog5(ChannelId);
m_logger.UaSCClientLog5(ChannelId);

if (m_reconnecting)
{
throw ServiceResultException.Create(
StatusCodes.BadRequestInterrupted,
"Attempting to reconnect to the server.");
}
if (m_reconnecting)
{
throw ServiceResultException.Create(
StatusCodes.BadRequestInterrupted,
"Attempting to reconnect to the server.");
}

// send request.
operation = BeginOperation(timeout, null, null);
SendRequest(operation, request);
// send request.
operation = BeginOperation(timeout, null, null);
startWriter = SendRequest(operation, request);
}
}
}
finally
{
// the writer sends on this thread once the gate is released: a queued
// writer would wake a pool worker that finds no work (see StartWriterInline)
if (startWriter)
{
StartWriterInline();
}
}
try
Expand Down Expand Up @@ -1467,10 +1480,13 @@ private void OnHandshakeComplete(IAsyncResult? result)
/// <summary>
/// Sends a request to the server.
/// </summary>
/// <returns>True if the writer must be started (see
/// <see cref="UaSCUaBinaryChannel.BeginWriteMessageDeferred"/>).</returns>
/// <exception cref="ServiceResultException"></exception>
private void SendRequest(WriteOperation operation, IServiceRequest request)
private bool SendRequest(WriteOperation operation, IServiceRequest request)
{
bool success = false;
bool startWriter = false;
BufferCollection? buffers = null;

try
Expand All @@ -1492,7 +1508,7 @@ private void SendRequest(WriteOperation operation, IServiceRequest request)
true,
out bool limitsExceeded);

BeginWriteMessage(buffers, operation);
startWriter = BeginWriteMessageDeferred(buffers, operation);
buffers = null;
success = true;

Expand All @@ -1517,6 +1533,7 @@ private void SendRequest(WriteOperation operation, IServiceRequest request)
OperationCompleted(operation);
}
}
return startWriter;
}

/// <summary>
Expand Down Expand Up @@ -1989,7 +2006,10 @@ private void SendQueuedOperations()

try
{
SendRequest(request.Operation, request.Request);
if (SendRequest(request.Operation, request.Request))
{
ScheduleWriter();
}
}
catch (Exception e)
{
Expand Down
Loading