Quality & GrowthComplete guide

Performance

Performance engineering turns user and capacity goals into measurable budgets, diagnoses bottlenecks, and validates improvements under realistic load.

Overview

Performance engineering begins with a user, business, or capacity objective and an explicit budget for latency percentiles, throughput, errors, resource use, and cost. Always-on metrics reveal saturation and regressions; distributed traces locate critical-path time; profiles identify CPU and allocation hotspots; database plans expose I/O; BenchmarkDotNet isolates repeatable code paths; and production-shaped load tests show queuing, contention, dependency limits, and failure behavior. The highest-value improvements usually eliminate unnecessary network or database work, bound concurrency and queues, reduce payloads, batch calls, choose appropriate caching, and remove allocations only from proven hot paths. Release builds, realistic inputs, steady-state warmup, multiple runs, confidence intervals, and environmental notes keep evidence honest. An optimization is incomplete until correctness, tail latency, memory, throughput, cost, rollback, and post-deployment telemetry show improvement without shifting the bottleneck or weakening reliability.

What you will learn

  • Translate user and capacity goals into latency, throughput, error, resource, and cost budgets.
  • Choose metrics, traces, profiles, benchmarks, and load tests for distinct questions.
  • Diagnose queuing, saturation, I/O, contention, allocation, GC, and thread-pool problems.
  • Build statistically useful BenchmarkDotNet experiments with realistic inputs and release settings.
  • Optimize the measured constraint while preserving correctness and reliability.
  • Verify performance in production-shaped deployment and prevent regressions.

Prerequisites

  • Asynchronous .NET, HTTP and database I/O, memory allocation, and concurrency basics.
  • Metrics, traces, logs, release builds, and automated tests.
  • A .NET 10 SDK to run the telemetry parser benchmarks.

When to use Performance

Good fit

  • Use production telemetry to locate the user-visible or capacity constraint before creating a benchmark.
  • Use BenchmarkDotNet for isolated repeatable code paths and load tests for end-to-end concurrency.
  • Use profiles when you need evidence of where CPU time, allocation, locks, or I/O is spent.

Choose another approach when

  • Do not optimize from intuition, averages, debug builds, or one stopwatch result.
  • Do not trade correctness, security, maintainability, or resilience for an unmeasured micro-gain.
  • Do not use a microbenchmark to claim whole-system scalability.
  • Do not leave caches, queues, concurrency, payloads, or cardinality unbounded.

Key concepts

Latency and percentiles

Median describes typical response while tail percentiles reveal slow experiences hidden by averages.

Throughput and saturation

Work per interval must be understood beside queues, CPU, memory, connections, and dependency capacity.

Allocation and GC

Allocation rate and object lifetime influence collection frequency, pauses, and memory footprint.

Measurement

Benchmarks isolate code; load tests evaluate systems; profiles locate time and allocation in realistic paths.

Critical path

End-to-end latency follows dependent work, so optimizing parallel or non-critical work may not change the user outcome.

Queuing and contention

Locks, pools, thread starvation, and arrival rates can create nonlinear tail latency before CPU reaches 100 percent.

Benchmark validity

Warmup, release compilation, realistic data, consumed results, isolated noise, and statistical distributions make measurements credible.

Performance budgets

A measurable SLO and resource envelope turns optimization into an acceptance decision rather than an endless activity.

Architecture

A request budget is consumed across edge, application, cache, database, and network calls, all observed through correlated telemetry.

Client budget
Application
Cache / database
Telemetry evidence

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated sample starts with an allocation-heavy string-splitting parser, preserves its contract in tests, introduces a span-based implementation, and measures both through BenchmarkDotNet with MemoryDiagnoser. On the measured machine the span path was about 0.69 times the mean latency and eliminated the baseline's 208-byte allocation, but the sample records that results are environment-specific.

  1. 01
    Define the objective

    Choose the user journey, percentile, throughput, resource, error, and cost target.

  2. 02
    Capture a baseline

    Record representative production telemetry, environment, workload, and current result before editing code.

  3. 03
    Locate the constraint

    Follow traces and profiles through queues, application code, database, cache, network, and downstream dependencies.

  4. 04
    Protect correctness

    Add parity and edge-case tests so an optimization cannot silently change behavior.

  5. 05
    Create the experiment

    Use BenchmarkDotNet or a production-shaped load test with realistic inputs and controlled variables.

  6. 06
    Evaluate tradeoffs

    Compare distribution, allocation, throughput, saturation, error, readability, and operational cost.

  7. 07
    Deploy and guard

    Roll out safely, compare real telemetry, retain rollback, and add a regression budget.

Code example

Cache-aside can remove repeated I/O, but the cache must be bounded, observable, and allowed to miss safely.

ProductCache.cs
public async Task<ProductDto?> FindAsync(Guid id, CancellationToken ct)
{
    var key = $"product:{id}";
    if (cache.TryGetValue(key, out ProductDto? cached))
        return cached;

    var product = await database.Products
        .AsNoTracking()
        .Where(x => x.Id == id)
        .Select(x => new ProductDto(x.Id, x.Name, x.Price))
        .SingleOrDefaultAsync(ct);

    if (product is not null)
        cache.Set(key, product, TimeSpan.FromMinutes(2));
    return product;
}

Testing strategy

Performance evidence sits beside functional tests; it never replaces them.

  • Prove baseline and optimized implementations return identical results for representative and invalid inputs.
  • Run BenchmarkDotNet in Release without a debugger and consume return values.
  • Use several iterations and report distribution, runtime, hardware, GC mode, and allocations.
  • Load-test concurrency, ramp, steady state, burst, dependency slowdown, and recovery.
  • Set regression thresholds only after understanding environment noise and statistical variance.
  • Re-run production telemetry after deployment to confirm the end-to-end objective.

Security considerations

Performance controls are also availability controls and must not expose sensitive diagnostic data.

  • Bound requests, concurrency, queues, caches, result sets, fan-out, and expensive operations.
  • Authorize diagnostic endpoints and protect dumps, traces, profiles, query plans, and benchmark inputs.
  • Do not remove validation, cryptography, tenant isolation, or audit evidence for speed.
  • Redact secrets and personal data from profiling artifacts and high-cardinality labels.
  • Threat-model cache poisoning, algorithmic complexity, decompression, regex, and resource-exhaustion paths.

Performance and scalability

Optimize in descending order of measured end-to-end impact.

  • Eliminate unnecessary work and round trips before micro-optimizing syntax.
  • Batch or parallelize only independent work within downstream capacity and cancellation bounds.
  • Use pooling and spans only where profiles show allocation or copying is material.
  • Tune GC, thread pool, connection pools, and server limits only with workload evidence.
  • Track P50, P95, P99, throughput, errors, saturation, allocation rate, heap, GC pauses, and queue time together.

Deployment and operations

Hardware, runtime, containers, proxies, databases, and neighboring workloads change performance behavior.

  • Match architecture, runtime, GC mode, CPU and memory limits, database scale, and network path to production.
  • Warm caches and JIT deliberately or include cold behavior in the objective.
  • Use canary or staged rollout and compare the same metrics against a baseline cohort.
  • Set alerts on user SLOs and saturation rather than one host metric.
  • Keep benchmark reports, load models, dashboards, rollback, and capacity assumptions versioned.

Common problems and fixes

Average latency is healthy but users time out.

Likely cause: Tail percentiles or a subset of operations are slow.

Fix: Segment normalized operations and inspect P95 and P99 traces plus queue time.

CPU is low while latency rises.

Likely cause: The service is waiting on I/O, locks, pools, queues, or thread starvation.

Fix: Correlate traces, counters, thread stacks, connection pools, and dependency latency.

A benchmark changes dramatically between runs.

Likely cause: Debugging, thermal or power state, background load, JIT, input, or insufficient iterations differ.

Fix: Use BenchmarkDotNet, stable release conditions, multiple runs, and report variance.

Memory grows under sustained load.

Likely cause: An unbounded cache or queue, retained object graph, or slow consumer accumulates work.

Fix: Capture counters and a memory profile, then bound and backpressure the owning structure.

An optimization improves benchmark time but not the API.

Likely cause: The optimized code is not the end-to-end constraint.

Fix: Return to the critical-path trace and target database, network, queue, or dominant work.

Throughput plateaus and errors rise.

Likely cause: A finite dependency, pool, CPU, lock, or quota has saturated.

Fix: Find the first saturated resource, apply admission control, and scale or reduce work there.

Best practices

  • Define user and capacity budgets with representative workloads before optimization.
  • Trace the critical path and inspect database and downstream work before micro-optimizing C#.
  • Track percentiles, errors, throughput, saturation, allocation, queue time, and cost together.
  • Benchmark Release builds with realistic inputs, warmup, consumed results, and reported environment.
  • Protect behavioral parity and security before comparing performance.
  • Bound concurrency, queues, caches, payloads, results, and fan-out.
  • Validate isolated improvements through production-shaped load and canary telemetry.
  • Keep evidence, capacity assumptions, rollback, and regression budgets versioned.

Production checklist

  • User and capacity objectives define percentile, throughput, error, resource, and cost budgets.
  • Representative baseline telemetry and workload are captured.
  • Critical-path traces and profiles identify the actual constraint.
  • Correctness and security parity tests protect every optimization.
  • Benchmarks use Release, realistic inputs, warmup, consumed results, allocations, and reported environment.
  • Load tests cover ramp, steady state, burst, degradation, and recovery.
  • Queues, concurrency, caches, payloads, results, and cardinality are bounded.
  • Canary telemetry, alerts, capacity assumptions, rollback, and regression gates are ready.

Common interview questions

Why are percentiles better than average latency alone?

Averages hide the distribution. P95 or P99 reveal tail experiences that often dominate timeouts and user dissatisfaction.

When can caching make a system worse?

It adds invalidation, staleness, memory, stampede, and consistency concerns; low reuse or oversized keys can cost more than the saved work.

What is the difference between a benchmark and a load test?

A benchmark isolates a code path under controlled conditions. A load test exercises a system under concurrency and dependency constraints.

Why can low CPU coexist with high latency?

Requests may be waiting on database or network I/O, locks, queues, thread-pool work, or exhausted connection pools rather than executing on CPU.

What makes a microbenchmark trustworthy?

Release compilation, warmup, representative inputs, consumed outputs, isolated conditions, multiple measurements, allocation evidence, and a recorded runtime and machine.

What is coordinated omission in load testing?

A load generator waits for slow responses and therefore sends less work during stalls, undercounting the latency users would experience at the intended arrival rate.

How do you know an optimization succeeded?

Correctness remains intact and production-shaped evidence improves the target budget without unacceptable regressions in tails, errors, resources, cost, or maintainability.

What is a performance budget?

It is an explicit acceptable limit for a user or capacity outcome such as P95 latency, throughput, memory, CPU, allocation, database calls, payload size, or cost.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Performance Telemetry Parser

A .NET 10 measurement sample comparing allocation-heavy string splitting with a span parser through behavior tests and BenchmarkDotNet latency and allocation evidence.

.NET 10BenchmarkDotNetSpan<T>xUnit
dedicated-samplebenchmarkallocationprofilingcorrectness-testing
Run
dotnet run -c Release --project benchmarks/TelemetryParser.Benchmarks -- --filter *
Test
dotnet test PerformanceTelemetryParser.slnx