Blog

Sync Npgsql starved ASP.NET Core 10's thread pool for 39 seconds

  • aspnet-core
  • npgsql
  • postgresql
  • dotnet
  • performance
Abstract illustration: a jam of amber request blocks in front of a five-lane gate; four lanes are blocked by parked red workers and only one cyan lane is moving.

We sent 64 concurrent requests to a freshly started ASP.NET Core 10 app whose endpoint calls PostgreSQL through synchronous Npgsql. Each query takes 50 ms. The thread pool needed a median of 38.7 s to grow to 64 threads. During the first 10 seconds the endpoint served 227 requests/s at a p99 of 557 ms. The fully async version of the same endpoint served 1,242 requests/s at 54 ms and never used more than 16 pool threads.

The surprise was the sync-over-async variant (ExecuteScalarAsync().Result). Its pool reached 64 threads about 8× sooner than with plain sync calls (4.6 s vs 38.7 s), but it completed zero requests for the first ~4 s of four out of five runs.

This post is a reproduction in a lab, not a write-up of a production incident. It covers one PostgreSQL-backed minimal API on one 8-vCPU Linux VM, how to read the starvation signature in dotnet-counters, dotnet-stack and the WaitHandleWait trace event, and why the two blocking patterns behave so differently. It doesn’t cover Windows, EF Core, connection-pool exhaustion, or tuning the runtime’s blocking-injection knobs.

Why sync Npgsql calls are worth checking now

The Npgsql 10.0 release notes say the team is “considering to start dropping support for synchronous APIs (NpgsqlConnection.Open, NpgsqlCommand.ExecuteNonQuery, etc.) starting with Npgsql 11.0”. The plan they describe is to throw a runtime exception by default in 11.0, with a switch to re-enable sync I/O, and possibly to remove the APIs completely in 12.0. The tracking issue, npgsql/npgsql#5865, is open with an 11.0.0 milestone. As of today the latest release on NuGet is 10.0.3.

So sync calls inside async ASP.NET Core apps will need to change anyway. The measurements below show the cost of leaving them in place, and they show why rewriting Open() as OpenAsync().Result is not the fix.

The reproduction: three endpoints, one 50 ms query

The app is a .NET 10 minimal API that uses a singleton NpgsqlDataSource with Maximum Pool Size=80. Every endpoint runs SELECT pg_sleep(0.05), so PostgreSQL holds each request for 50 ms while the app’s CPU stays almost idle. The /async endpoint has the same shape with await. A fourth arm runs /sync with ThreadPool.SetMinThreads(100, io) at startup.

// Npgsql 10.0.3, .NET 10.0.14
const string Sql = "SELECT pg_sleep(0.05)";

app.MapGet("/sync", (NpgsqlDataSource db) =>
{
    using var conn = db.OpenConnection();
    using var cmd = new NpgsqlCommand(Sql, conn);
    cmd.ExecuteScalar();               // blocks a pool thread on a socket read
    return "ok";
});

app.MapGet("/sync-over-async", (NpgsqlDataSource db) =>
{
    using var conn = db.OpenConnectionAsync().AsTask().Result;
    using var cmd = new NpgsqlCommand(Sql, conn);
    _ = cmd.ExecuteScalarAsync().Result; // blocks a pool thread on a Task
    return "ok";
});

The load generator is k6 v2.3.0, configured as a closed loop. Each of 64 virtual users sends a request as soon as its previous one returns:

// k6 v2.3.0: k6 run -e ENDPOINT=sync -e VUS=64 -e DURATION=60s load.js
import http from 'k6/http';
export const options = { vus: Number(__ENV.VUS || 64), duration: __ENV.DURATION || '60s',
  discardResponseBodies: true };
export default function () {
  http.get(`http://127.0.0.1:5080/${__ENV.ENDPOINT}`, { timeout: '120s' });
}

With 64 requests always in flight and 50 ms per query, about 64 / 0.05 = 1,280 requests/s is the most any arm can reach.

Environment and methodology

Item Value
Host 8 vCPU Intel Xeon VM, 15 GiB RAM, Debian 13.7, kernel 6.12
Runtime .NET SDK 10.0.402, ASP.NET Core / .NET runtime 10.0.14, Server GC (Web SDK default)
Driver Npgsql 10.0.3 over a Unix domain socket
Database PostgreSQL 18.6, same VM, max_connections = 100
Load k6 v2.3.0, 64 VUs, 60 s per run, loopback HTTP
Diagnostics dotnet-counters, dotnet-stack, dotnet-trace 10.0.750501
  • Cold start every run. Each run starts a fresh app process and warms up the endpoint with one request, so every run begins with the default pool floor of 8 worker threads (one per vCPU, read from ThreadPool.GetMinThreads).
  • Interleaved runs. Five rounds, each running all four arms in turn, so slow drift on the VM affects every arm.
  • Data. Latency percentiles come from k6’s per-request CSV. Thread count and queue length come from dotnet-counters collect at 1 s intervals, using the threadpool-thread-count and threadpool-queue-length EventCounters.
  • Separate diagnostic runs. The stack snapshots and traces come from extra runs that weren’t measured, so the tools don’t distort the numbers.
  • One run excluded. In the first attempt at async run 5, k6 recorded no responses after 11 s and the run stretched to 151 s instead of 60 s. We excluded it and reran it. Every other run is included.

Timeline: sync calls ramp at about 1.5 threads per second

Two-panel chart. Top: thread-pool thread count over 60 s. The sync Npgsql line climbs roughly linearly from 9 to 64 threads at about 38 s. The .Result line passes 64 by about 4 s. The async line stays at 15 or fewer. The SetMinThreads(100) line starts near 68. Bottom: per-second p99 latency on a log scale. Sync starts near 600 ms and falls in steps to about 55 ms after 50 s. .Result has no completions until about 4.5 s, then drops from about 4.5 s to 53 ms. Async and SetMinThreads stay near 53 ms throughout.

Measured on our box: run 3 of each arm (the median-p99 run), 64 VUs, cold start. Thread count is sampled once per second. Latency is the per-second p99 of completed requests.

The sync line is the textbook signature from Microsoft’s thread-pool starvation guide: the thread count climbs slowly and steadily, CPU stays far below 100%, and work queues up. Across the five sync runs:

  • the thread count grew at a median of 1.48 threads/s (range 1.29–1.63), measured between 15 and 60 threads;
  • the pool reached 64 threads after a median of 38.7 s (36.0–41.1 s);
  • the queue length peaked at a median of 49 items;
  • process CPU averaged 1.7% of the machine.

Until the pool has a thread for every in-flight request, each request waits in the queue before it can block on its own socket. Latency falls in steps as threads arrive, and in the last 15 seconds sync reaches parity: 1,257 requests/s at a p99 of 61 ms.

Results: whole run and first 10 seconds

Grouped bar chart. Left: median p50, p95 and p99 latency for the whole 60 s run. All arms have p50 near 51 ms. Sync has p95 of 203 ms and p99 of 355 ms; the other three arms are near 51–53 ms. Right: throughput of 781 requests/s for sync, 1,167 for .Result, 1,257 for async and 1,261 for sync with SetMinThreads(100).

Measured on our box: median of 5 runs per arm. The whiskers show the min and max across runs.

All values are the median across 5 runs, with min..max in brackets. Latencies are in milliseconds.

Arm Requests/s (60 s) p50 p95 p99 Max Peak threads
Sync Npgsql 781 [742..822] 51.0 202.9 354.7 [353.7..355.5] 697 75
.Result 1,167 [1,167..1,170] 50.7 51.5 53.2 [52.6..53.5] 4,494 78
Async 1,257 [1,251..1,259] 50.7 51.5 53.2 [52.5..53.3] 103 15
Sync + SetMinThreads(100) 1,261 [1,259..1,262] 50.6 51.3 52.3 [52.0..53.7] 117 76

The first 10 seconds after a restart are where users notice the difference:

Arm, first 10 s Requests/s p50 p99
Sync Npgsql 227 256.8 557.4 [523.0..656.1]
.Result 697 50.7 187.7 [55.9..1,509.0]
Async 1,242 50.8 53.8 [52.9..54.3]
Sync + SetMinThreads(100) 1,248 50.6 53.5 [52.2..55.3]

The run-to-run spread is small for p99 over the whole run (standard deviation 0.7 ms for sync) and large for .Result in the first 10 seconds (623 ms). The .Result stall at startup varies from run to run, while the steady state is stable.

Root cause: the pool can tell a Task wait from a socket wait

dotnet-stack report taken 10 s into a sync run showed 15 pool threads parked in the same place:

Thread (0x2E58B):
  System.Private.CoreLib!System.Threading.ManualResetEventSlim.Wait(int32,...)
  System.Net.Sockets!System.Net.Sockets.SocketAsyncContext.ReceiveFrom(...)
  Npgsql!Npgsql.Internal.NpgsqlReadBuffer+<<Ensure>g__EnsureLong|54_0>d.MoveNext()
  ...
  Npgsql!Npgsql.NpgsqlCommand+<ExecuteScalar>d__113.MoveNext()
  StarvationLab!Program+<>c.<<Main>$>b__0_0(class Npgsql.NpgsqlDataSource)
  ...
  System.Private.CoreLib!System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()

On Linux, a synchronous socket receive in .NET is a managed wait on a ManualResetEventSlim. The 1.5 s snapshot of the .Result run looks similar, but there were 44 such threads and the wait sits under Task:

  System.Private.CoreLib!System.Threading.Monitor.Wait(class System.Object,int32)
  System.Private.CoreLib!System.Threading.ManualResetEventSlim.Wait(int32,...)
  System.Private.CoreLib!System.Threading.Tasks.Task.SpinThenBlockingWait(int32,...)
  System.Private.CoreLib!System.Threading.Tasks.Task.InternalWaitCore(int32,...)
  System.Private.CoreLib!System.Threading.Tasks.Task.InternalWait(int32,...)
  System.Private.CoreLib!System.Threading.Tasks.Task`1[System.__Canon].GetResultCore(bool)
  StarvationLab!Program+<>c.<<Main>$>b__0_1(class Npgsql.NpgsqlDataSource)

That Task frame explains the difference in ramp-up. Since .NET 6 the pool has blocking-injection settings that add threads quickly when a work item blocks, but the docs say they “take effect only for work items that wait for another task to complete, such as in typical sync-over-async cases”. A thread blocked in Socket.Receive doesn’t qualify, so the pool grows at its normal starvation rate. The starvation guide describes that rate as “1-2 per second”, and we measured 1.48. With .Result the pool grew at a median of 8.3 threads/s.

Illustrative diagram of three rows. Sync Npgsql: the worker is parked in a socket receive for the whole 50 ms. Sync-over-async: the worker is parked in Task.InternalWait. Fully async: no worker is held; the continuation is re-queued when the socket is readable.

Illustrative, not measured: what each pattern does to a pool worker during the query.

The faster ramp doesn’t make .Result cheap. In four of five runs the first response took 4.1–4.3 s to arrive, even though the counters showed about 60 threads and an empty queue by ~3.6 s. We didn’t pin down the cause of that last half second; the counters’ 1 s granularity and alignment are too coarse for it. Once warm, .Result holds 77–84 threads to do the work async does with 14–16.

What the WaitHandleWait trace does and doesn’t tell you

The WaitHandleWait event (.NET 9+) fires when a thread blocks in Task.Result, Monitor.Wait, ManualResetEventSlim.Wait and similar calls. We captured 20 s per arm:

dotnet-trace collect -p $PID --clrevents waithandle --clreventlevel verbose \
  --duration 00:00:00:20

A small TraceEvent 3.2.8 program counted WaitHandleWait/Start events and grouped them by the first frame in our code:

Arm Events in 20 s Attributed to the endpoint lambda
Sync Npgsql 8,088 7,990
.Result 15,756 14,146
Async 107 13

We expected sync Npgsql to be invisible to this event. It isn’t: the Linux socket wait shows up as MonitorWait with ExecuteScalar on the stack. The event finds both blocking patterns. It doesn’t tell you which one the pool compensates for quickly, so the thread-count timeline is still the better clue.

Fixes, from best to worst

  1. Go async end to end. await OpenConnectionAsync() and await ExecuteScalarAsync() reached 1,242 requests/s in the first 10 s with at most 16 threads. Npgsql 11 is also expected to require this.
  2. Raise the pool floor as a stopgap. SetMinThreads(100), or System.Threading.ThreadPool.MinThreads in runtimeconfig.json, matched async on latency in this lab. It still holds about 76 threads, each with its own stack, and the floor has to stay above the peak concurrency of blocking calls. If you guess too low, the slow ramp comes back.
  3. Don’t swap Open() for OpenAsync().Result. It recovered faster here, but it stalled at startup and used five times as many threads as async. It also uses Npgsql’s async I/O, so it hides from the sync-API exception planned for Npgsql 11 while keeping the blocking.

Caveats

  • Everything ran on one shared VM. The app, PostgreSQL, k6 and an unrelated ClickHouse server were all on the same machine, and load average was around 0.4 before the runs.
  • Traffic used loopback HTTP and a Unix socket to PostgreSQL, so there was no network latency. pg_sleep stands in for a slow query.
  • Each run is 60 s from a cold process. Long-running services see this ramp after every deploy or restart, or after a traffic spike beyond the threads they already have.
  • The results depend on core count. The default floor equals the processor count, so a 2-vCPU container starts with even fewer threads.
  • These are pool heuristics in .NET 10.0.14. Microsoft documents their shape, not their exact rates, and the rates can change between releases.

Takeaways

  • A thread count that climbs slowly while CPU sits near idle points to blocking, not to load. Graph the thread count after every restart.
  • The pool compensates quickly only for blocking it can see, which means waits on a Task. Sync socket I/O gets the slow path.
  • WaitHandleWait traces and dotnet-stack show where threads block. They don’t show how fast the runtime will compensate.
  • Grep for .Open(, .ExecuteReader(, .ExecuteScalar(, .ExecuteNonQuery(, .Result and .Wait() in request paths now, before Npgsql 11 does it for you.

The full lab (app, k6 script, run scripts, analysis, charts and the trace counter) is in starvation-lab.zip. Run run_all.sh against a local PostgreSQL 18, then rerun it with your own core count and query latency.