Covers writing custom metrics with Meter, IMeterFactory, Counter<T>, Histogram<T> and ObservableGauge<T>, naming and unit conventions, bounded tags, histogram bucket advice, exporting via OpenTelemetry (OTLP, Azure Monitor, Prometheus) and testing with MetricCollector<T>.
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.
"I start by deciding what question the metric answers, because that picks the instrument. 'How many orders per minute, by channel?' is a counter. 'How long does payment authorisation take?' is a histogram. 'How many orders are waiting for fulfilment right now?' is an observable gauge.
In code I put those in one class per feature, say
OrderMetrics, registered as a singleton. Its constructor takesIMeterFactory, which is the .NET 8+ way to create meters through DI: the factory owns the meter's lifetime and lets tests get an isolated meter. I create the instruments once there. Names follow OpenTelemetry conventions, lowercase and dotted, likeshop.orders.placedandshop.payment.duration, with the unit in the unit argument,sfor durations and{order}for counts, rather than baked into the name. Tags are the part I'm strict about: channel has three values, outcome has three, payment method has five. Never a customer id, order id or email, because each unique value is a new time series and also a privacy problem. For the histogram I useInstrumentAdviceto set bucket boundaries around our SLO, so p95 against a 500 ms target is accurate.Exporting is configuration:
AddMeter("Shop.Orders")insideWithMetrics, plusUseAzureMonitor()orAddOtlpExporter(). WithoutAddMeternothing is collected, which is the most common 'my metric is missing' bug. For tests I useMetricCollector<T>: arrange the class with a realIMeterFactoryfrom a service collection, run the code, and assert the measurement value and its tags.The mistake I see is metrics sprinkled through handlers with
new Meter(...)everywhere. One class per feature makes them discoverable, testable and reviewable for cardinality."
| Question | Instrument | Example name | Unit |
|---|---|---|---|
| How many, how fast? | Counter<long> |
shop.orders.placed |
{order} |
| How long, how big? | Histogram<double> |
shop.payment.duration |
s |
| How many right now (readable)? | ObservableGauge<int> |
shop.orders.awaiting_fulfilment |
{order} |
| How many in flight (tracked)? | UpDownCounter<long> |
shop.exports.active |
{export} |
| Exporter | Package | Model | Use when |
|---|---|---|---|
| OTLP | OpenTelemetry.Exporter.OpenTelemetryProtocol |
Push to a Collector | Vendor-neutral, Kubernetes, many back ends |
| Azure Monitor distro | Azure.Monitor.OpenTelemetry.AspNetCore |
Push to Application Insights | Azure-first teams; UseAzureMonitor() |
| Prometheus | OpenTelemetry.Exporter.Prometheus.AspNetCore |
Scrape /metrics |
Prometheus pull model (check the package's release status) |
| Console | OpenTelemetry.Exporter.Console |
stdout | Local debugging only |
We added shop.payment.duration with tags provider (3 values) and outcome (success, declined, error). Within a week it showed one provider's p95 at 2.1 s against 400 ms for the others, during Australian business hours only. That became a contract conversation with the provider and a routing rule that cut checkout p95 by 35%, and the whole metric cost 3 × 3 × 17 ≈ 150 series.
Checks that the candidate can write correct, cheap, testable custom metrics and knows how they reach a back end.
Green flags
IMeterFactory and creates instruments onceAddMeter is needed and how to test with MetricCollector<T>Red flags
new Meter() inside a request handlerOrderMetrics (singleton)
│ IMeterFactory.Create("Shop.Orders")
▼
Meter ── Counter<long> / Histogram<double> / ObservableGauge<int>
│ Add() / Record() (no-op until someone listens)
▼
MeterListener(s): OpenTelemetry MeterProvider | dotnet-counters | MetricCollector (tests)
│ aggregation per tag set, export every 60 s (OTLP default)
▼
Exporter ──► Collector / Azure Monitor / Prometheus
Recording is cheap when nobody listens: an instrument with no enabled listener returns almost immediately. When OpenTelemetry listens, each Add or Record finds the aggregation slot for that tag combination (a lock-free lookup) and updates it. Allocation-free recording needs up to three tags passed as KeyValuePair arguments or a TagList struct (which holds up to eight inline).
Before .NET 8 you wrote static readonly Meter s_meter = new("Shop.Orders"). That works, but every test in the process shares the same static meter, so parallel tests see each other's measurements. IMeterFactory (registered by AddMetrics(), which ASP.NET Core calls for you) creates meters scoped to the DI container: a test builds its own container and gets its own meter instance with the same name. The factory also disposes meters with the container.
OpenTelemetry semantic conventions: lowercase, dot-separated namespaces (shop.payment.duration), the unit in UCUM form in the unit field (s, ms, By, {request}), and no unit or type suffix in the name. The Prometheus exporter adds suffixes for you: shop.payment.duration with unit s becomes shop_payment_duration_seconds_bucket, _sum and _count. Counters get _total.
The default OpenTelemetry boundaries are designed for milliseconds (0 to 10,000). If you record seconds, almost everything lands in the first bucket and percentiles are useless. Fix it in one of two places:
InstrumentAdvice<double> { HistogramBucketBoundaries = [...] } (.NET 9+), which every listener can honour.AddView("shop.payment.duration", new ExplicitBucketHistogramConfiguration { Boundaries = [...] }), which overrides the advice.Or use base-2 exponential histograms (Base2ExponentialBucketHistogramConfiguration) where the back end supports them.
The OTLP exporter defaults to cumulative temporality and a 60-second export interval (OTEL_METRIC_EXPORT_INTERVAL). The Azure Monitor exporter sends delta values. Prometheus scrapes cumulative values on its own schedule. Short-lived processes (Functions, jobs) must flush on shutdown or the last interval is lost; the host does this when the MeterProvider is disposed.
MetricCollector<T> subscribes a MeterListener to one instrument (by meter name and instrument name, scoped to a factory) and stores every measurement with its tags and timestamp. You can assert LastMeasurement, or GetMeasurementSnapshot() for all of them. For observable instruments call RecordObservableInstruments() first.
OrderMetrics class below to a minimal API and watch it with dotnet-counters monitor --counters Shop.Orders.AddMeter call and confirm nothing reaches the OTLP or console exporter.MetricCollector<T> test below and run it in parallel with another test that records to the same meter name.Add(1, tag1, tag2) against Add(1, new KeyValuePair<string, object?>[] { ... }) with BenchmarkDotNet and [MemoryDiagnoser].A feature metrics class, its registration, and a unit test.
// OrderMetrics.cs
namespace Shop.Orders;
using System.Diagnostics;
using System.Diagnostics.Metrics;
public sealed class OrderMetrics
{
public const string MeterName = "Shop.Orders";
private int _awaitingFulfilment;
private readonly Counter<long> _placed;
private readonly Histogram<double> _paymentDuration;
public OrderMetrics(IMeterFactory meterFactory)
{
var meter = meterFactory.Create(MeterName);
_placed = meter.CreateCounter<long>(
"shop.orders.placed", unit: "{order}", description: "Orders accepted.");
// Buckets around our 500 ms payment SLO so p95 is accurate (.NET 9+ advice API)
_paymentDuration = meter.CreateHistogram(
"shop.payment.duration", unit: "s", description: "Payment authorisation time.",
tags: null,
advice: new InstrumentAdvice<double> { HistogramBucketBoundaries = [0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1, 2, 5] });
meter.CreateObservableGauge(
"shop.orders.awaiting_fulfilment", () => Volatile.Read(ref _awaitingFulfilment), unit: "{order}");
}
// Bounded tags only. KeyValuePair overloads (up to 3 tags) do not allocate.
public void OrderPlaced(string channel) =>
_placed.Add(1, new KeyValuePair<string, object?>("channel", channel));
public void PaymentCompleted(string provider, string outcome, TimeSpan elapsed) =>
_paymentDuration.Record(elapsed.TotalSeconds,
new KeyValuePair<string, object?>("provider", provider),
new KeyValuePair<string, object?>("outcome", outcome));
public void SetAwaitingFulfilment(int count) => Volatile.Write(ref _awaitingFulfilment, count);
}
// Program.cs
using OpenTelemetry.Metrics;
using Shop.Orders;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<OrderMetrics>();
builder.Services.AddOpenTelemetry()
.ConfigureResource(r => r.AddService("orders-api"))
.WithMetrics(m => m
.AddAspNetCoreInstrumentation()
.AddMeter(OrderMetrics.MeterName) // without this, nothing is exported
.AddOtlpExporter()); // or .UseAzureMonitor() on the builder with the distro
var app = builder.Build();
app.MapPost("/orders", (PlaceOrder cmd, OrderMetrics metrics) =>
{
metrics.OrderPlaced(cmd.Channel);
return Results.Accepted();
});
app.Run();
public sealed record PlaceOrder(string Channel);
// OrderMetricsTests.cs (xUnit, Microsoft.Extensions.Diagnostics.Testing)
namespace Shop.Orders.Tests;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.Metrics.Testing;
using Xunit;
public sealed class OrderMetricsTests
{
[Fact]
public void OrderPlaced_records_one_order_with_channel_tag()
{
using var services = new ServiceCollection().AddMetrics().BuildServiceProvider();
var factory = services.GetRequiredService<IMeterFactory>();
var metrics = new OrderMetrics(factory);
using var collector = new MetricCollector<long>(factory, OrderMetrics.MeterName, "shop.orders.placed");
metrics.OrderPlaced("web");
var m = Assert.Single(collector.GetMeasurementSnapshot());
Assert.Equal(1, m.Value);
Assert.Equal("web", m.Tags["channel"]);
}
}
AddMeter("Shop.Orders"). Why it is wrong: OpenTelemetry only listens to meters you name, so the metric silently never leaves the process. Instead: register every custom meter name, ideally from a constant on the metrics class.InstrumentAdvice or a view with suitable boundaries.payment_duration_ms. Why it is wrong: it clashes with exporters that add unit suffixes and with the conventions dashboards expect. Instead: put the unit in the unit argument and prefer seconds.Meter and asserting on it in parallel tests. Why it is wrong: tests see each other's measurements and become flaky. Instead: IMeterFactory from a per-test service provider plus MetricCollector<T>.KeyValuePair overloads (up to three tags) or TagList.http.server.request.duration already exists with route and status tags. Instead: keep custom metrics for business events.Custom metrics are an API: names, units and tags are a contract with every dashboard, alert and SLO built on them. Renaming a metric breaks those silently, so I treat a metric rename like a breaking change, review new metrics in PRs for cardinality, and keep them in one class per feature.
Also check whether something already exists before writing it: ASP.NET Core, HttpClient, EF Core, SqlClient and the runtime already publish request, dependency and runtime metrics. Custom metrics should describe the business.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
Custom Meter metrics |
Business events, domain durations | Series per tag set; code to maintain | Request and runtime data already published |
| Log-based metrics (KQL over logs) | Rare events, ad-hoc questions | Ingestion per GB, slow queries | High-volume counts or alerting at 1-minute resolution |
| Span metrics from traces (Collector connector) | RED per operation without code | Collector config; sampled traces skew counts | When you sample heavily before the connector |
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.
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
Cardinality is the number of unique label combinations; each is a separate time series. A user_id label multiplies a metric's series by the number of active users, and on a histogram that is again multiplied by every bucket, so 20 routes × 5 status codes × 17 buckets × 50,000 users is 85 million series.
I confirm it with prometheus_tsdb_head_series (or the Azure Monitor workspace's active series and ingestion metrics), find the metric with topk(10, count by (__name__) ({__name__=~".+"})), and the label with count(count by (user_id) (...)). I stop the bleeding without a deploy by dropping the label in the OpenTelemetry Collector or with Prometheus labeldrop, then remove the tag in code and move per-user questions to traces and logs.
The trade-off: per-user detail is real value, but metrics are the wrong place for unbounded data.
How to tell it (STAR)
**S:** Checkout conversion at [company] dropped by [x]% and our dashboards couldn't explain it because outbound latency was only broken down by host. **T:** I needed to find out whether payments were the cause. **A:** I added a payment duration histogram with provider and outcome tags, buckets around our 500 ms target, and tests with MetricCollector. Within days the p95 by provider showed one at 2.1 seconds in the afternoons. We shifted traffic with a feature flag, then built routing on recent p95 and took the numbers to the provider. **R:** Checkout p95 fell 35% and conversion recovered to [baseline], for about 150 extra time series.
Last updated 23 Nov 2026.