Diagnosing latency under load from Aspire metrics with an AI agent

 
 
  • Gérald Barré

This post is part of the series 'Debugging .NET with an AI agent'. Be sure to check out the rest of the blog posts of the series!

In the first post about Aspire, the slow request had 203 spans. In the second one, it called another service once per line of a cart. In both cases, the trace of the slow request contained the explanation.

This time it does not. The slow endpoint runs a single query, which takes less than a millisecond, and the request takes 170 ms. The trace shows a gap, and a gap has no attributes. The explanation is in the state of the process, shared by all the requests: that is what metrics measure.

The Aspire dashboard displays metrics, but in Aspire 13.5.4, neither the MCP server nor the aspire command line exposes them. This post adds dotnet-counters to the agent's tools, the same tool as in the thread pool starvation post, and a section to the skill to read its output correctly. Two of the metrics lie in a way that no model can guess.

The sample contains the application and the skill. Every output below comes from it, with the same versions as in the previous posts, plus dotnet-counters 9.0 and 10.0.

#The application

C#
var builder = DistributedApplication.CreateBuilder(args);

var database = builder.AddPostgres("postgres")
    .AddDatabase("inventorydb");

var pricing = builder.AddProject<Projects.PricingApi>("pricing-api")
    .WithHttpHealthCheck("/health");

var inventory = builder.AddProject<Projects.InventoryApi>("inventory-api")
    .WithReference(database)
    .WithReference(pricing)
    .WaitFor(database)
    .WaitFor(pricing)
    .WithHttpHealthCheck("/health");

builder.AddProject<Projects.LoadGenerator>("load-generator")
    .WithReference(inventory)
    .WaitFor(inventory);

builder.Build().Run();

inventory-api has two endpoints:

  • GET /products/{id}/stock returns the stock of a product with one SELECT. The product pages call it.
  • POST /reservations reserves stock for an order. It locks the product row, asks pricing-api for the price, and inserts the reservation.

pricing-api answers in 100 to 200 ms. The load generator runs 20 loops that create reservations, like an order pipeline, and 2 loops that read the stock, like the product pages.

Under this load, the stock endpoint takes 170 ms. The team says the database is slow.

#Step 1: Give the agent metrics

The Aspire dashboard collects the metrics of every resource and draws them. The MCP server has no tool to read them, aspire otel only has logs, spans, and traces, and the telemetry HTTP API of the dashboard, which aspire otel uses, has no metrics endpoint either.

dotnet-counters reads the same metrics directly from the process, through the diagnostics port that every .NET process opens:

Shell
dotnet tool install --global dotnet-counters

The skill gets a new row in its question table, and a new section:

| Is a connection pool saturated?          | `dotnet-counters` with `Npgsql`: `db.client.connection.count` (`used`) vs `db.client.connection.max` |
| How long do requests take, per route?    | `dotnet-counters` with `Microsoft.AspNetCore.Hosting`: `http.server.request.duration` |

Most lines of that section come from the mistakes I made while preparing this post. They are explained below.

#Ask the question

GET /products/{id}/stock on inventory-api takes about 170 ms under load, while the query it runs is trivial.
The application is running under Aspire. Find out why.

#Follow the investigation

##The time is before the query

After list_resources, the agent listed the traces, and opened a slow stock request (URLs removed):

Shell
aspire otel spans --trace-id 0249028c40e541309a35c2054a71deab --apphost AppHost/AppHost.csproj -n 50
11:23:15.615 OK     0.17s load-generator: GET 011ed53
11:23:15.615 OK     0.17s inventory-api: GET /products/{id:int}/stock 51bc12a
11:23:15.783 OK    0.69ms inventory-api: postgresql 9c2da1f

The agent: "The whole 170 ms is before the query: server span starts at 15.615, the 0.69 ms query starts at 15.783."

The database is not slow. Something happens during 168 ms between the start of the request and the start of the query, and nothing in the trace says what. The skill lists the usual suspect:

- Waiting for a pooled connection has no span of its own. It shows as a gap between the start of the server span
  and the start of its first database span. `db.npgsql.connection_id` tells which connection a query used

It is not the only possible explanation. Thread pool starvation produces the same gap, because the continuation of the request waits for a thread. So does a lock in the application code. The trace cannot tell them apart.

##The other route has the same gap

The agent opened a reservation next:

11:23:15.351 OK     0.34s inventory-api: POST /reservations 899fcd8
11:23:15.508 OK    0.58ms inventory-api: postgresql 6297228
11:23:15.508 OK     0.18s inventory-api: GET 089a142
11:23:15.509 OK     0.18s pricing-api: GET /prices/{productId:int} 4b99e1b
11:23:15.693 OK    0.71ms inventory-api: postgresql 25bf920

"Both routes show a ~160 ms gap before their first query. Let me check the connection pool."

##The metrics decide

The agent found the process with dotnet-counters ps, which lists it as InventoryApi, and collected 12 seconds of metrics:

Shell
dotnet-counters collect -p 79871 --counters Microsoft.AspNetCore.Hosting,Npgsql,System.Runtime \
  --format json --refresh-interval 2 --duration 00:00:00:12 -o counters.json

Filtered on connections and the thread pool, every sample says the same thing:

db.client.connection.max ({connection})     [...;Maximum Pool Size=10]                         10
db.client.connection.count ({connection})   [...;Maximum Pool Size=10,...state=used]           10
db.client.connection.count ({connection})   [...;Maximum Pool Size=10,...state=idle]            0
dotnet.thread_pool.queue.length ({work_item} / 2 sec)                                           0

The pool has 10 connections, all of them in use, all the time. The thread pool has nothing waiting. That rules out starvation, and points at the pool: a request that needs a connection waits until another request returns one.

##Who holds the connections

A saturated pool is a symptom too. Either the requests are too many for the pool, or each request keeps its connection too long. The reservation trace has the answer, in an attribute:

POST /reservations          | kind=Server | dur=343 | ts=2026-09-17T15:23:15.351483Z
postgresql                  | kind=Client | dur=1   | ts=2026-09-17T15:23:15.508262Z | conn=100 | q=SELECT stock FROM products WHERE id = $1 FOR UPDATE
GET /prices/{productId:int} | kind=Server | dur=184 | ts=2026-09-17T15:23:15.509222Z
postgresql                  | kind=Client | dur=1   | ts=2026-09-17T15:23:15.693123Z | conn=100 | q=WITH updated AS (UPDATE products SET stock = stock - $1 WHERE id = $2) ...

Both queries run on connection 100, and the 184 ms call to pricing-api happens between them. The connection is busy for 185 ms, and it runs 2 ms of SQL.

One trace is an example. The agent then exported 3,000 spans and computed the same numbers for every trace, with jq:

stock traces: 84  median total: 178ms  median pre-query gap: 177ms  median query: 1ms  max gap: 428ms

reservation traces: 462  median total: 321ms  median pricing call: 150ms
median span between 1st and last query on the held connection: 155ms
all-queries-on-one-connection: 462/462

This took three attempts. The first one used aspire otel spans --resource inventory-api, an option that does not exist: the command printed its help on standard output, and jq failed on it. The second one parsed the timestamps with strptime, which does not accept fractional seconds. The third one split the timestamps by hand.

##The code

C#
app.MapPost("/reservations", async (ReservationRequest request, NpgsqlDataSource dataSource, PricingClient pricing) =>
{
    await using var connection = await dataSource.OpenConnectionAsync();
    await using var transaction = await connection.BeginTransactionAsync();

    await using (var command = new NpgsqlCommand("SELECT stock FROM products WHERE id = $1 FOR UPDATE", connection, transaction))
    {
        command.Parameters.Add(new NpgsqlParameter { Value = request.ProductId });
        if (await command.ExecuteScalarAsync() is not int stock || stock < request.Quantity)
            return Results.Conflict();
    }

    var price = await pricing.GetPriceAsync(request.ProductId, request.Quantity);

    // UPDATE the stock and INSERT the reservation, then commit
    ...
});

The pool size is set at startup, with a comment:

C#
// The database server accepts 100 connections, shared by the 10 instances of the service
builder.AddNpgsqlDataSource("inventorydb", configureDataSourceBuilder: dataSource => dataSource.ConnectionStringBuilder.MaxPoolSize = 10);

##The report

Root cause: InventoryApi/Program.cs:22-49, the /reservations handler. The connection and transaction are
opened at lines 24-25, and await pricing.GetPriceAsync(...) at line 34 runs inside them. With
MaxPoolSize = 10 (line 7), ten concurrent reservations consume the entire pool for the duration of the
pricing call. /products/{id}/stock is an innocent bystander: its query is 1 ms, but it queues ~177 ms for a
connection.

Fix: Fetch the price before touching the database, so the connection is held only for the two queries.

Confidence: High. The pre-query gap, the pinned 10/10 pool with an empty thread-pool queue, and the single
connection id spanning the pricing call in 462/462 traces all agree.

21 turns, about two and a half minutes. The report also mentions a trade-off: with the price fetched first, a reservation that fails for lack of stock still calls pricing-api.

It did not propose to increase MaxPoolSize, which is the answer most people give to a saturated pool. Rule 7 of the skill forbids "more resources for a problem the code creates", and the comment says why it matters here: 10 instances with 20 connections each is twice what the database accepts. A bigger pool moves the queue from the application to the database.

#The fix

C#
 app.MapPost("/reservations", async (ReservationRequest request, NpgsqlDataSource dataSource, PricingClient pricing) =>
 {
    var price = await pricing.GetPriceAsync(request.ProductId, request.Quantity);

     await using var connection = await dataSource.OpenConnectionAsync();
     await using var transaction = await connection.BeginTransactionAsync();

     await using (var command = new NpgsqlCommand("SELECT stock FROM products WHERE id = $1 FOR UPDATE", connection, transaction))
     {
         command.Parameters.Add(new NpgsqlParameter { Value = request.ProductId });
         if (await command.ExecuteScalarAsync() is not int stock || stock < request.Quantity)
             return Results.Conflict();
     }

    var price = await pricing.GetPriceAsync(request.ProductId, request.Quantity);

The same change also shortens the FOR UPDATE lock: two reservations of the same product no longer wait for each other during a pricing call.

After aspire resource inventory-api rebuild, with the same load, 10 seconds of dotnet-counters, before and after:

MetricBeforeAfter
/products/{id}/stock, p50169 – 175 ms0.75 – 0.84 ms
/products/{id}/stock, p95194 – 208 ms0.89 – 1.09 ms
/reservations, p50298 – 315 ms147 – 157 ms
/reservations, p95362 – 391 ms195 – 199 ms
Connections used / idle10 / 00 – 2 / 3 – 5

The stock endpoint is 200 times faster, and reservations are twice as fast, now that they no longer wait for a connection. During those 10 seconds, the pool never opened more than 5 connections.

#Metrics that lie

These are the mistakes behind the new section of the skill. The agent did not make them during this investigation, because the skill warned it. I made all of them while preparing the sample.

##The process id is not the process

list_resources and aspire describe return an executable.pid for every project. For inventory-api, it was 75753. dotnet-counters collect -p 75753 ran for 10 seconds, without error, and wrote this file:

JSON
{ "TargetProcess": "dotnet", "StartTime": "2026-09-17T11:18:28.2395110-04:00", "Events": ]}

No events, and not even valid JSON. Process 75753 is dotnet run --project .../InventoryApi.csproj --no-build, the command that Aspire uses to start the project. The application is its child process, and dotnet-counters ps lists it under the name of the project. -n InventoryApi selects it by name.

##Active requests: 0

With about 22 requests in flight at all times, dotnet-counters reported this, every 2 seconds, with version 9 and version 10:

http.server.active_requests ({request})|http.request.method=GET,url.scheme=http:  0 0 0 0 0
http.server.active_requests ({request})|http.request.method=POST,url.scheme=http: 0 0 0 0 0
db.client.connection.npgsql.pending_requests ({request}):                         0 0 -1 0 0

http.server.active_requests is an UpDownCounter: the application adds 1 when a request starts, and subtracts 1 when it ends. dotnet-counters only sees the changes that happen after it connects. The 22 requests already running when it connected end without having been counted, and their replacements start. Under a steady load, the sum stays around 0, and it can even be negative, like the -1 above.

db.client.connection.count is not affected: Npgsql creates it with CreateObservableUpDownCounter, so its value is read from the pool at each interval. pending_requests is a plain UpDownCounter.

A model reading "pending requests: 0" concludes that nothing waits for a connection, which is the opposite of the truth here. The skill says:

- `http.server.active_requests` and `db.client.connection.npgsql.pending_requests` only count the changes that
  happen while `dotnet-counters` listens. Under a steady load they stay around 0, and can even be negative. Never
  read them as "nothing is waiting". `db.client.connection.count` and `db.client.connection.max` are exact

The Aspire dashboard does not have this problem, because it receives the metrics from the start of the process.

##The exception is not in the table

The first version of the sample had a bug in its SQL, and every reservation failed. aspire otel logs --severity Error printed:

11:19:12.223 FAIL inventory-api An unhandled exception has occurred while executing the request.

That is all the table output shows. The JSON output has an exception field with the message, 42601: cannot insert multiple commands into a prepared statement, and the stack trace. An agent that only reads tables reports "an unhandled exception" and nothing more.

#Telemetry contains secrets, again

  • aspire describe --format Json prints the environment variables of each resource with their values, including ConnectionStrings__inventorydb and its password. list_resources, the MCP tool, only prints the names. The skill tells the agent to use the MCP tool for that.
  • Every Npgsql metric has a db.client.connection.pool.name tag, which is the connection string without the password: host, port, user name, and database.
  • dotnet-counters can read any .NET process that runs as the same user. Giving it to an agent means giving it access to those processes' metrics, not only to the application.

#What the agent gets wrong, and how to fix it

It invents command options. aspire otel spans --resource inventory-api looks right. The resource is a positional argument, and the command answered with its help text, on standard output.

Fix: the question table shows the exact syntax, and the agent recovered after reading the output. Checking --help first costs one call.

It stops at the pool. "The pool is full" is not a root cause, and "increase the pool size" is the answer every blog post gives.

Fix: rule 7, and the db.npgsql.connection_id line, which lets the agent find what holds a connection.

It confuses the gap with thread pool starvation. Both look the same in a trace.

Fix: collect System.Runtime with Npgsql. An empty thread pool queue and a full connection pool point one way, the opposite points the other way, and the starvation post takes it from there.

It trusts the metrics that lie. The process id, active_requests, and the table output of the logs are described above.

Fix: the Reading metrics section of the skill. The agent avoided all three here.

Three investigations, three kinds of evidence: the spans of one request, the logs of one request, and the state of a process under load. The Aspire MCP server provided less of it than I expected, and the aspire command line and dotnet-counters filled the gaps. The skill that makes it work is the same kind of file as in the first post of this series: a list of commands, and a growing list of the ways their output can mislead.

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?