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

📚 Interview question

What is the difference between a counter, a gauge and a histogram? Give an example of each from a .NET 10 web API, and tell me which metrics ASP.NET Core and the .NET runtime already publish for you before you write any code.

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.

Junior Theory Beginner aspnet-core dotnet-counters metrics observability opentelemetry system-diagnostics-metrics

🎯 Key points

  • Counter: monotonic total, you chart its rate (requests/s, orders placed)
  • Gauge: current value that goes up and down (queue length, active connections, memory)
  • Histogram: distribution of measurements in buckets, gives p50/p95/p99 (request duration)
  • UpDownCounter vs Gauge: add/subtract deltas vs record the current value (Gauge<T> since .NET 9)
  • Observable* instruments are callbacks read at collection time
  • Built-in: http.server.request.duration, http.server.active_requests, kestrel.active_connections, http.client.request.duration
  • System.Runtime meter (.NET 9+): dotnet.gc.collections, dotnet.gc.pause.time, dotnet.thread_pool.queue.length, dotnet.exceptions
  • See them live with dotnet-counters monitor before adding custom metrics

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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) or ObservableGauge<T> for current values read on a callback, and Histogram<T>. The good news is that a lot is already there. ASP.NET Core publishes http.server.request.duration as a histogram with route, method and status code tags, plus http.server.active_requests. Kestrel publishes connection metrics, HttpClient publishes http.client.request.duration, and since .NET 9 the System.Runtime meter 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 with dotnet-counters monitor before 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."


The three instrument types

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>

Built-in metrics worth knowing (.NET 10)

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows which instrument fits which question, and knows the metrics .NET already publishes instead of reinventing them.

Green flags

  • Explains that counters are charted as rates and histograms as percentiles
  • Names http.server.request.duration and the System.Runtime meter
  • Mentions dotnet-counters or OpenTelemetry to see the metrics
  • Raises tag cardinality without being asked

Red flags

  • Thinks a gauge is just a counter that can decrease, with no idea of sampling
  • Averages durations into a single number
  • Would write custom request metrics before checking the built-in ones

📚 Learn in depth

1. What a metric is

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

2. Counters and rates

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.

3. Gauges: synchronous vs observable

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

4. Histograms and buckets

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.

5. How .NET publishes metrics

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.

6. Older APIs you may still meet

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.

Try it yourself

  1. Run any ASP.NET Core 10 app and dotnet-counters monitor -n MyApi --counters Microsoft.AspNetCore.Hosting,System.Runtime. Send load with bombardier or k6 and watch the values.
  2. Add Thread.Sleep(200) to an endpoint and watch dotnet.thread_pool.queue.length under load.
  3. Create a Counter<long> and an ObservableGauge<int> and view them with dotnet-counters monitor --counters Your.Meter.
  4. Export to the console with the OpenTelemetry console exporter and look at the histogram buckets in the output.
  5. Kill and restart the app while Prometheus scrapes it, and check that rate() handles the counter reset.

💻 Code

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

⚠ Common mistakes

  • Mistake: Storing a running total of requests in a gauge. Why it is wrong: restarts and multiple instances make the values meaningless and you cannot compute a rate. Instead: use a Counter<long> and let the backend apply rate().
  • Mistake: Recording average request time as a gauge. Why it is wrong: the average hides the slow tail and cannot be combined across instances. Instead: record each duration in a Histogram<double>.
  • Mistake: Writing custom request-count and duration metrics. Why it is wrong: ASP.NET Core already publishes http.server.request.duration with route and status tags. Instead: enable AddAspNetCoreInstrumentation() and add custom metrics only for business events.
  • Mistake: Mixing units, such as milliseconds in one histogram and seconds in another. Why it is wrong: dashboards and SLOs compare the wrong numbers. Instead: follow OpenTelemetry semantic conventions: durations in seconds, unit: "s".
  • Mistake: Putting user ids or order ids in tags. Why it is wrong: every unique value creates a new time series and the cost explodes. Instead: tag with bounded values (route, status class, channel); put ids in traces and logs.
  • Mistake: Creating a new 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.
  • Mistake: Using 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions dotnet-counters to view the metrics. Why: Checks they know the wider diagnostics toolset and when metrics are not enough.
    How to answer

    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.

    • dotnet-counters shows live metrics (CPU, GC heap size, allocation rate, ThreadPool queue length, exceptions) with almost no overhead. It tells you what kind of problem you have.
    • dotnet-trace records an EventPipe trace with CPU samples and runtime events; it tells you where time goes.
    • dotnet-gcdump captures the managed heap graph (types, sizes and references). Comparing snapshots shows what is growing; the reference paths show what keeps it alive. dotnet-dump captures the whole process for SOS analysis of hangs and native memory.
    • dotnet-monitor wraps all of this as an HTTP API or sidecar with triggers, which is how you use them in Kubernetes or Container Apps.

    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.

  2. When: Candidate says custom metrics should be about the business. Why: Checks they can go from concept to working, testable code.
    How to 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.

  3. When: Candidate says histograms give you p95 and p99. Why: Checks they understand what a histogram is for.
    How to answer

    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.

↩ Usually asked after

More in Metrics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me