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

📚 Interview question

How do you CPU-profile a .NET service with dotnet-trace? Explain how sampling works, how you read a flame graph or call tree in PerfView, Speedscope or Visual Studio, the difference between inclusive and exclusive time, and how you go from a hot frame to a fix.

CPU profiling .NET 10 services: EventPipe stack sampling with dotnet-trace, flame graphs and call trees in PerfView, Speedscope and Visual Studio, inclusive vs exclusive time, wall-clock vs CPU time, and turning a hot path into a verified fix.

Mid-Level Theory Intermediate cpu dotnet-trace flame-graph performance perfview profiling

🎯 Key points

  • dotnet-trace cpu-sampling uses EventPipe's SampleProfiler: managed threads' stacks roughly every 1 ms, low enough overhead for production
  • Statistical: short or rare events can be missed; capture 30–60 s under representative load
  • Flame graph: width = share of samples, y = call depth, x order is merged/alphabetical not chronological
  • Inclusive time = method plus callees; exclusive (self) time = the method's own code
  • Read top-down from your entry point, then bottom-up by self time
  • Samples include waiting threads, and awaiting async requests hold no thread: separate CPU work from waits
  • Combine with counters (classify) and distributed traces (async I/O latency)
  • Fix the hot frame, then re-profile and benchmark to verify the width shrank

⏱ 30-second answer

dotnet-trace with the default cpu-sampling profile uses EventPipe's sample profiler: roughly every millisecond it records each managed thread's call stack. Aggregated, those samples become a call tree or flame graph, where a frame's width is the share of samples it appears in.

I read it top-down from my entry point to find the wide paths, then bottom-up by exclusive (self) time to find the methods that actually burn CPU.

  • Inclusive time: the method and everything it calls.
  • Exclusive time: just its own code.

A wide frame is not always CPU work: EventPipe also samples threads that are waiting on a lock or I/O, and an awaiting async request holds no thread, so it doesn't appear at all. I cross-check with dotnet-counters and distributed traces. The trade-off: sampling is cheap enough for production but statistical, so short events can be missed; I capture under real load for 30–60 seconds and verify fixes with a second profile.

🗣 Full answer (senior)

How I would answer this in an interview

"CPU profiling in .NET is statistical sampling. When I run dotnet-trace collect --profile cpu-sampling, the runtime's sample profiler suspends managed threads roughly every millisecond and records their stacks. Nothing is instrumented, so overhead is a few percent, and the result is a .nettrace file of thousands of stacks. A method that appears in 30% of samples was on the stack 30% of the time.

I look at it two ways. Top-down, as a call tree or flame graph starting from the request entry point, I follow the widest tower: which controller, which service, which call inside it. Bottom-up, sorted by exclusive time, I see which methods have their own code on the CPU, which often points straight at something like Regex construction, JSON serialisation or a LINQ Contains over a list. For example, at [company] [a pricing endpoint spent 38% of its samples in Regex..ctor because a pattern was built per call]; making it a static, source-generated regex cut CPU by [a third].

The mistake I see is reading every wide frame as CPU work. EventPipe samples blocked threads too, so Monitor.Enter or WaitHandle.WaitOne can look 'hot' when the thread is just waiting. I check that against dotnet-counters: if CPU is low and the wide frames are waits, it's a contention or I/O problem, not a compute one. And I always re-profile after the fix: the frame should get narrower, and p95 or CPU per request should move."


Reading the views

View Shows Use it to
Flame graph (Speedscope 'Left Heavy', VS) Merged stacks; width = samples Spot the widest paths fast
Call tree (PerfView CallTree, VS) Inclusive % per node, expandable Walk down from your entry point
By name / bottom-up (PerfView ByName, VS Functions) Exclusive % per method Find the code doing the work
Caller/callee Who calls a hot method Decide which caller to change
Time order (Speedscope 'Time Order') Samples over time per thread Find bursts, stalls and GC pauses

Inclusive vs exclusive

Inclusive Exclusive
Counts Method + all callees Method's own instructions
High value means This path is expensive This method itself is expensive
Typical example OrderController.Get 80% Dictionary.FindValue 12%

Tools

Tool Strength
PerfView Deepest analysis, grouping and folding, diffing two traces; Windows
Speedscope (--format speedscope) Browser-based flame graphs, any OS
Visual Studio Performance Profiler Opens .nettrace, CPU Usage tool, hot path highlighting
perf + perfcollect on Linux Native frames and kernel time too

Production example

An order-search API ran at 70% CPU on four instances. A 60-second trace under load showed 31% of samples under System.Text.Json serialising a 400-field entity the client never used, and 12% exclusive in Enumerable.Contains over a List<int>. Projecting to a 12-field DTO and switching to a HashSet<int> cut CPU to 35%, and the next trace showed both frames under 3%.

🔍 What the interviewer is checking

Checks that the candidate can capture a CPU profile and correctly interpret it, not just name the tool.

Green flags

  • Explains sampling and what width means
  • Distinguishes inclusive from exclusive time
  • Knows wait frames and async gaps can mislead
  • Verifies a fix with a second profile and a metric

Red flags

  • Reads the flame graph's x axis as time
  • Profiles in Debug or at idle
  • Jumps to code changes without confirming the frame is CPU-bound

📚 Learn in depth

1. How sampling works

 every ~1 ms
   │
   ▼
 SampleProfiler suspends managed threads ──▶ walks each stack ──▶ writes a sample event
   │                                                         (thread id, frames)
   └── resumes threads

 thousands of samples ──▶ aggregated by identical stack ──▶ call tree / flame graph

It is statistical: with 1 ms sampling, 60 seconds and 20 busy threads you get about a million samples, which is plenty for anything above 1%. Short, rare events are under-represented; use event-based tracing for those.

2. CPU time vs wall-clock time

EventPipe's sample profiler records managed threads whether they are running or waiting, so its tree is closer to wall-clock (thread) time. Tools differ:

  • PerfView groups blocked time under frames like BLOCKED_TIME only with ETW/kernel data on Windows; with EventPipe you recognise waits by method names (Monitor.Enter, SemaphoreSlim.Wait, Task.Wait, socket receive).
  • Visual Studio's CPU Usage tool shows CPU time from OS sampling; its Thread/Events views show waits.
  • On Linux, perf (via perfcollect) gives real on-CPU samples including native and kernel frames.

Async code adds a twist: an awaiting request has no thread, so time spent awaiting I/O doesn't appear at all. For async latency, use distributed traces (Application Insights, OpenTelemetry) and dotnet-trace's activity events, not CPU samples.

3. Reading a flame graph

|               Kestrel request (100%)                                   |
|          OrderController.Search (82%)                    | Logging 9% |
| OrderService.Find (35%)      | JsonSerializer.Serialize (41%)        |
| EF query (20%) | List.Contains 12% | WriteProperties ... (38%)       |
  • y axis: depth of the stack; the root is at the top or bottom depending on tool.
  • x axis: sorted (often alphabetically) for merging; not time.
  • Wide plateaus at the top of a tower = high self time = optimisation candidates.

4. Symbols, frames and noise

  • Managed frames are resolved from the runtime's own method events; you don't need PDBs for method names, but you do for line numbers.
  • Inlined methods vanish into their callers; disable inlining only in experiments ([MethodImpl(MethodImplOptions.NoInlining)]).
  • Group framework frames (PerfView 'GroupPats', VS 'Just My Code') to see your code, then ungroup when the cost is inside the framework.
  • Exclude startup: start the trace after warm-up so JIT doesn't dominate.

5. From hot frame to fix

  1. Confirm the frame is CPU work, not waiting.
  2. Find the caller you own (caller/callee view).
  3. Ask: can it be avoided (cache, precompute), done less (batch, hash set), or done cheaper (source-generated regex/JSON, spans)?
  4. Benchmark the change with BenchmarkDotNet.
  5. Re-profile under the same load; compare traces (PerfView can diff two stacks views).

Try it yourself

  1. Build an endpoint that does list.Contains in a loop, load it with k6, and capture dotnet-trace collect -n App --duration 00:00:30 --format speedscope. Find the frame in speedscope.app.
  2. Open the same trace in PerfView, compare CallTree (inclusive) and ByName (exclusive).
  3. Add an endpoint that blocks on Task.Delay(100).Wait() and see how it looks in the samples compared with real CPU work.
  4. Fix the hot path, re-capture and use PerfView's diff to show the change.

💻 Code

Capturing a CPU profile from a running service and a container, and the kind of fix a profile typically leads to.

# Local or VM: 60 s of CPU samples once the service is warm and under load
dotnet-trace collect -n Search.Api --profile cpu-sampling \
  --duration 00:01:00 -o search.nettrace

# View in a browser on any OS
dotnet-trace convert search.nettrace --format speedscope   # open in speedscope.app

# Kubernetes: run the tool inside the pod (or use dotnet-monitor's /trace endpoint)
kubectl exec -it search-api-7d9f -- /tools/dotnet-trace collect -p 1 --duration 00:00:30
kubectl cp search-api-7d9f:/app/trace.nettrace ./trace.nettrace

The profile showed Regex..ctor and List<int>.Contains as wide self-time frames. Before and after:

using System.Text.RegularExpressions;

namespace Search.Api;

public sealed partial class SkuFilter
{
    // BEFORE (hot in the profile): new Regex per call, O(n) Contains per item
    // public bool IsAllowed(string sku, List<int> blockedIds) =>
    //     new Regex(@"^[A-Z]{3}-(\d+)$").Match(sku) is { Success: true } m
    //     && !blockedIds.Contains(int.Parse(m.Groups[1].Value));

    // AFTER: source-generated regex built once at compile time,
    // O(1) lookups in a FrozenSet built at start-up.
    [GeneratedRegex(@"^[A-Z]{3}-(\d+)$")]
    private static partial Regex SkuPattern();

    private readonly System.Collections.Frozen.FrozenSet<int> _blocked;

    public SkuFilter(IEnumerable<int> blockedIds) =>
        _blocked = System.Collections.Frozen.FrozenSet.ToFrozenSet(blockedIds);

    public bool IsAllowed(string sku) =>
        SkuPattern().Match(sku) is { Success: true } m
        && !_blocked.Contains(int.Parse(m.Groups[1].ValueSpan));
}

⚠ Common mistakes

  • Mistake: Optimising without measuring, picking code that 'looks slow'. Why it is wrong: Intuition about hot paths is usually wrong in large services. Instead: Profile under realistic load and start from the widest frames.
  • Mistake: Micro-optimising cold paths found in a trace at 0.5%. Why it is wrong: Even removing them entirely saves 0.5%. Instead: Fix the top two or three frames, then re-profile.
  • Mistake: Reading the x axis of a flame graph as time. Why it is wrong: Frames are merged and sorted; order means nothing. Instead: Use the time-order view for 'when'.
  • Mistake: Treating wide wait frames as CPU work. Why it is wrong: EventPipe samples blocked threads; making a lock-holder 'faster' may not help. Instead: Check CPU counters and recognise wait methods.
  • Mistake: Profiling a debug build or the first seconds after start-up. Why it is wrong: You see JIT, Tier 0 code and start-up work. Instead: Release build, warm process, steady load.
  • Mistake: A 5-second capture at idle. Why it is wrong: Too few samples and the wrong workload. Instead: 30–60 seconds under representative traffic.
  • Mistake: Looking only at inclusive time. Why it is wrong: The top of the tree is always 100%; it doesn't tell you which code to change. Instead: Switch to exclusive time to find the real worker.
  • Mistake: Expecting a CPU profile to explain async latency. Why it is wrong: Awaiting requests hold no thread and don't appear in samples. Instead: Use distributed tracing for I/O waits.

🏛 Senior insight: trade-offs

CPU profiles answer 'where does CPU go?', which is only one of the questions behind 'it's slow'. I decide which question I have first, from the symptom, and pick the tool to match. Mixing these up is how teams spend a week optimising serialisation when the real cost was a lock. I also keep the evidence: the before and after traces and the CPU-per-request metric go in the PR, so reviewers can see the change did what it claimed.

Symptom Tool Why
High CPU per request dotnet-trace cpu-sampling Shows the hot managed code
Low CPU, high latency, threads rising Contention events, ThreadPool counters, dump of stacks The time is waiting, not computing
Slow async I/O calls Application Insights / OpenTelemetry traces Awaits hold no thread, so samples miss them
High CPU in native or kernel code perf via perfcollect (Linux) Sees native and kernel frames
Memory growth dotnet-gcdump A CPU profile can't show retention
Approach When it fits Cost When not to
dotnet-trace sampling High CPU, hot code paths Few % CPU, 100s of MB files Async I/O latency
perf / perfcollect (Linux) Native, kernel or JIT-generated code Needs perf installed and permissions Quick managed-only checks
Visual Studio profiler Local repro, rich UI Needs a dev machine or the trace file Production containers directly
Application Insights Profiler Always-on sampled traces tied to requests Agent and data residency review Detailed one-off investigations

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions other diagnostics tools such as dotnet-counters or dotnet-gcdump Why: Checks they know which tool fits which symptom
    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 wide frames can be threads waiting on a lock Why: Checks they can diagnose lock contention with counters and contention events
    How to answer

    Throughput that plateaus with spare CPU points at threads waiting, not working. I confirm with dotnet-counters: monitor-lock-contention-count (the dotnet.monitor.lock_contentions metric) climbing with load. Then I find which lock with dotnet-trace using the contention events (--clrevents contention), which record the waiting stack and duration, or a dotnet-dump where clrstack -all shows dozens of threads in Monitor.Enter on the same object.

    Fixes, in order: shrink the critical section and never hold a lock across I/O; replace it with ConcurrentDictionary, Interlocked or an immutable snapshot swapped atomically; or shard the lock per key. Then I verify with the same load test. The trade-off: lock-free designs are harder to get right, so I take the simplest one that removes the contention.

  3. When: Candidate mentions the Visual Studio Performance Profiler Why: Checks they can run a full slow-endpoint investigation end to end
    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.

🛠 Real-world problems: how you handle them

A per-call Regex and an O(n) lookup burning 40% of CPU on a search API
Situation
A product search API on [Azure App Service, 4 × P2v3 instances in Australia East] served [~1,500 requests/s] at peak. CPU sat at [70–80%] and the team was about to scale out to 8 instances.
Signals
Application Insights showed p95 at [420 ms] with no slow dependencies; App Service CPU metrics high on every instance; dotnet-counters showed cpu-usage at 75%, low ThreadPool queue, normal GC.
Investigation
Because CPU was high and dependencies fast, I captured a 60-second dotnet-trace cpu-sampling profile on one instance under peak load and opened it in PerfView and Speedscope. Bottom-up by exclusive time: Regex..ctor and the regex interpreter at [24%], List<int>.Contains at [12%]. Caller/callee showed both inside SkuFilter.IsAllowed, called per product per request.
Resolution
Immediate: none needed beyond holding the scale-out. Fix: a source-generated static regex and a FrozenSet<int> built at start-up; BenchmarkDotNet showed IsAllowed going from [2.1 µs and 1.1 KB] to [90 ns and 0 B]. After release, a second trace showed both frames under 2%.
Prevention
A performance test stage running the search scenario in Azure Load Testing with a CPU-per-request budget; analyser rules for Regex construction in loops (SYSLIB1045 suggests GeneratedRegex); a quarterly profiling session on the top 5 endpoints.

How to tell it (STAR)

**S:** At [company] our search API was running at [75%] CPU at peak and we were about to double the instance count. **T:** I wanted to know where the CPU actually went before we paid for more servers. **A:** I captured a 60-second dotnet-trace under peak load and read it bottom-up in PerfView. Two frames stood out: a Regex built on every call and a List.Contains inside a loop, together about [36%] of samples. I replaced them with a source-generated regex and a FrozenSet, proved it with BenchmarkDotNet, and re-profiled after release. **R:** CPU dropped to [38%], p95 fell from [420 ms] to [240 ms], and we cancelled the scale-out, saving about [$X a month].

↩ Usually asked after

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me