LESSON 1 OF 13

Project Foundation, Performance Goals, and Measurement Fundamentals

Create the shared e-commerce Web API with .NET 10, EF Core, and SQL Server; establish the layered structure and record baseline measurements.

75 dk 59

Introduction

Performance optimization is not a matter of changing a few random lines of code. You must first observe the running application, define measurable goals, and verify where the bottleneck actually exists. In this lesson, we will create the shared e-commerce Web API used throughout the course. The project will be based on ASP.NET Core Web API, .NET 10, Entity Framework Core, and SQL Server.

We will not implement caching, pagination, or query optimization in depth yet. Instead, we will prepare a consistent baseline that can be measured before and after each later change. We will separate the application into layers, create a basic product endpoint, test it through Swagger or an OpenAPI-based UI, and record initial observations with Stopwatch, logging, HTTP measurements, and dotnet-counters.

1. Why performance must be measured

It is not enough to say that an endpoint is “fast.” You must define how fast it should be, under which request load, with how much data, and on what environment. A product endpoint might return in 40 milliseconds on a development laptop, but its latency, memory usage, or database connection count may become unacceptable when the database contains thousands of products and the API serves hundreds of concurrent requests.

We will distinguish three categories of measurements:

  • Latency: The time required to complete a request. The average is not sufficient, so later lessons will also consider percentiles such as p95 and p99.
  • Resource usage: CPU, memory, garbage collection behavior, thread-pool activity, and database connections.
  • Throughput: The number of successful operations the application can complete within a given period.

The objective of this lesson is not to produce a perfect production benchmark. It is to establish a repeatable baseline that we can use before and after every optimization.

2. Solution and layered project structure

Create the solution from a terminal. Because we will use controller-based Web API, specify --use-controllers explicitly. The .NET 10 Web API template includes OpenAPI support, while an interactive Swagger UI can be added separately.

mkdir ECommerce.Performance
cd ECommerce.Performance

dotnet new sln -n ECommerce.Performance
dotnet new webapi -n ECommerce.Api --framework net10.0 --use-controllers
dotnet new classlib -n ECommerce.Application --framework net10.0
dotnet new classlib -n ECommerce.Domain --framework net10.0
dotnet new classlib -n ECommerce.Infrastructure --framework net10.0

dotnet sln add ECommerce.Api/ECommerce.Api.csproj
dotnet sln add ECommerce.Application/ECommerce.Application.csproj
dotnet sln add ECommerce.Domain/ECommerce.Domain.csproj
dotnet sln add ECommerce.Infrastructure/ECommerce.Infrastructure.csproj

Configure the project references as follows:

dotnet add ECommerce.Application reference ECommerce.Domain
dotnet add ECommerce.Infrastructure reference ECommerce.Application
dotnet add ECommerce.Infrastructure reference ECommerce.Domain
dotnet add ECommerce.Api reference ECommerce.Application
dotnet add ECommerce.Api reference ECommerce.Infrastructure

The purpose of this structure is to limit responsibilities. Domain contains business entities and core rules. Application contains use cases and contracts. Infrastructure contains external concerns such as EF Core and SQL Server. Api is the HTTP entry point. A layered architecture does not automatically make an application fast, but it makes responsibilities easier to understand while measuring and optimizing the system.

3. Domain model and application contract

Add a Product class to ECommerce.Domain:

namespace ECommerce.Domain.Products;

public sealed class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public bool IsActive { get; set; }
    public DateTime CreatedUtc { get; set; }
}

To avoid returning the domain entity directly from the HTTP layer, define a DTO and service contract in the application layer:

namespace ECommerce.Application.Products;

public sealed record ProductListItem(
    int Id,
    string Name,
    decimal Price);

public interface IProductService
{
    Task<IReadOnlyList<ProductListItem>> GetActiveProductsAsync(
        CancellationToken cancellationToken = default);
}

DTOs do not guarantee better performance by themselves. They provide a foundation for selecting only required columns later, applying projections, and keeping the API contract independent from the database model.

4. EF Core and SQL Server infrastructure

Add the required packages to the Infrastructure project:

dotnet add ECommerce.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer
dotnet add ECommerce.Infrastructure package Microsoft.EntityFrameworkCore.Design

Create the DbContext and an initial service implementation:

using ECommerce.Domain.Products;
using Microsoft.EntityFrameworkCore;

namespace ECommerce.Infrastructure.Persistence;

public sealed class StoreDbContext(DbContextOptions<StoreDbContext> options)
    : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();
}

public sealed class ProductService(StoreDbContext db) : IProductService
{
    public async Task<IReadOnlyList<ProductListItem>> GetActiveProductsAsync(
        CancellationToken cancellationToken = default)
    {
        var products = await db.Products
            .Where(product => product.IsActive)
            .OrderBy(product => product.Id)
            .Select(product => new ProductListItem(
                product.Id,
                product.Name,
                product.Price))
            .ToListAsync(cancellationToken);

        return products;
    }
}

The query is intentionally simple. ToListAsync performs the I/O asynchronously. Select limits the result to fields required by the endpoint. Detailed discussion of these techniques belongs to later lessons; here, they give us a realistic data-access path to measure.

Add a connection string to appsettings.Development.json in the API project:

{
  "ConnectionStrings": {
    "Store": "Server=localhost;Database=ECommercePerformance;Trusted_Connection=True;TrustServerCertificate=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

Do not place passwords or other secrets in source control. For development, use User Secrets, environment variables, or a secure secret-management service.

5. Service registration, logging, and Swagger

Configure Program.cs with the following foundation:

using ECommerce.Application.Products;
using ECommerce.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddDbContext<StoreDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Store")));

builder.Logging.ClearProviders();
builder.Logging.AddConsole();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();
app.MapControllers();

app.Run();

In .NET 10, treat the generated OpenAPI document and Swagger UI as separate concerns. The application can generate an OpenAPI document, while an interactive Swagger interface requires an additional package and middleware. Keep the UI limited to development unless you have explicitly reviewed the security implications.

Add a controller:

using ECommerce.Application.Products;
using Microsoft.AspNetCore.Mvc;

namespace ECommerce.Api.Controllers;

[ApiController]
[Route("api/products")]
public sealed class ProductsController(IProductService service) : ControllerBase
{
    [HttpGet("active")]
    public async Task<ActionResult<IReadOnlyList<ProductListItem>>> GetActive(
        CancellationToken cancellationToken)
    {
        var products = await service.GetActiveProductsAsync(cancellationToken);
        return Ok(products);
    }
}

6. First measurement: Stopwatch and structured logging

Do not confuse application startup time with request-processing time. Stopwatch can measure the elapsed time of a selected code path. However, writing detailed logs for every request can create I/O overhead. Keep logging intentional and configurable.

using System.Diagnostics;
using ECommerce.Application.Products;
using Microsoft.AspNetCore.Mvc;

namespace ECommerce.Api.Controllers;

[ApiController]
[Route("api/products")]
public sealed class ProductsController(
    IProductService service,
    ILogger<ProductsController> logger) : ControllerBase
{
    [HttpGet("active")]
    public async Task<ActionResult<IReadOnlyList<ProductListItem>>> GetActive(
        CancellationToken cancellationToken)
    {
        var stopwatch = Stopwatch.StartNew();
        var products = await service.GetActiveProductsAsync(cancellationToken);
        stopwatch.Stop();

        logger.LogInformation(
            "Active product query completed in {ElapsedMilliseconds} ms and returned {Count} items",
            stopwatch.Elapsed.TotalMilliseconds,
            products.Count);

        return Ok(products);
    }
}

This gives us an application-level observation, but it is not identical to the total time observed by a client. Client time may include DNS, TCP or TLS connection setup, network transfer, JSON serialization, and client-side waiting. Record the two perspectives separately.

7. HTTP measurements and dotnet-counters

Run the application:

dotnet run --project ECommerce.Api

Call the endpoint several times through Swagger or another HTTP client. To create repeatable samples, you can use a simple PowerShell example:

$samples = 10
1..$samples | ForEach-Object {
    $result = Measure-Command {
        Invoke-RestMethod `
          -Uri "https://localhost:7001/api/products/active" `
          -SkipCertificateCheck
    }
    [pscustomobject]@{
        Sample = $_
        Milliseconds = $result.TotalMilliseconds
    }
}

Change the port to match your application output. Treat the first request separately because application startup, connection pooling, and JIT compilation can make early requests different from later ones.

After finding the process ID, install and run dotnet-counters:

dotnet tool install --global dotnet-counters
dotnet-counters ps
dotnet-counters monitor --process-id <PID>

To focus on ASP.NET Core hosting and runtime information, use:

dotnet-counters monitor \
  --process-id <PID> \
  --counters Microsoft.AspNetCore.Hosting,System.Runtime

While sending requests, observe current requests, request duration, CPU usage, garbage collection activity, and heap behavior. Do not draw conclusions from one number. Repeat the test with the same endpoint, similar data, a similar request count, and as much environmental consistency as possible.

8. Defining performance goals

Goals give optimization work a direction. For this course project, you can begin with a table such as the following:

MetricInitial targetNote
Product-list p95 latencyBelow 250 ms locallySpecify the data volume
Response sizeNo unnecessary fieldsCompression will be studied later
Successful request rate99% or higherKeep failures separate from latency
SQL query countRecord for each endpointUseful for N+1 analysis

These are not universal production rules. Production targets must reflect user expectations, SLAs, data volume, infrastructure, and cost. The important qualities are that a target is measurable, repeatable, and connected to a business requirement.

Common mistakes

  • Looking only at the average: A few slow requests may disappear in the average. Track p95 and p99 as well.
  • Treating Debug as production: The debugger, verbose logging, and development middleware can affect measurements.
  • Using the first request as the representative sample: Separate warm-up requests.
  • Treating a log entry as the complete request time: The logged interval may cover only one code section, while the client measures more.
  • Using unrealistic data: A test with five products says little about query behavior with hundreds of thousands of rows.
  • Applying every optimization without measurement: More complex code is not automatically faster. Record the baseline first.

Short practice exercise

  1. Create the solution and separate the four projects by responsibility.
  2. Configure SQL Server and insert at least 100 sample products.
  3. Call /api/products/active 10 times through Swagger or an HTTP client.
  4. Record all durations and mark the first request separately.
  5. Use dotnet-counters during the same test to observe CPU, GC, and ASP.NET Core counters.
  6. Save the endpoint's p95 latency, response size, and logged query duration for comparison in the next lesson.

Reflection question: What three pieces of evidence would you present to claim that an endpoint was optimized? Include at least one latency measurement, one resource indicator, and a before-and-after comparison under the same test conditions.

Conclusion

In this lesson, we created the foundation of the shared e-commerce API and applied the first rule of performance work: do not optimize without measuring. We established a layered structure, configured EF Core, created an asynchronous product endpoint, added controlled logging, exposed OpenAPI information, and prepared live observation with dotnet-counters.

In the next lessons, we will use this project to study async/await, EF Core query behavior, tracking, projections, the N+1 problem, pagination, and caching. After each change, we will repeat comparable measurements and verify whether the application actually improved.

Sources