Covers the three core metric instrument types (counter, gauge, histogram), the System.Diagnostics.Metrics instruments that implement them, and the built-in ASP.NET Core, HttpClient and System.Runtime metrics in .NET 10.
A counter only goes up: it is a running total such as requests served or orders placed, and you chart its rate. A gauge is a current value that rises and falls, such as queue length, active connections or working set. A histogram records many measurements, such as request durations, into buckets so you can ask for the p95 or p99, not just an average.
In .NET these are Counter<T>, UpDownCounter<T>, Gauge<T>/ObservableGauge<T> and Histogram<T> in System.Diagnostics.Metrics. ASP.NET Core already publishes http.server.request.duration (a histogram) and http.server.active_requests; Kestrel, HttpClient and the System.Runtime meter add connection, outbound call, GC, thread pool and exception metrics.
The trade-off: histograms answer the most questions but cost the most series, so use them for latency and sizes, and counters for everything you only need to count.
"The three shapes answer different questions. A counter is a monotonic total: requests handled, orders placed, bytes sent. Nobody cares that the total is 4.2 million; you look at its rate, so the backend turns it into 'requests per second'. A gauge is a snapshot of something that goes up and down: items in a queue, open connections, memory in use. You look at its current value and its trend. A histogram records a distribution: every request duration falls into a bucket, and from the buckets you can work out the p50, p95 and p99. That is the one you need for latency, because an average hides the slow tail.
In .NET those map to
System.Diagnostics.Metrics:Counter<T>,UpDownCounter<T>for values you add to and subtract from,Gauge<T>(synchronous since .NET 9) orObservableGauge<T>for current values read on a callback, andHistogram<T>. The good news is that a lot is already there. ASP.NET Core publisheshttp.server.request.durationas a histogram with route, method and status code tags, plushttp.server.active_requests. Kestrel publishes connection metrics,HttpClientpublisheshttp.client.request.duration, and since .NET 9 theSystem.Runtimemeter publishes GC collections and pause time, thread pool queue length and exception counts. .NET 10 adds authentication, authorisation, Identity and Blazor metrics. I can see all of it withdotnet-counters monitorbefore I write a line of code.The mistake I see is people building a 'requests' gauge or averaging durations into a gauge, which throws away the information you need in an incident. Count events, gauge states, and put durations in a histogram."
| Type | What it holds | Example in an API | How you chart it | .NET instrument |
|---|---|---|---|---|
| Counter | Monotonic total | Orders placed, failed payments | rate() per second or per minute |
Counter<T>, ObservableCounter<T> |
| UpDownCounter | Running sum of +/- deltas | Items currently in an in-memory queue | Current value | UpDownCounter<T> |
| Gauge | Current value, sampled | Working set, pool size, last batch size | Current value, min/max over time | Gauge<T> (.NET 9+), ObservableGauge<T> |
| Histogram | Distribution in buckets | Request duration, payload size | Percentiles, heatmap | Histogram<T> |
| Meter | Metric | Type | Why it matters |
|---|---|---|---|
Microsoft.AspNetCore.Hosting |
http.server.request.duration |
Histogram (seconds) | Rate, errors and latency per route: the RED signals |
Microsoft.AspNetCore.Hosting |
http.server.active_requests |
UpDownCounter | Concurrency, early sign of saturation |
Microsoft.AspNetCore.Server.Kestrel |
kestrel.active_connections, kestrel.queued_connections |
UpDownCounter | Connection pressure |
Microsoft.AspNetCore.Diagnostics |
aspnetcore.diagnostics.exceptions |
Counter | Unhandled exceptions by type |
System.Net.Http |
http.client.request.duration |
Histogram | Latency of your dependencies |
System.Runtime |
dotnet.gc.collections, dotnet.gc.pause.time, dotnet.thread_pool.queue.length, dotnet.exceptions |
Counter / UpDownCounter | GC pressure, thread pool starvation |
On an orders API doing about 400 requests/s, the built-in http.server.request.duration histogram showed p99 jumping from 180 ms to 2.4 s while p50 stayed at 40 ms. dotnet.thread_pool.queue.length climbed from 0 to over 300 at the same time, which pointed straight at sync-over-async blocking rather than the database. No custom metric was needed to find it.
Checks that the candidate knows which instrument fits which question, and knows the metrics .NET already publishes instead of reinventing them.
Green flags
http.server.request.duration and the System.Runtime meterdotnet-counters or OpenTelemetry to see the metricsRed flags
A metric is a number aggregated in the process over a time window and exported as a small record: name, tags (dimensions), value and timestamp. That is why metrics are cheap compared with logs: 400 requests per second become one histogram record per export interval per tag combination, not 400 log lines.
request ──► Histogram.Record(0.042, route=/orders, code=200)
│
▼ in-process aggregation (per tag set)
buckets: [≤0.005:12][≤0.01:40][≤0.025:210][≤0.05:118]...
│ every 60 s (OTLP) or on scrape (Prometheus)
▼
metrics backend ──► rate(), histogram_quantile()
A counter is cumulative. Backends calculate a rate as the difference between two samples divided by the time between them. If the process restarts the counter resets to 0; Prometheus rate() detects the drop and treats it as a reset. This is why you never record "requests in the last minute" yourself: the backend does the windowing.
OpenTelemetry supports cumulative and delta temporality. Prometheus wants cumulative; some backends (and the Azure Monitor exporter) work with delta. The SDK handles it; you only choose the exporter.
ObservableGauge<T> takes a callback; the SDK calls it at collection time. Use it for values you can read cheaply on demand (queue depth, pool size).Gauge<T> (added in .NET 9) is recorded when the value changes, useful when the value is only known at an event (for example the size of the last batch).UpDownCounter<T> is for values you track with Add(+1) / Add(-1), such as in-flight jobs.A histogram stores counts per bucket boundary plus a sum and a count. Percentiles are estimated from the buckets, so the boundaries decide accuracy. The OpenTelemetry default boundaries (0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000) suit milliseconds; ASP.NET Core records seconds and advises its own boundaries (0.005 to 10 s) through InstrumentAdvice<T>, which .NET 9 introduced. Every bucket is a separate time series in Prometheus, so a histogram costs roughly buckets + 2 series per tag combination.
Meter("Microsoft.AspNetCore.Hosting") ─┐
Meter("System.Runtime") ├─► MeterListener ─► OpenTelemetry SDK ─► OTLP / Prometheus / Azure Monitor
Meter("Shop.Orders") (yours) ┘ └► dotnet-counters / dotnet-monitor (EventPipe)
Instruments do nothing until a listener subscribes, so an unused meter costs almost nothing. IMeterFactory (from .NET 8) creates meters through DI so they can be isolated in tests.
EventCounters (System.Runtime counters such as cpu-usage, gc-heap-size in dotnet-counters) were the .NET Core 3.0 to 8 mechanism; PerformanceCounter is Windows-only .NET Framework. New code uses System.Diagnostics.Metrics, which OpenTelemetry reads natively.
dotnet-counters monitor -n MyApi --counters Microsoft.AspNetCore.Hosting,System.Runtime. Send load with bombardier or k6 and watch the values.Thread.Sleep(200) to an endpoint and watch dotnet.thread_pool.queue.length under load.Counter<long> and an ObservableGauge<int> and view them with dotnet-counters monitor --counters Your.Meter.rate() handles the counter reset.One small service that uses each instrument type, registered through IMeterFactory:
// Program.cs (.NET 10, nullable enabled)
using System.Diagnostics.Metrics;
using OpenTelemetry.Metrics;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<OrderMetrics>();
builder.Services.AddOpenTelemetry().WithMetrics(m => m
.AddAspNetCoreInstrumentation() // http.server.* and kestrel.*
.AddHttpClientInstrumentation() // http.client.*
.AddRuntimeInstrumentation() // dotnet.gc.*, dotnet.thread_pool.*
.AddMeter(OrderMetrics.MeterName)
.AddOtlpExporter());
var app = builder.Build();
app.MapPost("/orders", async (OrderRequest req, OrderMetrics metrics, CancellationToken ct) =>
{
var started = TimeProvider.System.GetTimestamp();
await Task.Delay(20, ct); // stand-in for real work
metrics.OrderPlaced(req.Channel);
metrics.RecordPricing(TimeProvider.System.GetElapsedTime(started));
return Results.Accepted();
});
app.Run();
public sealed record OrderRequest(string Channel, decimal Total);
namespace Shop.Orders;
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
public sealed class OrderMetrics
{
public const string MeterName = "Shop.Orders";
private readonly Counter<long> _ordersPlaced; // counter: only goes up
private readonly Histogram<double> _pricingDuration; // histogram: distribution
private readonly ConcurrentQueue<Guid> _pending = new();
public OrderMetrics(IMeterFactory meterFactory)
{
var meter = meterFactory.Create(MeterName);
_ordersPlaced = meter.CreateCounter<long>("shop.orders.placed", unit: "{order}");
_pricingDuration = meter.CreateHistogram<double>("shop.pricing.duration", unit: "s");
// gauge: read on demand at collection time, no bookkeeping on the hot path
meter.CreateObservableGauge("shop.orders.pending", () => _pending.Count, unit: "{order}");
}
// Low-cardinality tag only: channel has 3 values (web, app, phone)
public void OrderPlaced(string channel) =>
_ordersPlaced.Add(1, new KeyValuePair<string, object?>("channel", channel));
public void RecordPricing(TimeSpan elapsed) => _pricingDuration.Record(elapsed.TotalSeconds);
}
# Watch built-in and custom metrics live, no exporter needed
dotnet-counters monitor -n Shop.Api --counters Microsoft.AspNetCore.Hosting,System.Runtime,Shop.Orders
Counter<long> and let the backend apply rate().Histogram<double>.http.server.request.duration with route and status tags. Instead: enable AddAspNetCoreInstrumentation() and add custom metrics only for business events.unit: "s".Meter per request or per class instance. Why it is wrong: it leaks listeners and duplicates instruments. Instead: create meters once via IMeterFactory in a singleton.UpDownCounter and forgetting the matching Add(-1) on failure paths. Why it is wrong: the value drifts upwards for ever. Instead: decrement in finally, or use an ObservableGauge that reads the real state.The senior move is to start with what the platform already gives you. Between ASP.NET Core, HttpClient and System.Runtime you already have rate, errors, latency, concurrency, GC and thread pool health for every service, and .NET 10 adds authentication, authorisation, Identity and Blazor meters on top. Custom metrics should be about the business (orders placed, payments declined, refunds issued), because those are the things the framework cannot know, and they are the numbers product owners will ask about in an incident. Review the list each quarter: a metric nobody has looked at in three months is cost without value, and a new business flow without a metric is a blind spot.
The second point is cost: a counter with 3 tag values is 3 series; a histogram with 15 buckets and the same tags is about 51. Add a route tag with 20 values and a status_code tag with 8 and that histogram is already 8,000+ series per service. That is fine for latency; it is not fine with a customer id tag, which turns one metric into millions of series, slows queries and multiplies the bill.
| Instrument | When it fits | Cost | When not to use it |
|---|---|---|---|
| Counter | Events you want a rate of | 1 series per tag set | Values that go down |
| Gauge / ObservableGauge | Current state you can read | 1 series per tag set | Events (you lose everything between samples) |
| UpDownCounter | In-flight work tracked by +/- | 1 series per tag set | When you can read the real value instead |
| Histogram | Latency, sizes, anything with a tail | buckets + 2 series per tag set | Plain counts; very high-cardinality tags |
The .NET diagnostics tools all talk to the runtime over its diagnostics IPC channel, so they work on Windows, Linux and in containers without a debugger.
I start with counters because they are cheap, then pick the heavier tool the symptom points to. The trade-off is overhead and data sensitivity: a full dump contains every secret in memory.
I put a feature's metrics in one singleton class that takes IMeterFactory, creates a Meter named after the component (Shop.Orders) and creates the instruments once: a Counter<long> for events such as orders placed, a Histogram<double> in seconds for durations, and an ObservableGauge<T> for current state. Names follow OpenTelemetry semantic conventions (shop.orders.placed, unit {order}), and tags are bounded (channel, outcome), never customer or order ids.
OpenTelemetry picks them up when I register the meter name with AddMeter inside WithMetrics, and the exporter (OTLP to a Collector, the Azure Monitor distro, or Prometheus) is a separate decision. I test with MetricCollector<T> from Microsoft.Extensions.Diagnostics.Testing, which captures measurements from a meter created by the same factory.
The trade-off: every tag value and histogram bucket is a time series you pay for, so I add metrics for questions someone will actually ask.
An average mixes fast and slow requests into one number that describes almost nobody. If 95 requests take 50 ms and 5 take 3 s, the average is (95 × 50 + 5 × 3,000) / 100 ≈ 198 ms, which looks fine while 1 in 20 customers waits 3 seconds. Percentiles describe the distribution: p50 is the typical request, p95/p99 is the slow tail people complain about.
Percentiles come from a histogram: count requests into buckets, then find the bucket where 99% of the count is reached and interpolate (put bucket boundaries close to your SLO threshold so the estimate is tight). Because a percentile is not additive, you cannot average p99 across pods or time windows; you merge the bucket counts first and then take the quantile, which is what histogram_quantile(0.99, sum by (le) (rate(...[5m]))) does.
The trade-off: high percentiles need enough traffic and well-chosen buckets to be trustworthy, so chart the request count next to them and alert on SLO burn rate rather than a raw p99.
Last updated 23 Nov 2026.