LESSON 16 OF 20

16. Metrics, Performance Analysis, and Observability

Collect ASP.NET Core, .NET runtime, and application metrics with OpenTelemetry and the Aspire Dashboard to analyze latency, errors, cache behavior, and queue performance.

50 dk 33

Introduction

In the previous lesson, we used logging, correlation, and distributed tracing to follow a request through the system and identify which services participated in it. In this lesson, we will evaluate the same system with numerical data. Metrics are telemetry measurements that describe application behavior over time. They can show how many requests occurred, how long they took, how many failed, how effectively a cache was used, or how long RabbitMQ messages waited before being processed.

Logs describe individual events, traces describe the path of one request, and metrics describe the overall behavior of the system. A trace might show that one order request took 1.8 seconds. A histogram can show that the p95 latency of order requests during the last five minutes was 420 ms. This distinction moves performance analysis from isolated examples to measurable trends.

In our Catalog, Order, and Inventory services, we will monitor:

  • ASP.NET Core HTTP request counts, errors, and latency distributions,
  • .NET runtime indicators related to CPU, garbage collection, and thread-pool behavior,
  • business metrics for orders, cache hits and misses, and failures,
  • RabbitMQ message waiting and processing durations,
  • bottleneck analysis and improvement cycles using the Aspire Dashboard.

The goal is not to produce as many charts as possible. Start with a measurable question, choose the correct instrument, validate the result with traces and logs, and then make one controlled improvement.

1. Choose metric instruments based on the question

The .NET metrics API and OpenTelemetry provide different instruments for different measurement goals:

InstrumentWhat it measuresExample
CounterA total that increases over timeTotal requests or errors
UpDownCounterA value that can increase and decreaseActive messages or connections
HistogramA distribution of recorded valuesHTTP and queue processing duration
ObservableGaugeA value observed at a particular pointApproximate cache item count

Counter is not the right instrument for request latency because it would lose the distribution of durations. Use a Histogram instead. For error rate, publishing separate request and error counters is flexible because the ratio can be calculated for different time windows. Cache hit ratio can similarly be calculated as cache_hits / (cache_hits + cache_misses). Publishing the raw counters instead of a single application-calculated ratio makes analysis easier in the Dashboard or another telemetry backend.

2. Add application-specific metrics

Let us create a small metric class for order operations. A stable Meter name allows the OpenTelemetry configuration to subscribe to these instruments explicitly.

using System.Diagnostics.Metrics;

public static class OrderMetrics
{
    public const string MeterName = "Shop.OrderService";

    private static readonly Meter Meter = new(MeterName, "1.0.0");

    public static readonly Counter<long> OrdersCreated =
        Meter.CreateCounter<long>("orders.created", "{order}");

    public static readonly Counter<long> OrdersFailed =
        Meter.CreateCounter<long>("orders.failed", "{order}");

    public static readonly Histogram<double> OrderDuration =
        Meter.CreateHistogram<double>("orders.duration", "ms");

    public static readonly Counter<long> CacheHits =
        Meter.CreateCounter<long>("catalog.cache.hits", "{hit}");

    public static readonly Counter<long> CacheMisses =
        Meter.CreateCounter<long>("catalog.cache.misses", "{miss}");

    public static readonly Histogram<double> QueueDuration =
        Meter.CreateHistogram<double>("orders.queue.duration", "ms");
}

Record measurements at the correct points in the application workflow:

public async Task<IResult> CreateOrderAsync(
    CreateOrderRequest request,
    CancellationToken cancellationToken)
{
    var started = Stopwatch.GetTimestamp();

    try
    {
        var product = await catalogClient.GetProductAsync(
            request.ProductId, cancellationToken);

        if (product is null)
        {
            OrderMetrics.CacheMisses.Add(1,
                new KeyValuePair<string, object?>("service", "catalog"));
            return Results.NotFound();
        }

        OrderMetrics.CacheHits.Add(1,
            new KeyValuePair<string, object?>("service", "catalog"));

        var order = await orderRepository.CreateAsync(request, cancellationToken);
        OrderMetrics.OrdersCreated.Add(1);
        return Results.Created($"/orders/{order.Id}", order);
    }
    catch (Exception)
    {
        OrderMetrics.OrdersFailed.Add(1);
        throw;
    }
    finally
    {
        var elapsedMs = Stopwatch.GetElapsedTime(started).TotalMilliseconds;
        OrderMetrics.OrderDuration.Record(elapsedMs);
    }
}

In a production application, cache hit and miss measurements should normally be emitted in one cache abstraction. Recording the same event in both the controller and repository can inflate totals. Avoid using high-cardinality values such as product IDs, order IDs, or user IDs as metric tags. Thousands of distinct values create unnecessary time series and increase storage and processing costs.

3. Configure OpenTelemetry metrics

In an Aspire solution, the ServiceDefaults project commonly centralizes shared logging, tracing, and metrics configuration. Add the application Meter to the metrics pipeline:

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics.AddMeter(OrderMetrics.MeterName);
        metrics.AddMeter("Shop.CatalogService");
        metrics.AddMeter("Shop.InventoryService");
    });

Also verify that ASP.NET Core and runtime meters are enabled. Depending on the ServiceDefaults version used by the solution, these meters may already be registered by a shared extension. An explicit example is:

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics.AddMeter(
            "Microsoft.AspNetCore.Hosting",
            "Microsoft.AspNetCore.Server.Kestrel",
            "System.Net.Http",
            "System.Runtime",
            OrderMetrics.MeterName);
    });

Rebuilding the entire OpenTelemetry pipeline in multiple locations can create duplicate exporters or unexpected registrations. Inspect the existing ServiceDefaults extension and add only the missing Meter or instrumentation. When the Aspire application runs, the services send telemetry through OTLP to the Dashboard, where resources and meters appear separately on the Metrics page.

4. Read ASP.NET Core and runtime metrics

ASP.NET Core metrics are a useful starting point. Do not rely on the average request duration alone. A few extremely fast requests can hide a small number of very slow requests. The p50 represents a typical request, while p95 and p99 help reveal the experience of the slowest users.

Select the OrderService resource in the Dashboard and inspect the ASP.NET Core or Kestrel meters. Filter by route, HTTP method, and response status. Ask these questions first:

  1. Which endpoint has the highest p95 latency?
  2. Does latency increase only for 5xx responses?
  3. Does the error rate rise together with request volume?
  4. Is the increase limited to OrderService, or do Catalog and Inventory calls also slow down?

Next, inspect the System.Runtime meter. Higher CPU usage, longer garbage-collection pauses, or thread-pool queueing may contribute to application latency. However, correlation in a runtime metric is not proof of causation. Use traces and structured logs from the same time window to validate the hypothesis.

5. Analyze queue waiting and message processing

For the RabbitMQ OrderPlaced consumer, it is useful to distinguish two durations:

  • Queue duration: The time from publishing the message until the consumer receives it.
  • Processing duration: The time from receipt until the consumer completes successfully or fails.

If the message contains a publish timestamp, the consumer can calculate queue duration and record it in a histogram. Clock differences between machines can produce negative or inaccurate values, so a reliable timestamp strategy is required in production. Processing duration can be measured directly in the consumer:

public async Task HandleAsync(OrderPlaced message,
    CancellationToken cancellationToken)
{
    var started = Stopwatch.GetTimestamp();
    try
    {
        await inventoryClient.ReserveAsync(
            message.OrderId, cancellationToken);
        await orderRepository.MarkProcessedAsync(
            message.OrderId, cancellationToken);
    }
    finally
    {
        OrderMetrics.QueueDuration.Record(
            Stopwatch.GetElapsedTime(started).TotalMilliseconds);
    }
}

There is an important naming issue in this example: the code actually records consumer processing duration. The queue waiting time must be measured separately. Name the instruments clearly, for example orders.queue.wait and orders.consumer.duration. Incorrect names can lead the team to make the wrong operational decision.

6. Find bottlenecks with the Aspire Dashboard

Use a repeatable analysis workflow:

  1. Choose the symptom: For example, Order creation p95 latency is above 600 ms.
  2. Narrow the time window: Identify the deployment or test period when the change occurred.
  3. Separate services: Inspect Order, Catalog, and Inventory metrics independently.
  4. Filter dimensions: Focus on the relevant endpoint, status code, or operation.
  5. Open a trace: Select a slow trace from the same period and compare span durations.
  6. Validate with logs: Search for retry, timeout, SQL, or RabbitMQ warnings that coincide with the delay.
  7. Make one change: For example, remove an unnecessary Catalog call or configure an appropriate cache lifetime.
  8. Measure before and after: Compare p95 latency, error rate, and resource usage with the same request profile.

A metric chart shows the behavior of a signal over time; a trace shows the details of one operation. If catalog.cache.hits increases but Order latency does not improve, inspect whether the cache contains the expected data and examine the HTTP and SQL spans after a cache miss.

7. Common mistakes

  • Monitoring only the average: Without p95 or p99, a small number of slow requests may remain hidden.
  • Using high-cardinality tags: Adding UserId, OrderId, or the complete URL to every metric can expand the Dashboard and backend unnecessarily.
  • Skipping failed operations: Record duration in a finally block or another scope that also executes when the operation fails.
  • Calculating cache ratio incorrectly: Hit and miss counters must use the same scope; not every successful HTTP response is a cache hit.
  • Confusing queue wait with processing time: They represent different bottlenecks.
  • Treating the Dashboard as a production APM platform: The Aspire Dashboard is highly useful for development and local inspection, but production retention, access control, alerting, and long-term storage need separate design.
  • Publishing sensitive data: Card numbers, tokens, secrets, and personal data should not be placed in metric tags, logs, or trace attributes.

8. Short practice exercise

Run the application through the Aspire AppHost and complete this experiment:

  1. Enable orders.duration, orders.created, and orders.failed in OrderService.
  2. Add cache hit and miss counters to the Catalog cache layer.
  3. Send at least 30 successful and 10 unsuccessful order requests.
  4. Inspect total requests, error rate, and latency distribution in the Dashboard.
  5. Disable the cache and repeat the same test.
  6. Compare p95 latency and cache hit ratio for both conditions in a table.
  7. Select one slow trace and explain whether the delay came from HTTP, SQL, cache, or the message queue.

Do not finish by saying only that “the cache was faster.” Record which metric changed, during which time window, whether the error rate changed, and how the trace data supports your conclusion.

Conclusion

Metrics let us observe the overall health of a distributed application over time. ASP.NET Core and runtime metrics expose platform behavior, application-specific counters and histograms expose business operations, and queue and cache metrics reveal the performance of communication between services.

Effective analysis combines metrics, traces, and logs. Begin with a measurable question, select the appropriate instrument, use low-cardinality dimensions, and measure the same signal again after an improvement. In this way, the Aspire Dashboard becomes more than a screen showing whether resources are running: it becomes a practical development tool for supporting performance decisions with evidence.

Sources