Introduction
In this final lesson, we will combine the performance techniques covered throughout the course in one practical project. Using the shared e-commerce API, we will create a measurable test plan, run load and stress tests, inspect endpoint-level throughput, latency, and error rate, and observe CPU, memory, and database behavior. We will then classify whether a bottleneck belongs to the application code, EF Core queries, SQL Server, the cache layer, or network communication.
The goal is not simply to find the lowest average response time. A real optimization effort must consider p95 and p99 latency, error rate, resource consumption, and system behavior as load increases. One change may reduce average latency while increasing memory usage or database pressure. For that reason, every optimization should be validated with a before-and-after comparison under the same scenario and conditions.
Do not optimize before measuring, and do not assume success until you measure again after the change.
1. Load testing, stress testing, and success criteria
Load testing examines whether the application can handle expected or target traffic while maintaining an acceptable response time and error rate. For example, a target for the product listing endpoint might be a p95 latency below 400 milliseconds with 100 concurrent clients.
Stress testing pushes the system beyond normal operating limits. The number of concurrent requests is gradually increased, sudden traffic spikes are introduced, or resources such as CPU and memory are constrained. The purpose is not only to find when the application becomes slow, but also to observe whether it recovers after failure and returns controlled errors.
Example target table
| Endpoint | p95 target | Minimum throughput | Allowed error rate |
|---|---|---|---|
GET /api/products | 400 ms | 250 requests/sec | Less than 1% |
GET /api/products/{id} | 250 ms | 300 requests/sec | Less than 0.5% |
POST /api/orders | 700 ms | 80 requests/sec | Less than 1% |
These values are examples, not universal rules. Targets should be based on the application’s workload, hardware, database, network topology, and business requirements. If success criteria are not written before testing begins, results tend to become subjective.
2. Stabilizing the test environment
Comparable results require the same build configuration, database volume, cache state, and, as far as possible, machine conditions. Running load tests in Debug or Development mode can produce misleading results. Use a Release build, production-like settings, and a controlled logging level.
- Publish the API in Release mode:
dotnet publish -c Release. - Prepare the test database using a deterministic seed.
- Record whether the cache is cold or warm for every test run.
- Do not run the load generator on the same machine as the API; otherwise, client resource usage can affect the results.
- Record the application version, Git commit, .NET version, machine characteristics, and database version.
If Redis or another distributed cache is used, test cache-hit and cache-miss scenarios separately. A successful warm-cache result may hide the cost of the first request or the cost of generating cache keys and serialized payloads.
3. Creating a simple load-test client
The following example sends a controlled number of GET requests without an external load-testing tool. It is not a production-grade load-testing platform; it demonstrates scenario execution and basic metric collection for the course project.
using System.Diagnostics;
var endpoint = "https://localhost:7043/api/products?page=1&pageSize=20";
var totalRequests = 2_000;
var maxConcurrency = 50;
var results = new List<RequestResult>();
var gate = new SemaphoreSlim(maxConcurrency);
var tasks = Enumerable.Range(0, totalRequests).Select(async _ =>
{
await gate.WaitAsync();
var stopwatch = Stopwatch.StartNew();
try
{
using var client = new HttpClient();
using var response = await client.GetAsync(endpoint);
stopwatch.Stop();
return new RequestResult(response.IsSuccessStatusCode, stopwatch.Elapsed);
}
catch
{
stopwatch.Stop();
return new RequestResult(false, stopwatch.Elapsed);
}
finally
{
gate.Release();
}
});
results.AddRange(await Task.WhenAll(tasks));
var successful = results.Where(x => x.Success).Select(x => x.Duration.TotalMilliseconds).OrderBy(x => x).ToArray();
var errors = results.Count(x => !x.Success);
var p95 = successful.Length == 0 ? 0 : successful[(int)(successful.Length * 0.95) - 1];
Console.WriteLine($"Requests: {results.Count}");
Console.WriteLine($"Errors: {errors}");
Console.WriteLine($"Error rate: {(double)errors / results.Count:P2}");
Console.WriteLine($"P95: {p95:N0} ms");
record RequestResult(bool Success, TimeSpan Duration);Creating a new HttpClient for every request is intentionally simple here, but it is not a good general practice. A real load generator should reuse an HttpClient instance or use IHttpClientFactory. The load generator must not accidentally represent connection setup overhead as API processing time.
Throughput can be calculated by dividing the total number of requests by the test duration. However, average throughput alone is not enough. Also inspect the percentage of requests exceeding the target, the slowest requests, and the distribution of status codes and failures.
4. Telemetry and endpoint-level measurement
ASP.NET Core built-in metrics help monitor request duration, active requests, Kestrel connections, and other signals. For first-level investigation, use dotnet-counters to observe the running process:
dotnet-counters monitor --process-id 12345 \
--counters Microsoft.AspNetCore.Hosting,System.RuntimeThe key indicators include:
- Throughput: The number of requests or operations completed per second.
- Latency: The time required to complete a request. Evaluate p50, p95, and p99 together instead of relying only on the mean.
- Error rate: The percentage of 4xx, 5xx, timeout, and connection errors.
- CPU: Sustained high CPU may indicate application code, serialization, compression, or expensive SQL-related work.
- Memory and GC: Track working set, allocation rate, and garbage-collection activity.
- Database: Measure query duration, connection wait time, active connections, and lock waits.
For application-specific metrics, use Meter and Histogram. Histograms are generally more useful than averages when analyzing latency distributions.
using System.Diagnostics.Metrics;
public static class PerformanceMetrics
{
public static readonly Meter Meter = new("Store.Api");
public static readonly Histogram<double> OrderDuration =
Meter.CreateHistogram<double>("store.order.duration", "ms");
}Record the measurement when the operation completes and attach a low-cardinality label such as operation name or endpoint group. Avoid unbounded tag values such as user IDs, unique URLs, or order numbers because they can increase the cost of the metrics system.
5. Classifying bottlenecks by layer
When an endpoint is slow, blaming the database immediately is not a reliable diagnosis. The following classification helps organize evidence.
| Symptom | Possible layer | Areas to inspect |
|---|---|---|
| High CPU, low SQL duration | Application | Serialization, mapping, compression, unnecessary loops |
| High SQL duration, moderate CPU | EF Core / SQL Server | Generated SQL, execution plan, indexes, N+1 queries |
| Latency rises after cache misses | Cache | TTL, key design, Redis connection, payload size |
| Active connections and waits increase | Database or network | Pool size, connection leaks, network latency |
| Application is fast but client is slow | Network | Response size, compression, TLS, proxy behavior |
For example, suppose product listing takes 900 ms while SQL Server reports that the query takes only 100 ms. Adding an index alone may not change the result significantly. The remaining time may be spent on JSON serialization, a large response, cache deserialization, or network transfer. Measure each layer’s contribution before changing code.
6. Building a before-and-after report
For the final project, compare at least three states: the baseline version, individual optimizations, and the final version containing the combined optimizations. Use the same request profile for every run.
| Scenario | RPS | P50 | P95 | P99 | Errors | CPU | Allocation |
|---|---|---|---|---|---|---|---|
| Baseline | 120 | 210 ms | 760 ms | 1.4 sec | 2.1% | 78% | 18 MB/sec |
| Projection + pagination | 205 | 130 ms | 390 ms | 720 ms | 0.8% | 64% | 10 MB/sec |
| Final cache + compression | 310 | 82 ms | 230 ms | 460 ms | 0.3% | 69% | 8 MB/sec |
The values above are examples; replace them with measurements from your application. The report should not contain only a statement such as “the API became 60% faster.” Include test duration, concurrency, data volume, cache state, database conditions, and failure categories.
7. Adding performance regression tests with BenchmarkDotNet
Load tests measure end-to-end behavior, while BenchmarkDotNet is useful for comparing small, repeatable code paths. For example, you can compare allocation behavior for two ways of mapping product entities to DTOs.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<MappingBenchmark>();
public class MappingBenchmark
{
private readonly Product[] products =
Enumerable.Range(1, 100).Select(id => new Product(id, $"Product {id}", 10m)).ToArray();
[Benchmark]
public ProductDto[] MapWithSelect() =>
products.Select(x => new ProductDto(x.Id, x.Name, x.Price)).ToArray();
[Benchmark]
public List<ProductDto> MapWithLoop()
{
var result = new List<ProductDto>(products.Length);
foreach (var product in products)
result.Add(new ProductDto(product.Id, product.Name, product.Price));
return result;
}
}
public record Product(int Id, string Name, decimal Price);
public record ProductDto(int Id, string Name, decimal Price);Do not look only at the Mean column. Standard deviation, allocated memory, and allocation per operation are also important. Enable MemoryDiagnoser when you need allocation data. Run benchmarks outside Debug mode, and record environment information when comparing results across machines or runtime versions.
Defining an exact threshold for every benchmark in a CI pipeline requires care. Hardware and virtualization differences can create small variations. First define a tolerance range; for example, consider a regression when p95 benchmark duration becomes more than 10% worse. Fail the build for large regressions and report smaller variations as warnings that require review.
8. Common mistakes
- Relying on average latency: The average can hide a small number of very slow requests. Track p95 and p99 as well.
- Testing in Debug or Development mode: Detailed logging and unoptimized builds can distort results.
- Running only one iteration: JIT compilation, cache warm-up, network noise, and system activity require repeated runs.
- Ignoring the load generator: Client CPU usage or new connection setup can make the API appear slower than it is.
- Not recording cache state: Cold-cache and warm-cache results should not be mixed in one comparison.
- Looking only at success rate: An API that succeeds 100% of the time but misses its latency target is not necessarily performant.
- Changing code for every suspected bottleneck: Validate the hypothesis with measurements before introducing complexity.
Short practice exercise
Complete the following final project:
- Define one success criterion for the product listing endpoint and one for order creation.
- Run at least 2,000 requests at three different concurrency levels using a Release build.
- Record throughput, p50, p95, p99, and error rate for each endpoint.
- Collect CPU, working set, GC, SQL duration, active connections, and cache-hit rate during the tests.
- Classify the largest bottleneck by layer and apply one measurement-driven optimization.
- Run the same test again and prepare a before-and-after report.
- Add at least one small BenchmarkDotNet benchmark to detect an allocation or execution-time regression.
Conclusion
Performance optimization is not a one-time code cleanup; it is a continuous process of measurement and validation. A good API does not merely respond quickly. It behaves predictably as load increases, uses resources efficiently, handles failures in a controlled way, and protects performance improvements with automated tests.
Throughout this course, you studied async/await, EF Core queries, projections, pagination, caching, compression, connection pooling, and memory management separately. The final project shows that their real value cannot be evaluated without measurable goals and controlled tests. In future projects, begin with a hypothesis, collect the right metrics, make the smallest useful change, and rerun the same scenario to verify the result.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/test/load-tests?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/metrics/overview?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/metrics/http?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-counters
- https://benchmarkdotnet.org/Configs/Diagnosers.htm