📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you would add custom business metrics to a .NET 10 service with System.Diagnostics.Metrics: create a Meter, a Counter<T> and a Histogram<T>, choose names, units and tags, export them with OpenTelemetry, and prove in a unit test that they are recorded.

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>.

Mid-Level Coding Intermediate imeterfactory metrics observability opentelemetry system-diagnostics-metrics unit-testing

🎯 Key points

  • Meter created through IMeterFactory (not a static Meter) in a singleton metrics class
  • Instruments created once in the constructor, never per call
  • OpenTelemetry naming: lowercase dotted names, unit in the unit field (s, By, {order})
  • Bounded tags only: channel, outcome, payment method; never ids or emails
  • Custom metrics for business events; request, dependency and runtime metrics are already built in
  • InstrumentAdvice sets histogram buckets near the SLO (added in .NET 9, current in .NET 10)
  • AddMeter('Shop.Orders') in WithMetrics, then an OTLP, Azure Monitor or Prometheus exporter
  • MetricCollector<T> from Microsoft.Extensions.Diagnostics.Testing asserts measurements

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 takes IMeterFactory, 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, like shop.orders.placed and shop.payment.duration, with the unit in the unit argument, s for 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 use InstrumentAdvice to set bucket boundaries around our SLO, so p95 against a 500 ms target is accurate.

Exporting is configuration: AddMeter("Shop.Orders") inside WithMetrics, plus UseAzureMonitor() or AddOtlpExporter(). Without AddMeter nothing is collected, which is the most common 'my metric is missing' bug. For tests I use MetricCollector<T>: arrange the class with a real IMeterFactory from 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."


Choosing the instrument

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}

Exporters

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can write correct, cheap, testable custom metrics and knows how they reach a back end.

Green flags

  • Uses IMeterFactory and creates instruments once
  • Explains units and naming conventions
  • Talks about tag cardinality and privacy unprompted
  • Knows AddMeter is needed and how to test with MetricCollector<T>

Red flags

  • new Meter() inside a request handler
  • Customer or order ids as tags
  • Durations recorded as gauges or averages

📚 Learn in depth

1. The moving parts

OrderMetrics (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).

2. Why IMeterFactory

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.

3. Naming, units and descriptions

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.

4. Histogram buckets

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:

  • At the instrument with InstrumentAdvice<double> { HistogramBucketBoundaries = [...] } (.NET 9+), which every listener can honour.
  • At the SDK with a view: AddView("shop.payment.duration", new ExplicitBucketHistogramConfiguration { Boundaries = [...] }), which overrides the advice.

Or use base-2 exponential histograms (Base2ExponentialBucketHistogramConfiguration) where the back end supports them.

5. Temporality and export interval

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.

6. Testing

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.

Try it yourself

  1. Add the OrderMetrics class below to a minimal API and watch it with dotnet-counters monitor --counters Shop.Orders.
  2. Remove the AddMeter call and confirm nothing reaches the OTLP or console exporter.
  3. Record seconds into a histogram without advice and look at the bucket counts in the console exporter; then add advice and compare.
  4. Write the MetricCollector<T> test below and run it in parallel with another test that records to the same meter name.
  5. Benchmark Add(1, tag1, tag2) against Add(1, new KeyValuePair<string, object?>[] { ... }) with BenchmarkDotNet and [MemoryDiagnoser].

💻 Code

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"]);
    }
}

⚠ Common mistakes

  • Mistake: Forgetting 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.
  • Mistake: Creating instruments inside the method that records them. Why it is wrong: repeated creation is slow and can produce duplicate instruments. Instead: create them once in the singleton's constructor.
  • Mistake: Customer id, order id or email as a tag. Why it is wrong: unbounded cardinality multiplies series and cost, and it puts personal information into a metrics store with no access controls designed for it (APP 11). Instead: bounded tags; ids belong in traces and logs.
  • Mistake: Recording seconds with the default millisecond buckets. Why it is wrong: everything falls in the first bucket, so percentiles are meaningless. Instead: set InstrumentAdvice or a view with suitable boundaries.
  • Mistake: Units in the name, such as 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.
  • Mistake: Using a static 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>.
  • Mistake: Passing tags as a new array on every call on a hot path. Why it is wrong: it allocates per measurement and adds GC pressure. Instead: use the KeyValuePair overloads (up to three tags) or TagList.
  • Mistake: Building a custom request-duration metric. Why it is wrong: http.server.request.duration already exists with route and status tags. Instead: keep custom metrics for business events.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is unsure when to use a gauge versus an UpDownCounter. Why: Checks the fundamentals behind the instrument choice.
    How to answer

    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.

  2. When: Candidate mentions UseAzureMonitor or the OTLP exporter. Why: Checks they understand the whole OpenTelemetry set-up, not just metrics.
    How to answer

    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.

  3. When: Candidate says ids must never be tags. Why: Checks they can diagnose and fix a cardinality explosion when someone else adds one.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Payment provider tail latency surfaced by one custom histogram
Situation
A checkout service at [company] using [three] payment providers, about [50,000] orders a day; checkout conversion had dropped and nobody knew why.
Signals
Built-in `http.client.request.duration` showed slower outbound calls but only by host, mixed with other traffic; product reported lower conversion in [afternoons]; no alert fired.
Investigation
Added `shop.payment.duration` with `provider` and `outcome` tags and SLO-aligned buckets. In Grafana, `histogram_quantile(0.95, sum by (le, provider) (rate(shop_payment_duration_seconds_bucket[5m])))` showed one provider at 2.1 s p95 against 400 ms for the others, worst between 1 pm and 5 pm AEST. Application Insights dependency data matched.
Resolution
Immediately shifted a share of traffic away from the slow provider with a feature flag. Long term, added a provider routing rule based on recent p95 and raised it with the provider under the contract's SLA.
Prevention
Standard: every external business dependency gets a duration histogram with provider and outcome tags; PR checklist for metric cardinality; `MetricCollector<T>` tests on each metrics class; alert on payment p95 SLO burn rate paging the payments on-call with a runbook.

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.

↩ Usually asked after

More in Metrics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me