Skip to content

Underutilization of TimerQueue when application runs with CPU affinity #83890

Open

Description

@ezsilmar

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

  1. ghost added
    needs-area-label
    on Mar 24, 2023
  2. ghost added
    untriaged
    on Mar 24, 2023
  3. removed
    needs-area-label
    on Mar 24, 2023
  4. verdie-g commented on Apr 11, 2023

    @verdie-g
    Contributor

    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?

  5. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    It has become an important issue in some of our services that are using many Task.Delay as a timeout mechanism.

    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?

  6. verdie-g commented on Apr 11, 2023

    @verdie-g
    Contributor

    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.
    image
    All these metrics are collected from event counters.

  7. verdie-g commented on Apr 11, 2023

    @verdie-g
    Contributor

    By the way, this logic found in Timer

    _associatedTimerQueue = TimerQueue.Instances[Thread.GetCurrentProcessorId() % TimerQueue.Instances.Length];

    can also be found here
    int i = (int)((uint)Thread.GetCurrentProcessorId() % (uint)Environment.ProcessorCount);

    int index = (int)((uint)Thread.GetCurrentProcessorId() % (uint)s_lockedStackCount); // mod by constant in tier 1

  8. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    I can only see FireQueue something

    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.

  9. ezsilmar commented on Apr 11, 2023

    @ezsilmar
    ContributorAuthor

    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 OperationCancelledException and NetworkException less frequently. Something like this:

    using (var cts = new CancellationTokenSource())
    {
      cts.CancelAfter(TimeSpan.FromSeconds(5)); // set large timeout here
      
      var realTimeoutTask = Task.Delay(200); // the timeout we actually use
      var responseTask = httpClient.SendAsync(request, cts.Token);
       
      await Task.WhenAny(realTimeoutTask, responseTask);
    
      if (!responseTask.IsCompleted)
      {
        responseTask.ContinueWith(x => { ... }); // read the body to be able to reuse http connection
        return GetTimeoutResult();
      }
    }

    However this solution creates even more timers so we want to fix contention issue in any case.

  10. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    We observe high spikes in thread pool queue (and latency) every couple of minutes

    Canceled timers would not be queuing any work items.

    var realTimeoutTask = Task.Delay(200);

    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?

  11. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    (I just realized the most recent response was from @ezsilmar... I thought I was responding to @verdie-g. Comments about timeouts still apply, though.)

  12. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    But even if we cancel the timer, it would still take a lock on this path creating contention

    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.

  13. danmoseley commented on Apr 11, 2023

    @danmoseley
    Contributor

    Regardless, the modulo scheme will fail to lead to one queue per core, right?

  14. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    Regardless, the modulo scheme will fail to lead to one queue per core, right?

    If you affinitize your process to a subset of cores, you might get partitioned into fewer queues than possibly desired.

  15. ezsilmar commented on Apr 11, 2023

    @ezsilmar
    ContributorAuthor

    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.

    What OS are you running on? What .NET version?

    We are using Centos 7 and Centos 8 and we are using runtimes 5.0.9 and 6.0.13.

    Canceled timers would not be queuing any work items.

    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.

  16. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    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.

  17. danmoseley commented on Apr 11, 2023

    @danmoseley
    Contributor

    If you affinitize your process to a subset of cores, you might get partitioned into fewer queues than possibly desired.

    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)

  18. stephentoub commented on Apr 11, 2023

    @stephentoub
    Member

    Should we have a separate issue to discuss fixing that?

    That's what this issue is. I'm not understanding.

  19. ezsilmar commented on Apr 11, 2023

    @ezsilmar
    ContributorAuthor

    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).

  20. ezsilmar commented on Apr 11, 2023

    @ezsilmar
    ContributorAuthor

    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 use cpu_count queues 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 ?

  21. removed
    untriaged
    on Jul 24, 2023
  22. added this to the Future milestone on Jul 24, 2023
  23. verdie-g commented on Sep 22, 2023

    @verdie-g
    Contributor

    Let's take a multi-threaded counter for the benchmark for the sake of simplicity.

    // From https://gist.github.com/EgorBo/427f8332b027f4023c0d125b6d5ace5a
    class ThreadCounter64
    {
        private readonly PaddedLong[] _values = new PaddedLong[Environment.ProcessorCount];
    
        public void Increment() =>
            Interlocked.Increment(ref _values[Thread.GetCurrentProcessorId() % Environment.ProcessorCount].Value);
        
        /// <summary>To avoid false sharing.</summary>
        [StructLayout(LayoutKind.Explicit, Size = 64)]
        private struct PaddedLong
        {
            [FieldOffset(0)]
            public long Value;
        }
    }
    
    public class Benchmark
    {
        private const int Iterations = 10_000_000;
        
        [Benchmark(OperationsPerInvoke = Iterations)]
        public void ThreadCounter64Increment()
        {
            ThreadCounter64 counter = new();
            
            Barrier b = new(Environment.ProcessorCount);
            Parallel.For(0, b.ParticipantCount, _ =>
            {
                b.SignalAndWait();
    
                for (int i = 0; i < Iterations; i += 1)
                {
                    counter.Increment();
                }
            });
        }
    }

    This is the architecture of my CPU
    Screenshot from 2023-09-22 13-59-02

    BenchmarkDotNet v0.13.8, Pop!_OS 22.04 LTS
    AMD Ryzen 7 5800X, 1 CPU, 16 logical and 8 physical cores
    
    
    .NET SDK 7.0.401
      [Host]     : .NET 7.0.11 (7.0.1123.42427), X64 RyuJIT AVX2
      DefaultJob : .NET 7.0.11 (7.0.1123.42427), X64 RyuJIT AVX2
    
    Method Mean Error StdDev
    taskset -c 0-7 13.66 ns 0.255 ns 0.251 ns
    Method Mean Error StdDev
    taskset -c 0-3,8-11 38.26 ns 0.764 ns 1.277 ns

    When running with taskset -c 0-7, each processor maps to a single element of the array in ThreadCounter64 and we can see it's 2.8x faster than with task -c 0-3,8-11. However this benchmark might be biased because with 0-7, 8 physical cores are used and only 4 are used with 0-3,8-11.

    To cope with that let's always use taskset -c 0-7 but change the modulo

    +    private readonly int _modulo = int.Parse(Environment.GetEnvironmentVariable("MODULO")!);
    +
        public void Increment() =>
    -        Interlocked.Increment(ref _values[Thread.GetCurrentProcessorId() % Environment.ProcessorCount].Value);
    +        Interlocked.Increment(ref _values[Thread.GetCurrentProcessorId() % _modulo].Value);
    Method Mean Error StdDev Median
    MODULO=8 taskset -c 0-7 17.64 ns 0.489 ns 1.441 ns 18.17 ns
    Method Mean Error StdDev Median
    MODULO=4 taskset -c 0-7 84.67 ns 3.064 ns 9.033 ns 88.45 ns

    Now 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

    Method Mean Error StdDev
    MODULO=16 taskset -c 0-15 21.56 ns 0.420 ns 0.449 ns
    Method Mean Error StdDev
    MODULO=8 taskset -c 0-15 43.21 ns 0.860 ns 2.204 ns

    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.ProcessCount with Environment.PhysicalMachineProcessorCount in the counter class. The trick here will be to find a name that wouldn't be fixed with the exisiting ProcessCount.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions