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

πŸ“š Interview question

What are the main .NET diagnostics tools? Explain what dotnet-counters, dotnet-trace, dotnet-dump, dotnet-gcdump and dotnet-monitor each tell you, and which one you reach for first when a service misbehaves.

The .NET diagnostics CLI toolbox: what dotnet-counters, dotnet-trace, dotnet-dump, dotnet-gcdump and dotnet-monitor each capture, their overhead, and the order you use them in.

Junior Theory Beginner dotnet-counters dotnet-dump dotnet-monitor dotnet-trace performance profiling

🎯 Key points

  • dotnet-counters: live EventCounters/Meters (CPU, GC, ThreadPool queue, exceptions, alloc rate), near-zero overhead, first tool
  • dotnet-trace: EventPipe trace (CPU samples, GC, exceptions) to .nettrace, viewed in PerfView, VS or Speedscope
  • dotnet-dump: full process memory snapshot; analyse with SOS (clrstack, dumpheap, gcroot) for hangs and leaks
  • dotnet-gcdump: managed heap graph only, smaller and safer than a full dump; compare two for leaks
  • dotnet-monitor: HTTP API/sidecar that runs the same collections in containers, with triggers (CPU, memory) and egress to storage
  • All use the diagnostics IPC socket and EventPipe: work cross-platform, no debugger attach needed
  • Order: counters to find the symptom, then trace (CPU/latency) or gcdump/dump (memory, hangs)

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

πŸ—£ Full answer (senior)

How I would answer this in an interview

"All five tools sit on the same plumbing: every .NET process opens a diagnostics IPC channel, a Unix domain socket or a named pipe, and the tools use it to start EventPipe sessions or ask for a dump. That's why they work the same on Windows, Linux and inside a container, and why none of them needs a debugger attached.

I use them in a fixed order. First dotnet-counters, because it's cheap and answers 'what kind of problem is this?'. If CPU is high, I look at the ThreadPool queue and lock contention. If memory grows, I watch GC heap size and Gen 2 collections. If latency climbs with low CPU, I suspect blocking or I/O. Then I pick the specialist tool. dotnet-trace records CPU samples and runtime events into a .nettrace file I open in PerfView, Visual Studio or Speedscope to see hot call stacks. For memory I take two dotnet-gcdump snapshots and compare them, because a gcdump only holds the managed object graph and is much smaller than a full dump. dotnet-dump is the heavy one: the whole process memory, which I analyse with SOS commands like clrstack, dumpheap -stat and gcroot, mainly for hangs, deadlocks and native memory questions.

dotnet-monitor is the production version: it runs as a sidecar or tool, exposes the same collections over an authenticated HTTP API, and can collect automatically on triggers like 'CPU above 80% for a minute'. The mistake I see is people taking a full dump first. It pauses the process, can be gigabytes, and holds customer data, so it should be the last tool, not the first."


What each tool gives you

Tool Captures Overhead Typical question it answers
dotnet-counters Live metrics from System.Runtime, Microsoft.AspNetCore.Hosting, System.Net.Http, custom Meters Negligible Is it CPU, GC, ThreadPool or I/O?
dotnet-trace EventPipe events: CPU sampling, GC, exceptions, contention, custom EventSource Low to moderate (CPU sampling ~1 ms interval) Which methods burn CPU or wait?
dotnet-gcdump Managed heap graph (types, counts, sizes, references) Triggers a full blocking Gen 2 GC What is filling the heap, and who holds it?
dotnet-dump Full process memory Pauses the process; file size equals working set Why is it hung? What is on every thread's stack?
dotnet-monitor All of the above via REST, plus triggers and egress Same as the underlying collection How do I collect safely in a container?

Which one first

Symptom First Then
High CPU counters (cpu-usage, threadpool-queue-length) trace with the CPU sampling profile
Memory grows counters (gc-heap-size, gen-2-gc-count) two gcdumps, compare
Requests hang counters (ThreadPool thread count rising) dump, clrstack -all / parallelstacks
Latency up, CPU low counters (monitor-lock-contention-count, ThreadPool queue) trace with contention events

Production example

An API's memory climbed from 400 MB to 2.5 GB over a day. dotnet-counters showed the GC heap tracking the working set, so it was managed memory. Two dotnet-gcdump snapshots an hour apart showed 1.2 million extra CacheEntry objects rooted by a static dictionary with no eviction. Adding a size limit flattened memory at 450 MB.

πŸ” What the interviewer is checking

Checks that the candidate knows what each diagnostics tool captures and can pick the right one for a symptom instead of guessing.

Green flags

  • Starts with dotnet-counters and names concrete counters
  • Distinguishes gcdump (heap graph) from a full dump
  • Knows dotnet-monitor exists for containers and triggers
  • Mentions overhead and data sensitivity of dumps

Red flags

  • Only knows the Visual Studio debugger
  • Takes a full dump for every problem
  • Can't say which tool finds a CPU hot path versus a leak

πŸ“š Learn in depth

1. The diagnostics IPC channel

Every .NET Core 3.0+ process creates a diagnostics endpoint: a named pipe on Windows, and a Unix domain socket in $TMPDIR named dotnet-diagnostic-{pid}-...-socket on Linux and macOS. The diagnostics client library (Microsoft.Diagnostics.NETCore.Client) speaks a small binary protocol over it.

  dotnet-counters ─┐
  dotnet-trace   ───   diagnostics IPC    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  dotnet-gcdump  ──┼─────────────────────▢│ .NET runtime          β”‚
  dotnet-dump    ───  (socket / pipe)     β”‚  EventPipe, dump      β”‚
  dotnet-monitor β”€β”€β”˜                      β”‚  writer, GC, JIT      β”‚
                                          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

In containers the socket lives in the container's /tmp, so a sidecar must share that volume, or you set DOTNET_DiagnosticPorts to point the runtime at dotnet-monitor's listening socket.

2. EventPipe

EventPipe is the runtime's cross-platform event tracing system (the equivalent of ETW on Windows). Providers such as Microsoft-Windows-DotNETRuntime (GC, JIT, exceptions, contention) and Microsoft-DotNETCore-SampleProfiler (stack samples) write events into a buffer, which is streamed to the client.

  • dotnet-counters asks for EventCounters and System.Diagnostics.Metrics instruments at an interval (1 s by default). In .NET 8+ the built-in metrics also appear as System.Runtime meters.
  • dotnet-trace chooses profiles such as cpu-sampling (the default), gc-verbose or gc-collect, or explicit --providers.

3. Heap snapshots versus dumps

dotnet-gcdump asks the runtime to perform a full, blocking GC and emit events that describe every live object and reference. The result is a graph without object contents, so it is small and contains little sensitive data. dotnet-dump collect writes the whole address space (or a heap-only/mini dump with --type). It shows field values, native memory and every thread's stack, so it can answer anything, but it is large, pauses the process and must be treated as sensitive data under the Privacy Act's security obligations.

4. dotnet-monitor

dotnet-monitor (with a .NET 10 release) runs as a global tool or the mcr.microsoft.com/dotnet/monitor container image. It exposes /processes, /trace, /gcdump, /dump, /metrics (Prometheus format) and supports collection rules: trigger (CPU, GC heap size, request duration, exception) β†’ action (collect trace or dump) β†’ egress (Azure Blob Storage). It needs authentication (API key or Entra ID) because a dump endpoint is effectively a data-exfiltration endpoint.

5. Overhead to remember

Collection Cost
Counters Under 1% CPU
CPU sampling trace A few % CPU while running; file grows ~MB per second
gcdump A full blocking GC: seconds on a multi-GB heap
Full dump Process frozen while written; disk equal to memory

Try it yourself

  1. Install the tools: dotnet tool install -g dotnet-counters dotnet-trace dotnet-dump dotnet-gcdump.
  2. Run a sample API, generate load with k6 or bombardier, and watch dotnet-counters monitor -n MyApi --counters System.Runtime,Microsoft.AspNetCore.Hosting.
  3. Record 30 seconds with dotnet-trace collect -n MyApi --duration 00:00:30 and open the .nettrace in PerfView or convert it with --format speedscope.
  4. Add an endpoint that leaks into a static list, take two gcdumps a minute apart, and compare them in Visual Studio.
  5. Run dotnet-monitor in Docker next to your app with a shared /tmp volume and call /gcdump over HTTP.

πŸ’» Code

Typical command sequence for a misbehaving service, from cheapest to heaviest.

# 1. Find the process
dotnet-counters ps

# 2. Cheap live view: what kind of problem is it?
dotnet-counters monitor -n Orders.Api \
  --counters System.Runtime,Microsoft.AspNetCore.Hosting,System.Net.Http

# 3a. CPU or latency: record 30 s of CPU samples and runtime events
dotnet-trace collect -n Orders.Api --profile cpu-sampling --duration 00:00:30 \
  --format speedscope

# 3b. Memory growth: two heap snapshots a few minutes apart, then compare
dotnet-gcdump collect -n Orders.Api -o before.gcdump
dotnet-gcdump collect -n Orders.Api -o after.gcdump
dotnet-gcdump report after.gcdump | head -30

# 3c. Hang or deadlock: full dump, then SOS
dotnet-dump collect -n Orders.Api --type Full -o hang.dmp
dotnet-dump analyze hang.dmp
#   > clrthreads
#   > parallelstacks
#   > dumpheap -stat

A custom metric so dotnet-counters shows business signals next to runtime ones:

using System.Diagnostics.Metrics;

namespace Orders.Api.Diagnostics;

public sealed class OrderMetrics
{
    // The meter name is what you pass to dotnet-counters --counters.
    public const string MeterName = "Orders.Api";
    private readonly Counter<long> _ordersPlaced;
    private readonly Histogram<double> _pricingMs;

    public OrderMetrics(IMeterFactory meterFactory)
    {
        var meter = meterFactory.Create(MeterName);
        _ordersPlaced = meter.CreateCounter<long>("orders.placed");
        _pricingMs = meter.CreateHistogram<double>("orders.pricing.duration", unit: "ms");
    }

    public void OrderPlaced() => _ordersPlaced.Add(1);
    public void PricingTook(TimeSpan elapsed) => _pricingMs.Record(elapsed.TotalMilliseconds);
}

// Program.cs
// builder.Services.AddSingleton<OrderMetrics>();
// then: dotnet-counters monitor -n Orders.Api --counters Orders.Api

⚠ Common mistakes

  • Mistake: Optimising without measuring, guessing at the cause from the code. Why it is wrong: Most guesses are wrong and you change code that was never the bottleneck. Instead: Start with dotnet-counters to classify the problem, then collect evidence.
  • Mistake: Micro-optimising cold paths that a tool showed as 0.1% of CPU. Why it is wrong: No user will notice; it costs review time and readability. Instead: Work down the trace from the widest frames.
  • Mistake: Assuming where the time goes from the architecture diagram ("it must be the database"). Why it is wrong: In distributed systems the cost is often somewhere unexpected: serialisation, a retry loop, a lock, DNS. Instead: Let counters, traces and Application Insights dependency timings tell you.
  • Mistake: Taking a full dump first. Why it is wrong: It freezes the process, can be gigabytes and contains secrets and personal data. Instead: Counters, then trace or gcdump; full dumps only for hangs or native memory.
  • Mistake: Using a single gcdump to find a leak. Why it is wrong: One snapshot shows what is big, not what is growing, and big caches are often intentional. Instead: Compare two or three snapshots taken under the same load, then follow the reference paths of the type that grows.
  • Mistake: Relying only on 1-second counters for a problem that lasts milliseconds. Why it is wrong: Counters average away short bursts such as a single exception storm or a GC pause. Instead: Start a short dotnet-trace early when the symptom is transient.
  • Mistake: Not sharing /tmp with a diagnostics sidecar in Kubernetes. Why it is wrong: The tools can't find the diagnostics socket. Instead: Mount a shared emptyDir or set DOTNET_DiagnosticPorts.
  • Mistake: Leaving dotnet-monitor's API open without authentication. Why it is wrong: Anyone who reaches it can download a memory dump. Instead: Use an API key or Entra ID and keep it on an internal port.
  • Mistake: Copying dumps to laptops or tickets. Why it is wrong: They are copies of production data and may trigger Notifiable Data Breaches obligations if lost. Instead: Keep them in access-controlled storage with a retention period.

πŸ› Senior insight: trade-offs

Knowing the tools is junior; the senior part is choosing the cheapest tool that can answer the question and treating diagnostic artefacts as production data. These CLI tools are for the investigation, not the detection: continuous monitoring (the same runtime metrics exported through OpenTelemetry to Azure Monitor or Prometheus, with alerts on p95 latency, GC heap and ThreadPool queue length) should tell you something is wrong before users do, and give you the shape of the problem before anyone opens a terminal. I also want dotnet-monitor or an equivalent pre-installed so a trace in production is one HTTP call rather than a change request.

Counters first is a default, not a rule: when the symptom is a short burst (a 200 ms stall every few minutes), I start a dotnet-trace or a dotnet-monitor trigger straight away, because 1-second averages will hide it.

Tool When it fits Cost When not to
dotnet-counters Every investigation, first None to speak of Millisecond-scale transient events
dotnet-trace CPU, latency, contention, transient events Some CPU, large files Memory leaks (use gcdump)
dotnet-gcdump Managed memory growth Blocking full GC Native memory, hangs
dotnet-dump Hangs, deadlocks, native memory, crashes Process pause, big sensitive file Routine CPU work
dotnet-monitor Containers, automated triggers Running a sidecar, securing it A dev laptop

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions using dotnet-counters to classify the problem Why: Checks they can read CPU, GC and ThreadPool counters and turn them into a diagnosis
    How to answer

    I look at dotnet-counters (System.Runtime) next to request and dependency telemetry:

    • CPU-bound: process CPU usage sits near the cores you have and latency climbs with load. Fix: better algorithms, less work per request, caching, then profile with dotnet-trace.
    • Memory/GC-bound: high allocation rate, a high % time in GC and frequent Gen 2 collections. Fix: allocate less on hot paths (pooling, spans, streaming instead of buffering).
    • I/O-bound: CPU is low but requests are slow and dependency durations (SQL, HTTP) dominate. Fix: fewer round trips, better queries and indexes, true async I/O, caching.

    If CPU is low and the ThreadPool queue keeps growing, it's blocking (sync-over-async), not I/O capacity. The trade-off: one counter never proves it; I confirm with a profile or trace.

  2. When: Candidate mentions dotnet-dump or SOS Why: Checks they can actually analyse a production memory dump
    How to answer

    When I can't attach a debugger, I take a dump: a snapshot of the process's memory, threads and stacks that I analyse offline. For a hang or a leak, dotnet-dump collect -p <pid> does it in seconds. For crashes, I enable automatic crash dumps with the DOTNET_DbgEnableMiniDump environment variables. On App Service I use Diagnose and solve problems, and in Kubernetes dotnet-monitor. Then I analyse with dotnet-dump analyze: clrstack -all and syncblk for hangs, dumpheap -stat and gcroot for leaks, pe for exceptions. Or I open the dump in Visual Studio and use the Threads and Parallel Stacks windows. Dumps contain customer data, so they're handled as sensitive.

  3. When: Candidate mentions dotnet-trace or the Visual Studio profiler Why: Checks they can go from a slow endpoint to the cause with these tools
    How to answer

    First I measure: Application Insights tells me which endpoint is slow and at what percentile, and whether time goes into dependencies like SQL or HTTP. Then I reproduce it on a Release build and run the Visual Studio Performance Profiler (Alt+F2): CPU Usage for hot paths, Database for query count and duration, .NET Object Allocation Tracking for GC pressure, and .NET Async for slow awaits. In an environment where I can't use Visual Studio, dotnet-counters shows live metrics like thread pool queue length and GC, and dotnet-trace captures CPU samples. I fix the biggest cause, often an N+1 query, re-measure against the baseline, and add a load test so it doesn't regress.

↩ Usually asked after

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me