Expose opt-in CPU affinity for threadpool workers (`UV_THREADPOOL_AFFINITY`)
TL;DR: Built a synthetic benchmark to isolate what UV_THREADPOOL_AFFINITY-style pinning would actually buy, separate from other scheduling changes. On a Ryzen 9 5900X, across 4 independent runs: naive whole-process pinning -- what taskset -p gives you today -- roughly triples p99 event-loop delay, direct evidence for the "why process-level affinity isn't sufficient" argument below. Selective per-thread pinning helps too, but modestly (4-8%), and part of that comes from sizing the pool down rather than placement itself. Full results and caveats near the bottom.
Motivation
Applications that pair libuv's threadpool with CPU-heavy work elsewhere in the process (native ML inference, DSP, video encoding, BLAS/oneDNN-backed libraries, etc.) can see contention between libuv's threadpool workers and those other threads. When everything is scheduled across the same CPUs, this shows up as increased context switching and latency spikes on the threadpool, even when aggregate CPU utilization doesn't look saturated.
I ran into this building a native Node.js ML inference runtime, where a native library's own thread pool contended with libuv's threadpool at higher concurrency. UV_THREADPOOL_SIZE controls how many threadpool workers exist, but there's currently no way to control where they run relative to other CPU-heavy threads in the same process.
Proposal
An opt-in environment variable, parsed once during threadpool initialization alongside UV_THREADPOOL_SIZE:
UV_THREADPOOL_AFFINITY=0,1Since libuv's threadpool workers are created lazily on first use (guarded by a one-time init on the first uv__work_submit, not at loop startup), parsing this at that same point means zero overhead for loops that never touch the threadpool.
Format: a comma-separated CPU list, optionally with ranges (e.g. 0-3,7), consistent with taskset/numactl conventions. Parseable with a simple tokenizer, no external dependency needed.
Placement semantics: every threadpool worker's affinity mask would be set to the entire specified CPU set (e.g. {0, 1}), leaving intra-set scheduling to the OS rather than pinning individual workers to single static cores. This avoids starvation when UV_THREADPOOL_SIZE exceeds the number of pinned cores and keeps the behavior simple to reason about.
This would build on libuv's existing uv_thread_setaffinity() rather than introduce a new primitive, applying it to the threadpool workers at the point they're created.
Why process-level affinity isn't sufficient
Tools like taskset apply to every thread in the process, including any CPU-heavy threads a consuming application or its native dependencies create outside libuv's control. Pinning the whole process to a CPU range pins those other threads too, which reintroduces the exact contention this is meant to avoid. The same limitation applies to cgroup cpuset-based isolation: cgroups operate at the process/container boundary, and libuv's threadpool and a native addon's own thread pool typically live inside the same process, so there's no cgroup boundary to draw between them.
It's also possible to approximate this from userland today by submitting exactly UV_THREADPOOL_SIZE uv_queue_work jobs at startup, each calling uv_thread_setaffinity(uv_thread_self(), ...) on itself. In practice this is unreliable: there's no guaranteed 1:1 mapping between submitted jobs and live worker threads without additional synchronization, and any real work submitted concurrently during that window can race for a worker slot before it's pinned. The useful abstraction is affinity handled at the point workers are actually created, not approximated from outside.
On cross-platform consistency
Opt-in and platform-limited, similar in shape to UV_USE_IO_URING: a performance path gated behind an environment variable, with existing behavior preserved wherever it doesn't apply. uv_thread_setaffinity() is already documented as unsupported on macOS and non-atomic on Windows, so I'd propose the env var be a documented no-op (or an explicit warning, open to preference) on platforms where the underlying call isn't reliable.
Container/cgroup handling
Where the requested CPU set doesn't fully overlap with the thread's inherited affinity mask (e.g. restricted by a Linux cgroup cpuset), the proposed approach is to read the current mask via sched_getaffinity/pthread_getaffinity_np, take the intersection with the requested set, and fall back to that inherited mask with a warning if the intersection is empty, rather than failing the call outright. This also matters for CI environments with restricted or virtualized CPU topology (e.g. single-vCPU runners); the same intersection-and-fallback logic would let a test requesting an unavailable CPU degrade gracefully rather than fail the build.
Insufficient CPU capacity (e.g. small cloud VMs, or oversized pool/mask mismatch)
Distinct from the quota case above: on environments with very few total CPUs (common on budget cloud/serverless tiers, often 1-2 vCPUs), a requested set can pass the intersection check while providing no real isolation, since the threadpool and any addon-managed threads have nowhere else to go but the same one or two cores. In that situation, pinning is strictly worse than doing nothing: it removes the OS scheduler's freedom to time-slice adaptively, for zero isolation benefit.
A related but distinct case: UV_THREADPOOL_SIZE and UV_THREADPOOL_AFFINITY are independent knobs, so someone can set a large pool (e.g. UV_THREADPOOL_SIZE=16) alongside a narrow mask (e.g. a single CPU). The result, 16 workers time-sliced on one core, is arguably user error, but worth a debug-level log line when the requested worker count exceeds the pinned CPU count, so it's diagnosable rather than a silent performance regression.
Proposed handling for both: after resolving the intersection, compare the result against total available CPU capacity and against UV_THREADPOOL_SIZE; if the pinned set effectively covers all available capacity, or is narrower than the configured pool size, log a warning rather than applying a configuration that's likely to hurt rather than help.
Inheritance by threads created from pool workers
On Linux, a thread inherits the CPU affinity mask of the thread that creates it by default (this mirrors fork()'s documented behavior). libuv's threadpool is commonly used to run native addon code (for example, Node's napi_async_work executes on it), and that code sometimes creates its own threads or lazily initializes its own thread runtime on first use (OpenMP runtimes, for instance, initialize at the first parallel region). Those threads would inherit the pool worker's mask, so the pool's pin would propagate into threads libuv never created and doesn't control, and could squeeze a library that respects its inherited mask into the pool's CPU set.
I don't think libuv can reasonably intercept that, so I'd suggest documenting it rather than trying to solve it: the variable directly affects only the pool workers, code running on them may pass the mask on to threads it creates, and libraries that need a different placement should set it explicitly on their own threads. It also means this feature composes with addon-level affinity settings (OMP_PLACES, KMP_AFFINITY, etc.) only if the deployer configures disjoint CPU sets on both sides; it doesn't coordinate them. Interested in whether documentation is enough here or whether maintainers see a better option.
Relationship to the pluggable threadpool work
I'm aware there's been past interest in a pluggable threadpool API for libuv (#267, a threadpool meta-issue in #1959, and a substantial implementation attempt in #1726), but all of that dates to around 2018 and #1959 is closed and labeled stale, so I don't see evidence of active work in that direction right now. If that effort or something like it does resume, an embedder could eventually reimplement placement however it wants anyway. UV_THREADPOOL_AFFINITY is a small, opt-in addition to the existing threadpool that doesn't touch that direction or compete with it -- it just gives embedders something usable now for the specific placement problem described above. If a pluggable threadpool eventually makes this redundant for some users, that's fine; this isn't meant to be permanent load-bearing API (see the "documented as subject to change" note below).
Scope / open questions
Strictly opt-in. I don't think this should become default behavior, since pinning can hurt general-purpose workloads even where it helps CPU-bound server workloads.
Given the platform and container-interaction questions here, I'd suggest this land initially without a permanent compatibility guarantee (documented as subject to change) rather than settling the final name/format on the first pass.
- What should happen if a requested CPU is outside the process's mask entirely, rather than partially overlapping?
- No-op or warning on platforms where affinity setting is unsupported?
Benchmark results
I built a synthetic benchmark isolating the effect of affinity specifically, separate from application-level scheduling/backpressure changes: a CPU-heavy native addon (N pthreads doing sustained floating-point work, no sleeps, no computation that matters) contending with Node's main thread and libuv threadpool (8 concurrent crypto.pbkdf2 calls) while taskset -p approximates this proposal from outside the process. Full methodology, harness code, and raw output: affinity-bench.
Machine: Ryzen 9 5900X, 12C/24T, two 6-core CCDs each with its own 32MB L3. Linux reports this as a single NUMA node, so the two CPU sets used below are L3 cache domains discovered at runtime (/sys/devices/system/cpu/cpu*/cache/index3/shared_cpu_list), not a NUMA split. 45s per condition, run four times end to end to find out whether single-run numbers were representative or noise.
Delay added above the 10ms monitorEventLoopDelay sampling floor, p99, across all 4 runs (mean ± population stdev):
| Condition | N | Mean | Stdev | Range | vs baseline |
|---|---|---|---|---|---|
| 1. Baseline, no taskset | 24 | 0.97ms | ±0.02ms | 0.94-0.99ms | — |
| 2. Whole process pinned to the Node-set mask (naive) | 24 | 2.96ms | ±0.03ms | 2.94-3.00ms | +204% |
| 3. Selective: Node's threads / addon's threads on separate sets | 24 | 0.90ms | ±0.02ms | 0.88-0.92ms | -8% |
| 4. Addon capped to the addon-set's core count, no pinning | 12 | 0.93ms | ±0.02ms | 0.90-0.96ms | -4% |
| 5. Same as 4, plus selective pinning | 12 | 0.90ms | ±0.02ms | 0.88-0.92ms | -7% (-3% vs cond. 4) |
At n=4, p99 turned out tight: every condition's stdev is about 0.02-0.03ms on means of roughly 1-3ms (2-3% coefficient of variation). That's what makes condition 2 vs 1 the strongest claim here: naively applying taskset -p to the whole process (while the addon still spawns one thread per logical CPU) roughly triples p99 added delay, and did so in all four independent runs with almost no spread (2.94, 2.95, 2.94, 3.00ms). That's real evidence for the "why process-level affinity isn't sufficient" argument above, not just reasoning about it.
Selective pinning alone (3 vs 1) and capping the addon's thread count with no pinning at all (4 vs 1) land in the same modest 4-8% range, consistently. I want to be upfront about that rather than downplay it: on this workload and this machine, a meaningful part of the benefit is attributable to giving Node's threads room to run at all, not to placement specifically. Holding thread count constant, adding selective pinning on top of sizing (5 vs 4) moves p99 by only about 3%.
max is where repetition earned its keep: coefficients of variation of 33-80% on max across the same four runs (versus 2-3% on p99), with condition 4 alone ranging from 3.08ms to 18.85ms added delay across identical runs. That's about as direct as evidence gets that a single-run max isn't something to build a tail-latency claim on. p95/p99 are the metrics I'd trust from this benchmark; max needs many more than four repeated trials before I would, and even then I'd want to report a distribution rather than a single number.
Net: pinning helps, reproducibly, at p99, but modestly (4-8%), and a comparable share of that comes from sizing the addon's pool down rather than from placement itself. The clean, dramatic-looking part of this data is process-wide pinning being bad, not selective pinning being a big win.
Context
This is one half of a two-part proposal. I've also filed a companion issue on nodejs/node proposing affinity for Node's main/event-loop thread specifically, since that thread is created by the embedding application, not by libuv, and so falls outside what libuv itself could offer, including a note on production precedent for the general pattern. Link: nodejs/node#66387.
I'm happy to prototype the Linux implementation if there's interest in the direction.
Source: libuv/libuv