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

📚 Interview question

How do you profile a .NET service safely in production? Explain how you would use dotnet-monitor in containers and the Application Insights Profiler, what overhead each adds, and how you handle the security and privacy risks of traces and dumps.

Production profiling for .NET 10: dotnet-monitor as a sidecar with collection rules and egress, the Application Insights Profiler (classic SDK and the OpenTelemetry preview), overhead and blast radius, authentication, and Privacy Act obligations for diagnostic artefacts.

Senior Theory Advanced application-insights dotnet-monitor performance privacy-act production profiling

🎯 Key points

  • Prefer always-on cheap signals (metrics, distributed traces) and short targeted captures over long heavy ones
  • dotnet-monitor: sidecar or tool sharing the diagnostics socket; REST endpoints; collection rules (trigger → action → egress to Blob Storage)
  • Secure it: API key or Entra ID, internal port only, least-privilege egress identity
  • Application Insights Profiler: sampled traces tied to slow requests; classic SDK GA, OpenTelemetry profiler still preview (late 2026)
  • Overhead: counters negligible, CPU sampling a few %, gcdump a blocking full GC, full dump a process pause
  • Limit blast radius: one instance, out of rotation if heavy, time-boxed, off-peak
  • Dumps contain secrets and PII: encrypted storage in Australian region, access control, short retention, NDB awareness

⏱ 30-second answer

Safe production profiling means cheap signals always on and heavy captures rare, short and controlled.

  • Always on: runtime metrics and distributed traces through OpenTelemetry to Azure Monitor.
  • On demand: dotnet-monitor as a sidecar exposes trace, gcdump and dump endpoints over an authenticated API, with collection rules that capture automatically on a trigger (CPU, heap size, slow requests) and egress to Blob Storage.
  • Sampled continuous profiling: the Application Insights Profiler captures short traces and ties them to slow requests. The classic SDK version is GA; the OpenTelemetry-based profiler is still preview as of late 2026.

I limit blast radius to one instance, and treat dumps as production data under the Privacy Act. The trade-off is evidence versus risk: a full dump answers anything but pauses the process and copies every secret in memory.

🗣 Full answer (senior)

How I would answer this in an interview

"I split production diagnostics into three tiers. The first is always on and cheap: runtime metrics like CPU, GC heap, ThreadPool queue length and request duration, plus distributed traces, all exported with OpenTelemetry to Azure Monitor. That tells me which endpoint, which instance and which kind of problem before I touch anything. The second tier is short, targeted captures: a 30-second CPU trace or a gcdump. The third is a full memory dump, which I only take for hangs, crashes or native memory, because it pauses the process and contains everything in memory, including tokens, connection strings and customer data.

In containers I make the second tier boring by running dotnet-monitor as a sidecar. It shares the app's diagnostics socket, listens on an internal port with an API key or Entra ID authentication, and writes artefacts to a Blob Storage account in Australia East using a managed identity that can only write. Collection rules mean I don't have to be awake: 'if CPU is above 80% for two minutes, take a 30-second trace, at most once an hour'. For example, at [company] [a rule caught a 3 am CPU spike caused by a regex timeout storm, and the trace was waiting for us in the morning]. On App Service, the Application Insights Profiler does something similar out of the box: it samples for a couple of minutes at a time and links traces to slow requests, which makes it easy to say 'this request was slow because of this stack'.

The mistake I see is treating diagnostics as harmless. A dump is a copy of production memory. If it ends up on a laptop or in a ticket, that's a possible notifiable data breach. So artefacts are encrypted, access-controlled, kept in an Australian region and deleted after [14] days."


Overhead and risk by capture type

Capture Overhead Data sensitivity Typical limit
Metrics (counters, OpenTelemetry) Negligible Low Always on
Distributed traces Low, with sampling Medium (URLs, headers, SQL text) Always on, sampled
CPU sampling trace (30–60 s) A few % CPU Low to medium (method names, some event payloads) On demand or triggered, rate-limited
gcdump Blocking full GC (100s of ms to seconds) Low (types, no values) On demand, one instance
Full dump Process frozen while writing; disk = memory High (everything) Hangs/crashes only, approved

dotnet-monitor vs Application Insights Profiler

dotnet-monitor Application Insights Profiler
Where Any host: AKS, Container Apps, VMs Azure App Service, VMs, AKS with agent/SDK
What Traces, gcdumps, dumps, logs, metrics on request or by rule Periodic sampled CPU traces linked to requests
Control You define triggers and egress Mostly automatic; on-demand sessions
Status (late 2026) Supported; .NET 10 release available Classic SDK profiler GA; OpenTelemetry profiler in preview

Production example

A payments API on AKS had a p99 spike every few days that lasted five minutes. A dotnet-monitor collection rule on request duration took a trace during the next spike; it showed thread pool starvation from a sync-over-async call in a rarely used refund path. The fix removed the spikes, and the rule's cost was one 40 MB trace in Blob Storage.

🔍 What the interviewer is checking

Checks whether the candidate can get evidence from production without causing an outage or a data breach.

Green flags

  • Tiers diagnostics from cheap to heavy
  • Knows dotnet-monitor sidecar, collection rules and egress
  • States overhead of each capture type
  • Treats dumps as sensitive data with Australian storage and retention

Red flags

  • Takes full dumps by default
  • Leaves diagnostics endpoints unauthenticated
  • Says production profiling is impossible

📚 Learn in depth

1. Three tiers of production diagnostics

 Tier 1  always on     metrics + traces + logs  ──▶  Azure Monitor / Prometheus
                         │ alert
                         ▼
 Tier 2  targeted      CPU trace, gcdump         ──▶  dotnet-monitor / AI Profiler
                         │ still unexplained (hang, native, crash)
                         ▼
 Tier 3  heavy         full dump                 ──▶  approved, one instance

Each tier is more expensive and more sensitive, so you go down only as far as you need.

2. dotnet-monitor in a container

The app and dotnet-monitor must share the diagnostics socket. In Kubernetes:

 Pod
 ├─ app container        DOTNET_DiagnosticPorts=/diag/dotnet-monitor.sock
 ├─ monitor container    listens on /diag/dotnet-monitor.sock (Listen mode), :52323 API
 └─ emptyDir volume /diag shared by both

In Listen mode the runtime connects to dotnet-monitor at start-up, so the monitor works even with a read-only /tmp. Endpoints include /processes, /trace, /gcdump, /dump, /logs, /livemetrics and /metrics (Prometheus). Collection rules combine a trigger (EventCounter thresholds, AspNetRequestDuration, AspNetResponseStatus), actions (CollectTrace, CollectGCDump, CollectDump) and limits (ActionCount, SlidingWindowDuration), with egress providers such as Azure Blob Storage.

3. Application Insights Profiler

The Profiler for .NET collects short ETW/EventPipe-based traces (by default for about two minutes at a time on a schedule, plus on-demand sessions and CPU or memory triggers) and correlates them with request telemetry, so the portal shows a 'hot path' for slow operations. As of late 2026 there are two paths: the classic Application Insights SDK profiler, and the Azure Monitor OpenTelemetry Profiler for .NET, which works with the Azure Monitor OpenTelemetry Distro and Application Insights SDK 3.x but is still prerelease. Check its current status before relying on it for production.

4. Overhead in numbers

  • CPU sampling: the runtime suspends managed threads about every millisecond to walk stacks; expect a few percent CPU and some latency jitter while it runs.
  • gcdump: forces a full blocking GC; on a 4 GB heap that can be over a second.
  • Full dump: the process is suspended while memory is written; a 4 GB process writes 4 GB to disk. Liveness probes may kill the pod mid-dump unless you account for it.

5. Security and privacy

  • Authentication: dotnet-monitor requires an API key or Entra ID by default; never disable it outside a laptop.
  • Network: bind the API to localhost or an internal port; no ingress.
  • Egress identity: a managed identity with write-only access to a specific container.
  • Data: dumps can contain access tokens, connection strings and personal information. Under the Privacy Act 1988 (APP 11, security of personal information) you must protect them, and losing one could be an eligible data breach under the NDB scheme. Store in Australia East/Southeast, encrypt, restrict access, set lifecycle deletion.
  • Change control: heavy captures (full dumps) are a production change; record who took them and why.

Try it yourself

  1. Run your app and the mcr.microsoft.com/dotnet/monitor image with Docker Compose, sharing a volume and setting DOTNET_DiagnosticPorts.
  2. Call /processes and /trace?durationSeconds=30 with the API key.
  3. Add a collection rule that takes a gcdump when gc-heap-size exceeds a threshold; trigger it with a leaky endpoint.
  4. Configure Azure Blob egress with a SAS or managed identity and a lifecycle rule to delete after 14 days.
  5. Enable the Application Insights Profiler on a test App Service and find a slow request's trace in the portal.

💻 Code

A Kubernetes pod with dotnet-monitor as a sidecar, sharing the diagnostics socket. Authentication stays on (the default); the API key comes from a Kubernetes secret.

apiVersion: v1
kind: Pod
metadata:
  name: payments-api
spec:
  volumes:
    - name: diag
      emptyDir: {}
  containers:
    - name: app
      image: myregistry.azurecr.io/payments-api:1.42.0
      env:
        - name: DOTNET_DiagnosticPorts          # runtime connects to the monitor
          value: /diag/dotnet-monitor.sock
      volumeMounts:
        - { name: diag, mountPath: /diag }
    - name: monitor
      image: mcr.microsoft.com/dotnet/monitor:10
      args: ["collect"]                         # auth is on by default; never pass --no-auth here
      env:
        - name: DotnetMonitor_DiagnosticPort__ConnectionMode
          value: Listen
        - name: DotnetMonitor_DiagnosticPort__EndpointName
          value: /diag/dotnet-monitor.sock
        - name: DotnetMonitor_Urls                # internal only; no Service/Ingress
          value: http://localhost:52323
        - name: DotnetMonitor_Authentication__MonitorApiKey__Subject
          valueFrom: { secretKeyRef: { name: dotnet-monitor-apikey, key: subject } }
        - name: DotnetMonitor_Authentication__MonitorApiKey__PublicKey
          valueFrom: { secretKeyRef: { name: dotnet-monitor-apikey, key: publicKey } }
      volumeMounts:
        - { name: diag, mountPath: /diag }

Generate the key pair once with dotnet monitor generatekey; callers send the token as Authorization: Bearer <token>.

A collection rule (in dotnet-monitor's settings) that takes at most one 30-second trace per hour when CPU stays high:

{
  "CollectionRules": {
    "HighCpu": {
      "Trigger": {
        "Type": "EventCounter",
        "Settings": {
          "ProviderName": "System.Runtime",
          "CounterName": "cpu-usage",
          "GreaterThan": 80,
          "SlidingWindowDuration": "00:02:00"
        }
      },
      "Actions": [
        {
          "Type": "CollectTrace",
          "Settings": { "Profile": "Cpu", "Duration": "00:00:30", "Egress": "diagnosticsBlob" }
        }
      ],
      "Limits": { "ActionCount": 1, "ActionCountSlidingWindowDuration": "01:00:00" }
    }
  }
}

⚠ Common mistakes

  • Mistake: Optimising without measuring because 'we can't profile production'. Why it is wrong: You end up guessing at production-only problems. Instead: Set up dotnet-monitor or the Profiler in advance so a capture is routine.
  • Mistake: Micro-optimising cold paths found in a single production trace. Why it is wrong: One trace at one moment may not represent normal load. Instead: Correlate with request metrics and fix what dominates slow requests.
  • Mistake: Exposing dotnet-monitor's API without authentication or through ingress. Why it is wrong: Anyone reaching it can download a dump of production memory. Instead: API key or Entra ID, localhost or internal port only.
  • Mistake: Reaching for a full dump before cheaper captures have been tried. Why it is wrong: Process pause, huge files, maximum data exposure, often for a question a trace or gcdump would answer. Instead: Counters, traces and gcdumps first; keep full dumps for the cases that need them: hangs and deadlocks, crashes, native memory and finaliser problems.
  • Mistake: Copying dumps to laptops, tickets or chat. Why it is wrong: Uncontrolled copies of personal information; a possible notifiable data breach. Instead: Analyse in a controlled environment; encrypted storage with retention.
  • Mistake: Forgetting liveness probes during a dump. Why it is wrong: The orchestrator kills the frozen pod and you lose the dump. Instead: Take dumps on a pod taken out of rotation, or relax the probe temporarily.
  • Mistake: Unlimited collection rules. Why it is wrong: A flapping trigger fills storage and adds constant overhead. Instead: Set action counts and sliding windows.
  • Mistake: Profiling one instance and assuming it represents all of them. Why it is wrong: In a distributed system the slow requests may come from one zone, one noisy node or one tenant's data. Instead: Use distributed traces to find which instance and dependency is slow, then capture there.
  • Mistake: Assuming the OpenTelemetry-based Application Insights Profiler is GA. Why it is wrong: It is still prerelease as of late 2026. Instead: Check its status; use the classic profiler or dotnet-monitor where you need support.

🏛 Senior insight: trade-offs

The senior move is to design for diagnosability before the incident: metrics and traces always on, dotnet-monitor or the Profiler deployed and tested, egress storage and access agreed with security, and a runbook that says which capture to take for which symptom. Then a production investigation is a 5-minute capture, not a week of 'can't reproduce'. I also involve security and privacy early: once they've agreed where artefacts live and who can open them, nobody hesitates during an incident.

Option When it fits Cost When not to
dotnet-monitor sidecar AKS, Container Apps, VMs; custom triggers Extra container, config, securing the API Tiny services with no SLOs
Application Insights Profiler App Service and Azure-hosted ASP.NET Core with AI Agent/SDK, some overhead in sessions Where the OTel profiler's preview status is unacceptable
kubectl exec + CLI tools Ad-hoc, small teams Tools in the image, shell access Locked-down or distroless images
Full dump Hang, crash, native memory Pause, large sensitive file CPU or simple managed-memory questions

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the CLI diagnostics tools behind dotnet-monitor Why: Checks they know what each underlying collection captures
    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 mentions taking a full dump for a hang Why: Checks they can analyse the dump once they have it
    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 always-on metrics and traces through OpenTelemetry Why: Checks they can set up OpenTelemetry and sampling for the always-on tier
    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.

🛠 Real-world problems: how you handle them

Catching a rare p99 spike with a dotnet-monitor collection rule
Situation
A payments API on [AKS in Australia East, 8 pods] had a p99 latency spike from [250 ms] to [6 s] for about five minutes every [2–4 days], usually overnight. It couldn't be reproduced in staging.
Signals
Azure Monitor alerts on p99; Application Insights showed slow requests across all endpoints during the spike but no slow dependencies; ThreadPool thread count rose sharply in the runtime metrics.
Investigation
Because the spike was rare and short, I deployed dotnet-monitor as a sidecar with a collection rule: when AspNetRequestDuration above 2 s for more than 50 requests in a minute, collect a 60-second trace and one gcdump, at most once per 6 hours, egress to Blob Storage. Two nights later the rule fired. The trace in PerfView showed many threads blocked in Task.Wait inside a rarely used refund reconciliation job that ran on the request ThreadPool.
Resolution
Immediate: disabled the reconciliation job's schedule. Fix: made the job async end to end and moved it to a BackgroundService with bounded concurrency. Spikes stopped.
Prevention
Kept the collection rule permanently; added an analyser (VSTHRD002 / CA2012-style) for blocking calls on async code; alert on ThreadPool queue length; documented the dotnet-monitor runbook and artefact retention of [14] days in an Australian storage account.

How to tell it (STAR)

**S:** At [company] our payments API had a five-minute latency spike every few days, always overnight, and nobody could reproduce it. **T:** I needed evidence from production without waking someone at 3 am or risking customer data. **A:** I added dotnet-monitor as a sidecar with a collection rule on request duration, authenticated and writing to an Australian storage account with 14-day retention. When the rule fired, the trace showed threads blocked in Task.Wait in a refund reconciliation job. I made the job async and moved it to a background service with bounded concurrency. **R:** The spikes went from [every 2–4 days] to none in [three months], and the rule has since caught [two] other issues.

↩ Usually asked after

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me