Finding slow requests with Aspire and 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!

The previous posts in this series answered questions about one process at one moment: why it crashed, what it waits for, what holds its memory. "Which requests are slow?" is a different kind of question. The answer is spread over time and often over several processes, and no dump contains it.

Distributed traces do. If your application runs under Aspire, every service already sends its traces, logs, and metrics to the Aspire dashboard. This post gives that data to an AI agent, through the Aspire MCP server and the aspire command line, and follows the agent as it finds a slow endpoint.

The agent needs one thing the MCP server does not provide, and that gap is the most useful part of this post.

The sample contains the application, the MCP configuration, and the skill.

#The application with a slow page

The sample is an Aspire application with three resources:

  • postgres, a PostgreSQL container with 500 customers and 5,000 orders,
  • orders-api, an ASP.NET Core API that uses Entity Framework Core,
  • load-generator, a worker that calls the API 4 times per second, like the users of a back-office application.
C#
var builder = DistributedApplication.CreateBuilder(args);

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

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

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

builder.Build().Run();

The API has three endpoints: an order by id, the orders of a customer, and the 100 most recent orders for the home page. The service defaults project configures OpenTelemetry, and the Aspire PostgreSQL integration adds a span for every SQL command. There is nothing else to set up to get the telemetry.

One endpoint is slow. As in the previous posts, you could find it by reading the code, since the whole API is 60 lines. Pretend you cannot: the API has 200 endpoints, and the only thing you know is that some pages feel slow.

#Step 1: Install the Aspire CLI

The Aspire CLI starts the application, and it contains the MCP server:

Shell
dotnet tool install --global Aspire.Cli

The application also needs Docker (or Podman) for the PostgreSQL container. Start it in the background from the sample folder:

Shell
aspire start

aspire start returns once the AppHost runs and prints the dashboard URL. aspire run does the same in the foreground.

#Step 2: Register the MCP server

aspire agent mcp starts an MCP server that talks to the running AppHost. For Claude Code, a .mcp.json file at the root of the sample declares it:

JSON
{
  "mcpServers": {
    "aspire": {
      "command": "aspire",
      "args": ["agent", "mcp"]
    }
  }
}

This is the file that aspire agent init writes when you select Install Aspire MCP server, and claude mcp add --scope project aspire -- aspire agent mcp writes an equivalent entry. The server finds the AppHosts that run under the current folder, so the agent must start in the folder of the application.

The server exposes these tools for a running application:

ToolWhat it returns
list_resourcesThe resources, their state, health, endpoints, commands, and process ids
list_tracesRecent distributed traces, with their spans and attributes
list_trace_structured_logsThe logs written during one trace
list_structured_logsRecent logs of a resource, with a full-text search
list_console_logsThe standard output of a resource
execute_resource_commandRuns start, stop, restart or rebuild on a resource

It also has tools to search the Aspire documentation, list integrations, and diagnose the environment. There is no tool for metrics. The third post deals with that.

#The MCP server cannot see the slow request

The obvious first call is list_traces on the API:

list_traces(resourceName: "orders-api")

Returned latest 2 traces. Earlier 115 traces not returned because of size limits.

Two traces out of 117, both for fast requests. The tool returns the most recent traces that fit in its response, and it has no parameter to sort by duration. Searching for the route does not help either:

list_traces(resourceName: "orders-api", search: "/orders/recent")

Returned latest 0 traces. Earlier 21 traces not returned because of size limits.

Zero. There are 21 traces for that route, and each of them is too big to fit on its own. The slow request is invisible through this tool precisely because it is slow: it does a lot of work, so its trace has a lot of spans.

An agent that trusts this output concludes that nothing is slow. The Aspire CLI reads the same data, and prints one line per trace:

Shell
aspire otel traces orders-api -n 200
│ Timestamp    │ Name                                    │ Spans │ Duration │ Status │
│ 11:07:44.540 │ orders-api-wwtezmxd: postgresql bb3dfef │ 203   │ 82.38ms  │ OK     │
│ 11:07:44.790 │ orders-api-wwtezmxd: postgresql bb4187c │ 3     │ 2.16ms   │ OK     │
│ 11:07:48.541 │ orders-api-wwtezmxd: postgresql c5c97e8 │ 203   │ 0.11s    │ OK     │

aspire otel spans --trace-id <id> lists the spans of one trace, and --format Json includes their attributes. So the agent gets both: the MCP server for the resources and the logs, and the CLI for traces. The skill tells it which one to use for what. The Aspire documentation goes further in the same direction: it presents the CLI and the Aspire skills as the main way for an agent to read this data, and the MCP server as optional.

#Step 3: Write the skill

The skill lives in .claude/skills/investigating-aspire-telemetry/SKILL.md. Its description names what someone types when they need it:

Markdown
---
name: investigating-aspire-telemetry
description: Investigate a slow or failing .NET application running under Aspire from its traces, structured logs and console logs, through the aspire MCP tools and the aspire CLI. Use when asked why an endpoint, a request or a service is slow, which call takes the time, or what a running Aspire application is doing.
---

The question table mixes both tools:

| Question                                 | Tool or command                                                                     |
| ---------------------------------------- | ----------------------------------------------------------------------------------- |
| What is running, is it healthy?          | `list_resources`                                                                    |
| Which requests are slow?                 | `aspire otel traces <resource> -n 200`, compare the `Duration` and `Spans` columns  |
| What does one request do?                | `aspire otel spans --trace-id <id> -n 500 --format Json`                            |
| What did the code log for this request?  | `list_trace_structured_logs` with the trace id                                      |
| Is there an error?                       | `list_structured_logs` with `search`, `aspire otel traces <resource> --has-error`   |
| Why does a resource not start?           | `list_console_logs`                                                                 |

The Known limits section starts with the size limit above, and the rules follow the same pattern as the other skills in this series: quote the output, never invent a value, and do not read the source before the telemetry points to it. One rule is new:

3. Compare the slow requests with fast requests of another route before concluding. A slow request is only
   meaningful next to what normal looks like

#Step 4: Ask the question

With the application running, from the sample folder:

Some requests to orders-api are slow, most are fast. The application is running under Aspire.
Find which requests are slow and why.

"Slow", "requests" and "Aspire" match the description, so the agent loads the skill.

#Step 5: Follow the investigation

##Check the application

The agent calls list_resources first. All the resources are Running and Healthy, and the API listens on http://localhost:5358. The output is long: 13 KB for seven resources, because it also lists the dashboard and the hidden helpers that rebuild projects, with every environment variable name and every command.

##Find the slow requests

Shell
aspire otel traces orders-api -n 200

The table has two populations and nothing in between (the trace URLs are removed from every table in this post):

│ 11:07:44.540 │ orders-api-wwtezmxd: postgresql bb3dfef │ 203   │ 82.38ms  │ OK     │
│ 11:07:48.541 │ orders-api-wwtezmxd: postgresql c5c97e8 │ 203   │ 0.11s    │ OK     │
│ 11:07:50.040 │ orders-api-wwtezmxd: postgresql 6b957fe │ 203   │ 87.03ms  │ OK     │
│ 11:07:54.540 │ orders-api-wwtezmxd: postgresql 592757c │ 3     │ 1.91ms   │ OK     │
│ 11:07:54.790 │ orders-api-wwtezmxd: postgresql 7492761 │ 3     │ 2.52ms   │ OK     │

Traces with 3 spans take about 2 ms. Traces with 203 spans take 80 to 110 ms. The Name column does not help: it says postgresql for both, not the route. The route is an attribute of the server span, so the agent opened a trace.

##Read one slow trace

This is the one place where the agent stumbled. Its first attempt piped the JSON output into jq, which failed:

jq: parse error: Invalid numeric literal at line 1, column 9

aspire otel prints Scanning for running AppHosts... on standard output before the JSON. The agent looked at the raw output, added tail -n +2, and grouped the 203 spans by name, route, and SQL text:

Shell
aspire otel spans --trace-id bb3dfefb8d512bfd3eff7bc03c5b035d -n 500 --format Json \
  | tail -n +2 \
  | jq -r 'length as $t | "TOTAL SPANS: \($t)", ([.[] | {n: .name, k: .kind, q: ((.attributes["db.query.text"]) // ""), r: ((.attributes["http.route"]) // ""), d: .durationMs}]
      | group_by(.n + "|" + .q + "|" + .r)
      | map({e: .[0], count: length, sum: (map(.d)|add)})
      | .[] | "\(.count) x [\(.e.k)] \(.e.n) route=\(.e.r) totalMs=\(.sum) q=\(.e.q | gsub("\n";" "))")'
TOTAL SPANS: 203
1 x [Server] GET /orders/recent route=/orders/recent totalMs=82 q=
1 x [Client] GET route= totalMs=82 q=
100 x [Client] postgresql route= totalMs=13 q=SELECT COALESCE(sum(o."Quantity"::numeric * o."UnitPrice"), 0.0) FROM "OrderLines" AS o WHERE o."OrderId" = @order_Id
100 x [Client] postgresql route= totalMs=6 q=SELECT c."Id", c."Name" FROM "Customers" AS c WHERE c."Id" = @order_CustomerId LIMIT 1
1 x [Client] postgresql route= totalMs=2 q=SELECT o."Id", o."CreatedAt", o."CustomerId" FROM "Orders" AS o ORDER BY o."CreatedAt" DESC LIMIT @p

This is the whole diagnosis in six lines. GET /orders/recent runs one query to load the orders, then two queries per order: one for the customer, one for the total. 1 + 100 + 100 = 201 queries.

Grouping before reading is the same habit as parallelstacks in the starvation post: 203 spans of JSON become five lines, and the counts are what matter.

##Compare with a fast request

Following rule 3, the agent opened a fast trace:

[Client] GET                         dur=2ms
[Server] GET /orders/{id:int}        dur=2ms
[Client] postgresql                  dur=1ms  SELECT s."Id", s."CreatedAt", s."CustomerId", ... FROM (SELECT o."Id", ...

One request, one query, with the customer and the lines joined. Then it checked that the slow traces all belong to the same route, by extracting the route and the number of database spans from two more of them:

spans=203 route=/orders/recent serverMs=72 db=201
spans=203 route=/orders/recent serverMs=74 db=201

##The report

Only then did the agent search the code for orders/recent, and read that handler:

C#
app.MapGet("/orders/recent", async (OrdersDbContext db, ILogger<Program> logger) =>
{
    var orders = await db.Orders
        .OrderByDescending(o => o.CreatedAt)
        .Take(100)
        .ToListAsync();

    var result = new List<OrderSummary>();
    foreach (var order in orders)
    {
        var customer = await db.Customers.FirstAsync(c => c.Id == order.CustomerId);
        var total = await db.OrderLines
            .Where(l => l.OrderId == order.Id)
            .SumAsync(l => l.Quantity * l.UnitPrice);

        result.Add(new OrderSummary(order.Id, order.CreatedAt, customer.Name, total));
    }

    logger.LogInformation("Built the recent orders summary with {OrderCount} orders", result.Count);
    return Results.Ok(result);
});

Its report, shortened:

Symptom: GET /orders/recent takes 72–110 ms while every other route on orders-api returns in 2–5 ms.

Root cause: the /orders/recent handler loads 100 orders, then in a foreach awaits two more queries per order,
db.Customers.FirstAsync and db.OrderLines…SumAsync. Classic N+1: 1 + 100 + 100 = 201 queries.
The other two routes don't do this: /orders/{id:int} uses Include, and /customers/{id:int}/orders already
projects the customer name and line total inside the query, so EF emits a single statement.

Confidence: High. Three slow traces independently show 201 DB spans on /orders/recent, and the query text
matches the two awaits in the loop one-for-one.

The whole investigation took 21 turns and a bit less than 2 minutes.

#The fix

The agent proposed the projection that another endpoint of the same API already uses:

C#
    var orders = await db.Orders
    var result = await db.Orders
         .OrderByDescending(o => o.CreatedAt)
         .Take(100)
        .ToListAsync();

    var result = new List<OrderSummary>();
    foreach (var order in orders)
    {
        var customer = await db.Customers.FirstAsync(c => c.Id == order.CustomerId);
        var total = await db.OrderLines
            .Where(l => l.OrderId == order.Id)
            .SumAsync(l => l.Quantity * l.UnitPrice);

        result.Add(new OrderSummary(order.Id, order.CreatedAt, customer.Name, total));
    }
        .Select(o => new OrderSummary(o.Id, o.CreatedAt, o.Customer.Name, o.Lines.Sum(l => l.Quantity * l.UnitPrice)))
        .ToListAsync();

The telemetry also verifies the fix. aspire resource orders-api rebuild rebuilds and restarts only the API, and the next traces for the route look like this:

│ 11:10:02.539 │ load-generator-pxuexeen: GET cf6d2d6 │ 203   │ 0.11s    │ OK     │
│ 11:10:03.540 │ load-generator-pxuexeen: GET 9e91f77 │ 203   │ 0.1s     │ OK     │
│ 11:10:08.790 │ load-generator-pxuexeen: GET 1479e4b │ 3     │ 11.24ms  │ OK     │
│ 11:10:09.789 │ load-generator-pxuexeen: GET 7476aba │ 3     │ 5.24ms   │ OK     │
│ 11:10:11.539 │ load-generator-pxuexeen: GET 306ed5d │ 3     │ 4.64ms   │ OK     │

From 203 spans and about 90 ms to 3 spans and about 5 ms. PostgreSQL runs on the same machine here, so each round trip costs a fraction of a millisecond. With a database 1 ms away on the network, the same loop costs 200 ms more, and the fix saves it all.

#Telemetry contains secrets too

Everything the first post says about dumps applies to telemetry, in a milder form. What the agent read in this investigation, and therefore what was sent to the model:

  • list_resources returns the dashboard URL with its login token, http://localhost:15163/login?t=.... The tool hides the values of environment variables, but not this.
  • Every database span has the SQL text in db.query.text, and the connection string without its password in db.npgsql.data_source: Host=localhost;Port=57852;Username=postgres;Database=ordersdb.
  • Logs contain whatever the code logs. By default, Entity Framework Core logs every SQL command at the Information level.

SQL parameter values are not in the spans, and the dashboard runs locally. This is a development tool: point it at a local application with test data, not at a copy of production.

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

Every mistake below has a fix, and it is always one of three things: a line in the skill, a better prompt, or one command you run yourself.

It concludes that nothing is slow. list_traces returns the most recent traces that fit, and a slow trace with many spans often does not fit at all.

Fix: the first line of Known limits, which says never to conclude from list_traces, and points to aspire otel traces.

It fails to parse the JSON. aspire otel prints a line about scanning for AppHosts before the JSON. The agent recovered in one step, but it wasted a turn.

Fix: a line in Known limits: always pass --apphost AppHost/AppHost.csproj. With it, the command skips the scan and the line is gone.

It adds up durations that are rounded. durationMs is an integer. A query that takes 0.3 ms reports 0, so 100 of them add up to 0 or to a small number: above, the 201 queries "total" 21 ms of an 82 ms request. The agent did not rely on that sum, but a model easily concludes "the database is only 25 % of the time".

Fix: a line in Known limits: a duration of 0 means less than 1 ms, so count the spans instead of adding their durations. The table output of aspire otel spans prints precise durations, such as 0.31ms.

It looks for data that is gone. The dashboard keeps telemetry in memory, and evicts the oldest entries first: by default, 10,000 log entries shared by all the resources. Entity Framework Core logs every command, so a slow request writes 202 log entries. For a fresh trace, list_trace_structured_logs found them, and returned the latest 37 because of its size limit. For the same trace, three and a half minutes later:

list_trace_structured_logs(traceId: "971cc00124d977c6377d2aaaeb26d72a")

Returned 0 log entries.

The trace still existed. Its logs did not. An agent that reads "0 log entries" as "this request logged nothing" is wrong.

Fix: a line in Before you start, and "the problem is happening now" in the prompt. If the logs are noisy, lower the level of Microsoft.EntityFrameworkCore.Database.Command, or raise Dashboard:TelemetryLimits:MaxLogCount.

It reads the source first. Given "some requests are slow" and a 60-line API, the agent can spot the loop without any telemetry.

Fix: rule 6. On a real application, "which of 200 endpoints is slow" is a question for the traces, not for grep.

The traces answered "what is slow" in one command, and "why" in one more. Here, the slow code ran in a single service. The next post follows a request across several services, where the trace shows the time, and the logs explain it.

#Additional resources

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

Follow me:
Enjoy this blog?