Following a slow request across services 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!

In the previous post, the slow code and the slow queries were in the same service. This time, a request goes through a web shop, a Redis cache, and a catalog service. The trace shows where the time goes, the logs say what the code decided, and the agent needs both.

It also shows why an agent's report deserves a second look, even when the fix is right: the agent found the faulty line, and still got the explanation slightly wrong.

The setup is the same as in the previous post: the Aspire MCP server, the aspire command line, and the same skill with a few more lines. The sample contains everything. Every output below comes from it, with the same versions as in the previous post.

#The application

Four resources:

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

var cache = builder.AddRedis("cache");

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

var storefront = builder.AddProject<Projects.Storefront>("storefront")
    .WithReference(cache)
    .WithReference(catalog)
    .WaitFor(cache)
    .WaitFor(catalog)
    .WithHttpHealthCheck("/health");

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

builder.Build().Run();
  • catalog-api returns a product in 30 to 60 ms. The delay stands for the query to the catalog database.
  • storefront renders a cart. For each line, it gets the product from the catalog through an IDistributedCache backed by Redis, so a product is only loaded once every few minutes.
  • load-generator displays a random cart, out of 200, twice per second. There are only 50 products.

With a cache that works, a cart should take a few milliseconds. It takes between 110 and 400 ms.

#Ask the question

GET /carts/{id} on storefront takes between 150 and 350 ms, which is much slower than expected.
The application is running under Aspire. Find out why.

The prompt does not mention the cache. The agent loaded the skill and started the same way as in the previous post: list_resources, where it noticed that storefront depends on cache and catalog-api, then the list of traces.

#Follow the investigation

##The traces grow with the carts

Shell
aspire otel traces storefront --apphost AppHost/AppHost.csproj -n 200

With the trace URLs removed:

│ 11:11:14.858 │ storefront: HMGET 246ad70 │ 17    │ 0.16s    │ OK     │
│ 11:11:15.358 │ storefront: HMGET 34bef37 │ 37    │ 0.33s    │ OK     │
│ 11:11:15.858 │ storefront: HMGET c343c77 │ 27    │ 0.26s    │ OK     │
│ 11:11:16.358 │ storefront: HMGET ebf49a9 │ 22    │ 0.21s    │ OK     │
│ 11:11:17.358 │ storefront: HMGET 3718e6e │ 17    │ 0.11s    │ OK     │
│ 11:11:17.659 │ storefront: PING 253d48b  │ 2     │ 1.46ms   │ OK     │

--apphost comes from a line that the previous investigation added to the skill: without it, the command prints a line before its output, and jq fails. The agent's first observation: "Duration clearly scales with span count". A cart with more lines has more spans, and it is slower.

The Name column now says HMGET, a Redis command. It is not the name of the request. The route is an attribute of the server span, and the skill says so.

##A timeline across three services

The agent's first attempt to print the spans of the slowest trace produced a table with two empty columns:

        Client  GET                  http://localhost:5402/carts/17
        Server  GET /carts/{id:int}  /carts/{id:int}
        Client  HMGET

It had asked jq for .startTime and .duration, fields that do not exist. It printed the first span to see the real shape, then sorted the spans by timestamp:

Shell
aspire otel spans --trace-id 16dfc89631845a25a7ee62b4072d521b -n 500 --format Json --apphost AppHost/AppHost.csproj \
  | jq -r 'sort_by(.timestamp) | .[] | [.timestamp[11:23], (.durationMs|tostring), .source, .kind, .name, (.attributes["url.full"] // "")] | @tsv'
15:11:41.358  383  load-generator  Client  GET  http://localhost:5402/carts/17
15:11:41.358  382  storefront      Server  GET /carts/{id:int}
15:11:41.358  1    storefront      Client  HMGET
15:11:41.359  53   storefront      Client  GET  http://localhost:5401/products/49
15:11:41.360  53   catalog-api     Server  GET /products/{id:int}
15:11:41.413  1    storefront      Client  HMSET
15:11:41.413  1    storefront      Client  EXPIRE
15:11:41.414  1    storefront      Client  HMGET
15:11:41.415  60   storefront      Client  GET  http://localhost:5401/products/9
15:11:41.415  60   catalog-api     Server  GET /products/{id:int}
15:11:41.475  1    storefront      Client  HMSET
15:11:41.475  1    storefront      Client  EXPIRE
...

This is what a distributed trace is for. One request of the load generator becomes a server span in storefront, which calls Redis and catalog-api, whose server span is the child of the HTTP client span. The pattern repeats for each of the 7 lines of the cart:

  1. HMGET: read the product from Redis,
  2. GET /products/{id} on the catalog, 40 to 60 ms,
  3. HMSET and EXPIRE: write the product to Redis, with an expiration.

The 7 catalog calls add up to 368 of the 383 ms, and the Redis calls take a millisecond each. So the question is not "why is the catalog slow" but "why is the catalog called at all". Every read is followed by a write: the cache never answers.

A fast trace, 144 ms, has the same pattern with only 3 lines.

##The logs say it too

The storefront logs a message when a product is not in the cache. list_trace_structured_logs returns the logs of one trace, and this is where the MCP server is the right tool: the result is small and already filtered.

list_trace_structured_logs(traceId: "847ea2987fd73b7c20c901e3d8e01ede")

Returned 18 log entries.

"message":"Product 19 not found in the cache, loading it from the catalog", ..., "RequestPath":"/carts/156"
"message":"Product 40 not found in the cache, loading it from the catalog", ..., "RequestPath":"/carts/156"
"message":"Product 39 not found in the cache, loading it from the catalog", ..., "RequestPath":"/carts/156"

With 50 products and 2 carts per second, a working cache would have loaded all the products after a few seconds. The agent had its symptom, and it read the code.

##The code

C#
public async Task<Product> GetProductAsync(int productId)
{
    var key = $"product:{productId}";
    var cached = await cache.GetStringAsync(key);
    if (cached is not null)
        return JsonSerializer.Deserialize<Product>(cached)!;

    logger.LogInformation("Product {ProductId} not found in the cache, loading it from the catalog", productId);
    var product = await httpClient.GetFromJsonAsync<Product>($"/products/{productId}")
        ?? throw new InvalidOperationException($"Product {productId} does not exist");

    await cache.SetStringAsync(key, JsonSerializer.Serialize(product), new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(options.Value.ProductCacheDuration),
    });

    return product;
}

The option is documented in seconds, and appsettings.json sets it to 600:

C#
sealed class CatalogOptions
{
    // In seconds
    public int ProductCacheDuration { get; set; } = 300;
}

##The report

The agent's report, shortened:

Root cause: Cache TTL is 1000× too short, Storefront/Program.cs:52. CatalogOptions.ProductCacheDuration is
documented "In seconds" and Storefront/appsettings.json sets it to 600. The entry therefore expires after
600 milliseconds, so every entry is gone before the next request needs it. That is why the cache never hits.

Also: Serial N+1 fan-out, Storefront/Program.cs:20-24: the foreach awaits catalog.GetProductAsync one item at
a time, so every cache miss adds its full latency to the response.

Fix: TimeSpan.FromSeconds, and fetch the items concurrently with Task.WhenAll.

17 turns, a bit more than a minute and a half. The line is right, and the fix is right. The explanation is not quite.

#The entries do not live 600 ms

"The entry expires after 600 milliseconds" predicts something the agent did not check: a product loaded twice in less than 600 ms should come from the cache the second time. Carts can contain the same product twice, so the telemetry can test that. Grouping the "not found" logs by trace and product:

Shell
aspire otel logs storefront --apphost AppHost/AppHost.csproj --format Json -n 100000 \
  | jq '[.[] | select(.message | test("not found in the cache"))] | group_by(.traceId + .attributes.ProductId) | map(select(length > 1)) | length'
75

75 requests loaded the same product twice. In one of them, product 22 is written to Redis, and read again 45 ms later:

15:12:18.948  44  Client  GET  http://localhost:5401/products/22
15:12:18.992  2   Client  HMSET
15:12:18.992  2   Client  EXPIRE
15:12:18.994  1   Client  HMGET
15:12:18.995  41  Client  GET  http://localhost:5401/products/43
15:12:19.036  2   Client  HMSET
15:12:19.036  1   Client  EXPIRE
15:12:19.037  1   Client  HMGET
15:12:19.038  39  Client  GET  http://localhost:5401/products/22

45 ms after the write, the entry is already gone. The reason is in the Redis implementation of IDistributedCache. It sends the expiration to Redis in whole seconds, and it computes them by truncating:

C#
// Microsoft.Extensions.Caching.StackExchangeRedis.RedisCache, decompiled
return (long)(absoluteExpiration.Value - creationTime).TotalSeconds;

600 ms becomes EXPIRE product:22 0, and Redis deletes a key whose expiration is 0 immediately. The cache does not keep the entries for too short a time. It deletes every entry the moment it writes it.

For this bug, the difference does not change the fix. It matters for the next one: with the "600 ms" explanation, a duration of 1,500 ms looks like it works, a little. It actually caches for 1 second, and 999 ms caches nothing. The skill now has a line for that:

- A cache that works has no write after most reads. A write after every read means the entries never survive:
  find the same key read twice, and the time between the write and the next miss tells how long the entry lived

#The fix

C#
 await cache.SetStringAsync(key, JsonSerializer.Serialize(product), new DistributedCacheEntryOptions
 {
    AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(options.Value.ProductCacheDuration),
    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(options.Value.ProductCacheDuration),
 });

A TimeSpan in the options, bound from "00:10:00", removes the unit from the equation entirely.

aspire resource storefront rebuild restarts only the storefront. The traces show the cache warming up:

│ 11:14:43.858 │ load-generator: GET 6e5cc04 │ 18    │ 0.13s    │ OK     │
│ 11:14:45.358 │ load-generator: GET 87d5c43 │ 9     │ 59.39ms  │ OK     │
│ 11:14:48.858 │ load-generator: GET 688e596 │ 5     │ 2.55ms   │ OK     │
│ 11:14:49.358 │ load-generator: GET 45e7d5e │ 33    │ 0.33s    │ OK     │
│ 11:14:50.358 │ load-generator: GET 843244a │ 9     │ 6.87ms   │ OK     │
│ 11:14:52.357 │ load-generator: GET 7d854a1 │ 7     │ 5.86ms   │ OK     │
│ 11:14:55.358 │ load-generator: GET 7a11532 │ 7     │ 4.58ms   │ OK     │

Over the traces before the fix, and over the traces of the next 30 seconds once the cache is warm:

Tracesp50p95
Before463249 ms358 ms
After855 ms8 ms

The agent also proposed to load the products in parallel with Task.WhenAll. That is a real improvement for a cold cache, and it is a separate change: with the cache working, the loop costs 5 ms. Mixing both in one fix hides which one solved the problem, and a parallel loop would have made this bug several times less visible without fixing it. Rule 7 is about that.

#Things that look like bugs, and are not

A few details of the telemetry confused me, or the agent, during this investigation. They are now in the Known limits section of the skill.

  • Redis spans arrive late. Right after the fix, the most recent traces had 2 spans instead of 5 to 9. The Redis instrumentation exports its spans about every 10 seconds, independently of the other spans of the same request. A trace from the last seconds can look like it never touched Redis.
  • Redis spans do not have the key. db.statement is HMGET or HMSET, nothing else. The logs are the only place that says which product was missed.
  • The table and the JSON do not use the same clock. The table prints 11:12:18, local time, and the JSON prints 15:12:18Z. An agent that compares a timestamp from one with a timestamp from the other finds a four-hour gap.
  • --search is not a phrase search. --search "Product 21 not found" returned the logs of products 18, 17, 25, and others. Filter the JSON with jq when the text matters.

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

It invents field names. .startTime and .duration sound right for a span, and jq prints empty values for missing fields without an error.

Fix: a line in Known limits with the actual fields of a span, and the habit of running jq '.[0]' first. The agent recovered on its own here, one call later.

It stops at a plausible explanation. "Expires after 600 ms" matches the code and the symptom. It does not match a product that is missed 45 ms after being written, and the agent did not look for one.

Fix: the cache line above, and a question in the prompt when the cause is a cache, a timeout, or a retry: "what does your explanation predict, and does the telemetry agree?".

It bundles fixes. The report had two fixes, one for the cause and one for the design.

Fix: rule 7, and read the report with the question "which of these changes removes the cause?".

It blames the slow service. The catalog takes 50 ms per product, and it is 96 % of the request. An agent that reads only durations proposes to optimize the catalog. This one did not, because the skill asks it to count, and the count was "one catalog call per line, every time".

Fix: rule 4, which asks for counts before explanations.

The traces and the logs answered this investigation, and the metrics were not needed. The next post is about a problem where each trace looks innocent, and only the metrics show the cause.

#Additional resources

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

Follow me:
Enjoy this blog?