Repository navigation
Description
Description
There's a sharding mechanism in TimerQueue that selects the queue based on the current CPU id
_associatedTimerQueue = TimerQueue.Instances[Thread.GetCurrentProcessorId() % TimerQueue.Instances.Length];This doesn't work as expected when the application is bound to specific cores.
For instance, with 32-core server you may have 4 numa nodes each containing 8 logical cores, where every pair of logical cores is backed by a single physical core. In this case, the cpuset of first numa node may look like this: [0, 1, 2, 3, 16, 17, 18, 19] as Linux enumerates first the physical cores, then their HT counterpart.
This leads to underutilization of the timer queues as we'd only use the first 4 due to modulo.
Reproduction Steps
for (var i = 0; i < 100; i++)
{
Task.Run(() => Task.Delay(10*60*1000 + i));
}
Console.ReadKey();Run it with
taskset -c 0,1,4,5 dotnet ./TimerRepro.dll
Then take a memory dump of the process and find the timer queues:
dotnet-dump ps
dotnet-dump collect -p <pid>
dotnet-dump analyze <dumpfile>
dumpheap -stat
do -mt <timerqueue_mt>
do <timerqueue>
dumparray -details <timerqueue_instances>
You'll observe that queues 0 and 1 are utilized while queues 2 and 3 are empty. Sample output (only interesting part):
MT Field Offset Type VT Attr Value Name
00007f40f009b3b8 4000b2b 30 System.Int64 1 instance 86 <ActiveCount>k__BackingField
00007f40f009b3b8 4000b2b 30 System.Int64 1 instance 14 <ActiveCount>k__BackingField
00007f40f009b3b8 4000b2b 30 System.Int64 1 instance 0 <ActiveCount>k__BackingField
00007f40f009b3b8 4000b2b 30 System.Int64 1 instance 0 <ActiveCount>k__BackingField
Expected behavior
All timer queues are utilized
Actual behavior
Depending on CPU ids only some queues are utilized
Regression?
No response
Known Workarounds
Some options that comes to mind:
- Introduce more complex logic similar to what GC does with affinity ranges: querying the number of CPUs on the machine, then querying the affinity mask, filtering CPUs to available ones and building a dictionary cpuid => TimerQueue
- Always create timerqueues equal to the number of total cores on the machine, even if we won't use all of them
- Not use the CPU id but a thread id or any other sharding key
Configuration
Observed on dotnet 6.0.12 WSL2 Ubuntu and dotnet 5.0.x CentOS 7 but the code is the same in newer versions.
Other information
Are there other places in the runtime where the same sharding is utilized?
Activity
verdie-g commentedon Apr 11, 2023
Hi @stephentoub, I think you might be interested by this. It has become an important issue in some of our services that are using many Task.Delay as a timeout mechanism.
Having as many TimerQueue as cores on the machine looks like a simple fix, however I'm not sure if there is already a way to get the total number of cores on the machine from managed code. I've seen it's already used in native code, in the gc for example. Any idea?
stephentoub commentedon Apr 11, 2023
Are you sure it's related to this issue?
For example, are you canceling your Task.Delays when the thing you're using it to timeout completes? What does your code for creating those tasks look like?
verdie-g commentedon Apr 11, 2023
I was wondering the same because when looking at the contention events in perfview I can only see FireQueue something. So I've compared an instance with the Task.Delay removed and I could see a 40% contention decrease.

All these metrics are collected from event counters.
verdie-g commentedon Apr 11, 2023
By the way, this logic found in Timer
runtime/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs
Line 511 in 17ed091
can also be found here
runtime/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/PoolingAsyncValueTaskMethodBuilderT.cs
Line 359 in 17ed091
runtime/src/libraries/System.Private.CoreLib/src/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs
Line 324 in 17ed091
stephentoub commentedon Apr 11, 2023
That's my point. Timers used for timeouts should rarely be firing. This sounds like more likely to be a bug in your code failing to cancel those tasks.
ezsilmar commentedon Apr 11, 2023
But even if we cancel the timer, it would still take a lock on this path creating contention?
To give a bit more context, in one other application where we have latency constraints (i.e. it's better to answer something in 200ms than waiting for the dependency to answer our http request) many timers are created and destroyed frequently. We observe high spikes in thread pool queue (and latency) every couple of minutes, which we connect with two other observations: 95% of all contention events are in
TimerQueue, and the high number of exceptions (as ~12% of all requests end up cancelled).The affinity issue is one of the mitigations we think of, but we also want to change how we use timeouts in HttpClient to trigger
OperationCancelledExceptionandNetworkExceptionless frequently. Something like this:However this solution creates even more timers so we want to fix contention issue in any case.
stephentoub commentedon Apr 11, 2023
Canceled timers would not be queuing any work items.
This is how Task.Delay should not be used for timeouts.
I'd urge you to fix how you're implementing timeouts before assuming this issue is related. You should also look into using Task.WaitAsync is your goal is to timeout a wait on a Task, as it appears to be.
What OS are you running on? What .NET version? And what evidence do you have that affinity is causing you to use fewer timer queues?
stephentoub commentedon Apr 11, 2023
(I just realized the most recent response was from @ezsilmar... I thought I was responding to @verdie-g. Comments about timeouts still apply, though.)
stephentoub commentedon Apr 11, 2023
The lock is held for much longer when firing than when creating/destroying, and how long it's held is impacted by how many active timers there are.
danmoseley commentedon Apr 11, 2023
Regardless, the modulo scheme will fail to lead to one queue per core, right?
stephentoub commentedon Apr 11, 2023
If you affinitize your process to a subset of cores, you might get partitioned into fewer queues than possibly desired.
ezsilmar commentedon Apr 11, 2023
Ok sorry for causing confusion, I think we are mixing up different issues here, let me try to explain it.
First, there's the original issue about affinity and underutilization of timer queues. I'm sure the issue of underutilization is present because there are reliable reproduction steps that we tested on multiple setups (though only Linux). However, the exact performance impact of this issue is unknown: I'm not sure how to measure it correctly, we probably need a machine without hyperthreading to be fair. What concerns me is that CPU id sharding is widely used as @verdie-g pointed out but the affinity case was not taken into account and should theoretically result in worse performance. Also as I point out in the workarounds, I don't see an easy fix that's why I think it's important to discuss :)
Secondly, there is what led us to the discovery of this underutilization: the issues with some of our apps (we are working at the same company with @verdie-g). I think this is separate issue as our code could be better, and I personally think that in the case I described the exceptions are worse offenders than timer queues. We obviously appreciate any feedback on this but it was not my goal to consume your time with consulting, I just wanted to explain how we ended up here.
We are using Centos 7 and Centos 8 and we are using runtimes 5.0.9 and 6.0.13.
I think we see the thread pool spikes not because we emit more work items but because we get unlucky and have a lock convoy that blocks the thread pool threads. For 8 core container we have 8-9 thread pool threads that looks quite reasonable to me but it also means that any small convoy could lead to a spike, especially as we shard by CPU id and not thread (so more threads won't make things better).
Also on a side note we use numa and HT aware affinity to isolate the containers as we found it to be much more predictable
than using other means like time quotas.
stephentoub commentedon Apr 11, 2023
Thanks. I'm not arguing against the original issue existing; affinitizing can impact whether the full range is utilized.
What I'm suggesting is that it's unlikely to be the actual root cause of your issues. It's true that timers firing and timers being created/destroyed both need to take the lock. However, that doesn't mean they equally contribute to cost and contention. When a timer is created/destroyed, it takes the lock, manipulates just a few references, and releases the lock. In contrast, when a timer fires and takes the lock, worst case while holding the lock it can end up traversing a linked list of all timers in that queue. That means worst case it can be O((N / P) ^ 2), where N is the number of active timers and P is the number of queues they're evenly distributed across, because every one of the N timers firing could iterate through N scheduled timers. There are some mitigations in place to avoid that worst case, but if you have lots of relatively short timers unnecessarily remaining active, you're actively working to defeat those mitigations. Would increasing P help? A little, but with lots of timers firing, and lots of timers created with relatively short durations (eg 200ms as in your example), its impact will be outweighed significantly by N.
Please fix your code to clean up timers that are no longer needed. Then if you still have a problem, we can figure out what's going on. Cleaning up timers includes canceling any Task.Delays you've created for timeouts, and ideally not using Task.Delay for that at all and instead using Task.WaitAsync.
danmoseley commentedon Apr 11, 2023
Should we have a separate issue to discuss fixing that? It seems to me that as far as possible if I affinitize to N cores (in any combination) I expect my app to behave as is the machine has N cores. (Notwithstanding any observable performance dynamics due to eg whether the cores are co located)
stephentoub commentedon Apr 11, 2023
That's what this issue is. I'm not understanding.
ezsilmar commentedon Apr 11, 2023
Agree with @stephentoub there's no need to create a separate issue. We should discuss the ways to fix cpu id sharding here, other things are unrelated to the discussion (only provided as an example why we could be interested in fixing it).
ezsilmar commentedon Apr 11, 2023
Speaking of which, I think that the idea to shard by cpu id is a good thing. The problem is it's not easy to add affinity into the current solution (
cpu_id % cpu_count). Also I agree with @danmoseley the app should usecpu_countqueues even in (maybe edge) case of cpu groups.One way to keep the sharding logic simple is to create the queues by the number of real processors (as seen by the OS). The benefit is we'd always shard correctly (even if the affinity changes mid-process). The drawback is we'd probably waste memory on this, even though most of the things are initialized lazily. I wonder if there's a platform independent way to query the total number of cores in the runtime?
Also do you think setting up a benchmark to test perf impact of this issue would be helpful ?
verdie-g commentedon Sep 22, 2023
Let's take a multi-threaded counter for the benchmark for the sake of simplicity.
This is the architecture of my CPU

When running with
taskset -c 0-7, each processor maps to a single element of the array inThreadCounter64and we can see it's 2.8x faster than withtask -c 0-3,8-11. However this benchmark might be biased because with0-7, 8 physical cores are used and only 4 are used with0-3,8-11.To cope with that let's always use
taskset -c 0-7but change the moduloNow it's 4.8x faster when each processor maps to a single element of the array.
Also with this method we can use all the cores of my processor
Surprisingly it's now only 2x faster.
As @ezsilmar mentioned, a fix would be to introduce a
public static partial class Environment { + /// <summary> + /// Returns the real number of logical cores on the machine, not on the one + /// seen by the process like <see cref="ProcessCount" />. + /// </summary> + public static int PhysicalMachineProcessorCount { get; } }and then replace the
Environment.ProcessCountwithEnvironment.PhysicalMachineProcessorCountin the counter class. The trick here will be to find a name that wouldn't be fixed with the exisitingProcessCount.