Advertisement

Diagnostics & Performance interview questions and answers

16 Diagnostics & Performance interview questions for .NET roles, each with a model answer, examples and likely follow-ups.

16 questions
Advertisement

16 questions

Q11 Advanced Save

How would you profile and reduce excessive garbage collection pauses affecting application latency?

Start by using dotnet-counters or a gcdump/trace to confirm GC is actually the bottleneck (high gen-0/gen-1 collection frequency, or notable gen-2/full GC pause times), then investigate allocation hotspots via a trace analyzed in PerfView or Visual Studio's allocation profiler to find code paths allocating excessively (often boxing, unnecessary intermediate collections, or large object heap allocations) -- common fixes include reducing allocations in hot paths (using Span<T>, object pooling, or avoiding LINQ in tight loops), and for latency-sensitive apps, considering Server GC's SustainedLowLatency mode or tuning GC settings.
// Reducing allocations in a hot path using object pooling
private static readonly ObjectPool<StringBuilder> _pool =
    new DefaultObjectPoolProvider().Create<StringBuilder>();

public string BuildMessage() {
    var sb = _pool.Get();
    try {
        sb.Append("...");
        return sb.ToString();
    } finally {
        sb.Clear();
        _pool.Return(sb);
    }
}
Real-world example
A latency-sensitive trading application reduces p99 response time significantly after profiling reveals excessive gen-0 allocations from creating new StringBuilder instances on every request, fixed by adopting an ObjectPool to reuse instances instead.
Likely follow-ups
  • What is SustainedLowLatency GC mode and when is it appropriate?
  • How does the Large Object Heap (LOH) affect GC pause characteristics differently from the normal heap?
Memory Management & Garbage Collection CLR & Runtime
Q12 Intermediate Save

What is the purpose of health check response caching and how does frequent health check polling itself impact application performance?

Health checks, if not designed carefully, can themselves become a performance concern under frequent polling (e.g., a Kubernetes liveness probe hitting the endpoint every few seconds) -- especially if a health check performs an expensive operation like a full database query on every invocation, so it's common to cache health check results for a short period or design checks to be lightweight (a simple connectivity ping rather than a full query) to avoid the diagnostic mechanism itself becoming a load concern.
builder.Services.AddHealthChecks()
    .AddCheck<DatabaseHealthCheck>("database", tags: new[] { "ready" });

// A well-designed health check avoids expensive operations:
public class DatabaseHealthCheck : IHealthCheck {
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct) {
        await _db.Database.CanConnectAsync(ct);  // cheap connectivity check, not a full query
        return HealthCheckResult.Healthy();
    }
}
Real-world example
A team discovers their Kubernetes liveness probe polling every 5 seconds was inadvertently generating significant additional database load because the health check performed a full table scan query instead of a lightweight connectivity check.
Likely follow-ups
  • How would you cache health check results to reduce polling overhead?
  • What's the right balance between health check thoroughness and its own performance cost?
Health Checks & Readiness/Liveness Probes Entity Framework Core & Data Access
Q13 Advanced Save

How does distributed tracing correlate a single logical request across multiple microservices, and what is a 'trace context' propagated between them?

Distributed tracing assigns a unique trace ID to a request when it first enters the system, propagated forward via HTTP headers (following the W3C Trace Context standard: traceparent header) to every downstream service call, with each service creating its own 'span' (a timed unit of work) tagged with that shared trace ID -- an observability backend then reconstructs the full request timeline by linking all spans sharing the same trace ID, letting you visualize exactly how long each hop in a multi-service call chain took.
// W3C traceparent header automatically propagated by OpenTelemetry instrumentation
// traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
//              version-traceId-------------------------spanId----------flags

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation());
// HttpClient calls automatically propagate the traceparent header to downstream services
Real-world example
A distributed trace reveals that a single user-facing API request spent 200ms in the API gateway, 50ms in an order service, and a surprising 1800ms in a downstream inventory service call, immediately pinpointing exactly where to focus optimization effort.
Likely follow-ups
  • What is a 'span' versus a 'trace' in distributed tracing terminology?
  • How does trace sampling reduce overhead in high-throughput systems?
gRPC Services Microservices & Distributed Architecture Patterns
Q14 Intermediate Save

What is the Large Object Heap (LOH), and why do objects larger than 85,000 bytes behave differently in the garbage collector?

Objects 85,000 bytes or larger are allocated on the Large Object Heap, a separate heap segment managed differently from the normal small-object heap -- LOH objects are collected only during gen-2 (full) collections and, historically, the LOH was never compacted (leading to potential fragmentation), though modern .NET can optionally compact it. Frequently allocating and discarding large objects (like large arrays or buffers) can cause LOH fragmentation and more frequent expensive full GCs, making techniques like buffer pooling (ArrayPool<T>) particularly valuable for large, frequently-allocated objects.
// This large array allocation goes to the LOH (>= 85,000 bytes)
byte[] largeBuffer = new byte[100_000];

// Better: rent from a pool instead of repeatedly allocating large arrays
byte[] pooledBuffer = ArrayPool<byte>.Shared.Rent(100_000);
try { /* use it */ }
finally { ArrayPool<byte>.Shared.Return(pooledBuffer); }
Real-world example
An image-processing service handling large byte array buffers switches from `new byte[]` allocations to ArrayPool<byte>.Shared.Rent/Return, significantly reducing LOH fragmentation and full GC frequency under sustained high throughput.
Likely follow-ups
  • How do you enable LOH compaction, and what's its performance cost when triggered?
  • What's the threshold and how was 85,000 bytes specifically chosen?
Memory Management & Garbage Collection CLR & Runtime
Q15 Beginner Save

What is the Diagnostics IPC channel, and how do diagnostic tools like dotnet-trace connect to a running .NET process without a debugger?

Every .NET process exposes a diagnostics IPC (inter-process communication) channel automatically at startup (a named pipe on Windows, a Unix domain socket on Linux/macOS), which diagnostic tools like dotnet-trace, dotnet-counters, and dotnet-dump connect to in order to send commands and receive data -- this out-of-process design means diagnostics can be performed on a live production process without attaching an invasive debugger or restarting the application.
Example

# List processes with an active diagnostics IPC channel dotnet-trace ps # Connect to a specific process and start collecting dotnet-trace collect --process-id 1234

Real-world example
An operations team runs dotnet-trace ps to discover all currently running .NET processes across a shared server, then attaches diagnostics to a specific one experiencing issues, all without any prior instrumentation or restart.
Likely follow-ups
  • How is the diagnostics IPC channel secured against unauthorized access?
  • What happens if a process was started before diagnostics tools existed on the machine?
Diagnostics & Performance CLR & Runtime
Q16 Advanced Save

What are the main strategies for optimizing performance in a .NET application?

Performance optimization in .NET generally spans four areas: reducing memory pressure (preferring struct over class for small, frequently-used data since structs avoid heap allocation, and using Span<T>/Memory<T> to work with large data without extra allocations); embracing asynchronous programming so I/O-bound work like database queries and API calls doesn't block threads; optimizing database access (AsNoTracking() for read-only Entity Framework queries, selecting only needed columns via projection, proper indexing); and caching frequently-accessed data via MemoryCache, the newer HybridCache (.NET 9+), or a distributed cache like Redis to avoid redundant, repeated work.
// Optimized EF Core query: only fetches the Name column, not entire User objects
var names = dbContext.Users.Select(u => u.Name).ToList();

// In-memory caching to avoid repeating an expensive operation
var cache = new MemoryCache(new MemoryCacheOptions());
cache.Set("key", expensiveResult, TimeSpan.FromMinutes(10));
Real-world example
A slow product-listing endpoint is sped up significantly by combining three of these techniques at once: adding AsNoTracking() to its read-only EF Core query, projecting only the specific fields the UI actually needs, and caching the resulting list in Redis for 60 seconds to absorb repeated identical requests.
Likely follow-ups
  • How do you use a profiler to identify which specific optimization actually matters for a given application?
  • What's the risk of over-applying caching to data that changes frequently?
Diagnostics & Performance Caching (In-Memory Distributed & Redis)

Showing 11–16 of 16