LESSON 1 OF 12

1. Real-World Project Architecture and Cache Requirements Analysis

Build a layered ASP.NET Core Web API project with Entity Framework Core, SQL Server, and Redis around a product catalog scenario. Identify slow queries, analyze caching opportunities, and establish baseline performance measurements for later lessons.

50 dk 86

Introduction

Implementing caching is not simply a matter of writing a value to Redis and reading it later. A reliable caching strategy starts by understanding which operations are expensive, which data is frequently read, how often the data changes, and whether the application runs on one server or across multiple servers.

In this lesson, we will create the sample project used throughout the course. The scenario is an ASP.NET Core Web API that serves a product catalog. The application will read products from SQL Server, use Entity Framework Core for data access, and later use Redis as a distributed cache. Our first goal is not to cache every endpoint. It is to establish a measurable baseline before introducing optimization.

The central rule of performance work is: measure first, change second, and measure again. Otherwise, we cannot determine whether a caching change actually helped or whether the real problem was a database query, network latency, serialization, or response size.

1. The sample project scenario

Let us call the application Catalog.Api. It will support product listing, product detail, and category filtering. We will use a simple layered structure:

  • Catalog.Api: HTTP endpoints, dependency injection configuration, and application startup.
  • Catalog.Application: use cases, services, DTOs, and application workflows.
  • Catalog.Domain: core business entities such as products and categories.
  • Catalog.Infrastructure: Entity Framework Core, SQL Server, Redis, and external integrations.
  • Catalog.Tests: unit and integration tests.

This separation prevents cache code from being scattered across controllers. When we apply the cache-aside pattern later, a controller will request a product list from an application service. The service or infrastructure layer will determine whether the result comes from the cache or SQL Server.

Recommended folder structure

src/
  Catalog.Api/
    Controllers/
    Extensions/
    Program.cs
  Catalog.Application/
    Products/
      IProductService.cs
      ProductService.cs
      ProductDtos.cs
  Catalog.Domain/
    Products/
      Product.cs
      Category.cs
  Catalog.Infrastructure/
    Persistence/
      CatalogDbContext.cs
      Configurations/
    Caching/
      CacheKeys.cs
      CacheOptions.cs
tests/
  Catalog.Tests/

Consistent naming is important in every layer. Names such as ProductService, ProductDto, ProductRepository, and ProductCacheKey make the product context explicit. Vague names become increasingly difficult to maintain as cache keys and service responsibilities grow.

2. Creating the projects and defining dependencies

Create a solution and the individual projects:

dotnet new sln -n Catalog

dotnet new webapi -n Catalog.Api -o src/Catalog.Api
dotnet new classlib -n Catalog.Application -o src/Catalog.Application
dotnet new classlib -n Catalog.Domain -o src/Catalog.Domain
dotnet new classlib -n Catalog.Infrastructure -o src/Catalog.Infrastructure
dotnet new xunit -n Catalog.Tests -o tests/Catalog.Tests

dotnet sln Catalog.sln add src/Catalog.Api
dotnet sln Catalog.sln add src/Catalog.Application
dotnet sln Catalog.sln add src/Catalog.Domain
dotnet sln Catalog.sln add src/Catalog.Infrastructure
dotnet sln Catalog.sln add tests/Catalog.Tests

Add project references while preserving the direction of dependencies. The Domain project should remain as independent as possible. Infrastructure can reference Domain and Application, while the API project can reference Application and the infrastructure configuration.

Later lessons will use the Entity Framework Core SQL Server provider, memory cache abstractions, and Redis through StackExchange.Redis or a distributed-cache integration. In this first lesson, the important task is not installing every package, but placing integration points in the correct layers.

3. Preparing the domain and data access model

A sample product entity may look like this:

namespace Catalog.Domain.Products;

public sealed class Product
{
    public int Id { get; private set; }
    public string Sku { get; private set; } = null!;
    public string Name { get; private set; } = null!;
    public string Category { get; private set; } = null!;
    public decimal Price { get; private set; }
    public bool IsActive { get; private set; }
    public DateTime UpdatedAtUtc { get; private set; }
}

Instead of returning the Entity Framework Core entity directly from the API, define a DTO:

namespace Catalog.Application.Products;

public sealed record ProductListItemDto(
    int Id,
    string Sku,
    string Name,
    string Category,
    decimal Price);

This separation also matters for caching. Rather than storing Entity Framework proxies, tracking state, or unnecessary navigation properties, we can cache a small and stable representation of the data that the API actually needs.

For read scenarios, use AsNoTracking:

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

public sealed class ProductService(CatalogDbContext db)
{
    public Task<List<ProductListItemDto>> GetProductsAsync(
        CancellationToken cancellationToken)
    {
        return db.Products
            .AsNoTracking()
            .Where(product => product.IsActive)
            .OrderBy(product => product.Name)
            .Select(product => new ProductListItemDto(
                product.Id,
                product.Sku,
                product.Name,
                product.Category,
                product.Price))
            .ToListAsync(cancellationToken);
    }
}

Selecting only the required columns, filtering inactive products in the database, and executing the query asynchronously are all important. Caching does not automatically replace a poorly designed query. Caching a query that retrieves unnecessary columns and rows increases the initial load cost and cache memory usage.

4. Identifying cache candidates

Not every value belongs in a cache. Ask the following questions for each use case:

  1. How frequently is the data read?
  2. How expensive is it to generate or retrieve?
  3. How frequently does it change?
  4. Is a short period of stale data acceptable?
  5. Is the response specific to a user or authorization context?
  6. Can the application regenerate the value from the source when the cache is lost?

Assume that the product catalog is public and frequently read. If prices and stock do not need to be real-time, the product list is a strong cache candidate. In contrast, payment results, user-specific carts, and authorization information should not be placed in a shared cache without careful design.

ScenarioCache decisionReason
Active product listSuitableFrequently read and potentially expensive as the dataset grows.
Product detailsUsually suitableEasy to access by identifier; invalidation is needed after updates.
Current inventory quantityUse cautionStale data may cause sales or reservation errors.
User-specific cartRequires scoped designThe key must include the user or cart identifier.
Payment resultUsually avoid cachingCorrectness and security are more important than speed.

5. Making slow queries visible

We need observability before optimization. In development, enable Entity Framework Core logging so that we can inspect the generated SQL and approximate execution time:

builder.Services.AddDbContext<CatalogDbContext>(options =>
{
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("Catalog"));
    options.EnableDetailedErrors();
});

Increase the logging level during development:

{
  "Logging": {
    "LogLevel": {
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

Do not expose sensitive data in production logs. Inspect the SQL Server query plan with the appropriate database tools. Pay particular attention to whether columns used for filtering, ordering, and joins have suitable indexes. For example, the need for an index involving IsActive and Category should be evaluated from real query patterns and measurements.

Measure more than query duration. Record total HTTP response time, request volume, error rate, and response size. A query can be fast inside the database while JSON serialization or network transfer still dominates the total response time.

6. Establishing a performance baseline

The first measurements must be taken without caching. Send a controlled number of requests to the same endpoint and record:

  • Average, median, and high-percentile response times.
  • Requests per second.
  • HTTP error rate.
  • SQL query count and duration.
  • Application and SQL Server CPU and memory usage.
  • Approximate response-body size.

You can begin with an HTTP client in a development environment. For more reliable results, create a repeatable load test using the same dataset and test conditions. Separate cold-start behavior from the steady state after the application has warmed up.

Create a baseline table such as this:

EndpointRequestsAveragep95SQL calls
GET /api/products100To measureTo measureTo measure
GET /api/products/1100To measureTo measureTo measure

After introducing caching in later lessons, repeat the same test under the same conditions. This lets us evaluate improvement with evidence rather than intuition.

7. Positioning Redis in the architecture

Do not access Redis directly from controllers. Place it behind a cache abstraction. The application layer can depend on an interface, while the infrastructure layer implements that interface with Redis or another provider.

public interface IProductCache
{
    Task<ProductListItemDto[]?> GetListAsync(
        CancellationToken cancellationToken);

    Task SetListAsync(
        ProductListItemDto[] products,
        TimeSpan duration,
        CancellationToken cancellationToken);

    Task RemoveListAsync(CancellationToken cancellationToken);
}

This approach makes it easier to use a fake cache in tests, switch between memory and Redis, and keep cache-library details outside business workflows. A cache is not the primary data source. The application must define how it behaves when the cache is empty, unavailable, or cleared.

In a multi-server environment, separate in-memory caches can produce inconsistent results because each application instance owns a different copy. A shared distributed cache such as Redis can be used by all instances. However, a distributed cache introduces network and serialization overhead. In later lessons, we will compare in-memory, distributed, and two-level strategies using measurements.

Common mistakes

  • Adding caching without measurement: An optimization made without identifying the actual bottleneck may improve the wrong layer.
  • Caching everything: A cache is not an unlimited data store; memory, expiration, and invalidation have costs.
  • Caching entities directly: Tracking state, navigation properties, and model changes can create problems. DTOs are safer.
  • Leaving cache keys vague: The key scope, version, filters, and pagination parameters should be explicit.
  • Depending on the cache: The application must regenerate data from the source when the cache is unavailable.
  • Logging sensitive data in production: SQL parameters and user data must follow an appropriate logging policy.

Short practice exercise

  1. Create the Catalog solution and its layers.
  2. Add the Product entity, ProductListItemDto, and CatalogDbContext.
  3. Create an endpoint that lists active products.
  4. Enable Entity Framework Core SQL logging and inspect the generated query.
  5. Test the endpoint with at least 20 requests and record average and p95 response times.
  6. Write a short justification for whether the product list, product detail, and inventory data should be cached.

Conclusion

In this lesson, we learned why requirements analysis and measurement must come before caching. We created the layered structure for a product catalog, established a DTO-based data flow, used asynchronous and no-tracking query patterns, identified logging points for slow-query analysis, and prepared a baseline performance table.

In the next lessons, we will build on this foundation by examining caching concepts and the differences between in-memory and distributed caching. When we introduce Redis, we will preserve the layer boundaries, naming conventions, and measurement process established here.

Sources