LESSON 2 OF 12

2. Caching Fundamentals and the First Implementation with In-Memory Cache

Learn cache, hit, miss, TTL, and eviction concepts, then apply the cache-aside pattern to product list and detail endpoints with ASP.NET Core IMemoryCache.

40 dk 72

Introduction

When every request in an ASP.NET Core application goes directly to the database, frequently accessed product catalogs can create unnecessary load. The same product list may be requested hundreds of times within a short period, yet the application does not need to read the same rows from the database for every request. A cache stores previously generated or retrieved data in a temporary, faster-to-access layer.

In this lesson, we will learn the fundamental concepts of caching and build our first implementation with IMemoryCache. We will add the cache-aside approach to product list and product detail endpoints, then compare database query counts and response times before and after caching. This implementation is appropriate for a single-server or development environment. Distributed caching and Redis integration for multi-server production environments will be covered in later lessons.

1. Core Caching Concepts

What is a cache?

A cache is a temporary storage layer for data that the application may need again. In the basic flow, the application first checks the cache. If the value exists, it is returned directly from the cache. If it does not exist, the application reads from the original data source, such as a SQL database, stores the result in the cache, and returns it to the client.

A cache is not a durable source of truth. The database or another authoritative source must remain available as a fallback. Cache entries may be removed, expire, disappear after an application restart, or become temporarily unavailable.

Hit and miss

  • Cache hit: The requested key exists in the cache, so the value can be returned without querying the primary source.
  • Cache miss: The requested key does not exist. The application retrieves the data from the primary source and usually stores the result in the cache.

Performance analysis should consider hit and miss rates, not only total request duration. A low hit rate may indicate that keys, expiration periods, or the selected data are not designed appropriately.

TTL and expiration

TTL, or Time To Live, defines how long a cache entry remains valid. If a product list has a TTL of 60 seconds, it can be used for up to 60 seconds after being inserted into the cache. After that period, the application retrieves fresh data and creates a new entry.

In the ASP.NET Core memory cache, absolute expiration makes an entry expire after a fixed period. Sliding expiration allows the expiration period to be renewed when the entry is accessed. In this lesson, we will use absolute expiration so that product data is refreshed within a predictable time window.

Eviction

Eviction means removing an entry from the cache. An entry may be removed because it expired, because application code explicitly removed it, or because the cache reached a configured capacity limit. An in-memory cache uses the memory of the application process, so cache growth must be controlled. Expiration, size limits, and sensible key design are application responsibilities.

2. The Application Before Caching

First, consider a simple product service that does not use a cache. The database context is assumed to already exist.

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 sealed class ProductListItem
{
    public int Id { get; init; }
    public string Name { get; init; } = string.Empty;
    public decimal Price { get; init; }
}

Before caching, the service executes an Entity Framework Core query on every call:

public sealed class ProductService
{
    private readonly AppDbContext _db;

    public ProductService(AppDbContext db)
    {
        _db = db;
    }

    public Task<List<ProductListItem>> GetProductsAsync(
        CancellationToken cancellationToken)
    {
        return _db.Products
            .AsNoTracking()
            .Where(x => x.IsActive)
            .OrderBy(x => x.Name)
            .Select(x => new ProductListItem
            {
                Id = x.Id,
                Name = x.Name,
                Price = x.Price
            })
            .ToListAsync(cancellationToken);
    }
}

This approach is correct, but repeated requests for the same list generate repeated SQL queries. To measure the effect, record the number of requests, database query logs, and HTTP response times.

3. Adding IMemoryCache

ASP.NET Core exposes IMemoryCache through dependency injection. Some MVC, Razor Pages, or related service registrations may enable it automatically, but explicitly registering it in Program.cs makes the application setup clear.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddMemoryCache();
builder.Services.AddScoped<ProductService>();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

var app = builder.Build();
app.MapControllers();
app.Run();

IMemoryCache stores objects in the memory of the application server. It is therefore a simple and fast option for single-server applications. Its contents disappear when the application restarts. With multiple application servers, each server may have a different cache, which can produce consistency problems.

4. Designing Cache Keys

Every cache entry is identified by a key. The key should clearly describe the data and prevent unrelated data sets from accidentally sharing an entry. Keeping key construction in one class reduces typing errors.

public static class ProductCacheKeys
{
    public const string ActiveProducts = "products:active:list:v1";

    public static string ById(int id) => $"products:by-id:{id}:v1";
}

The product identifier is part of the detail key. Including a version makes it possible to stop using old entries when the cached data shape changes. Avoid using unlimited and unvalidated user input directly as a key because it can cause unpredictable memory consumption.

5. Implementing Cache-Aside

With the cache-aside pattern, application code manages the cache explicitly. It checks the cache first. If the entry is missing, it reads from the database, stores the result in the cache, and returns it. The essential property is that missing cache data can always be recreated from the primary source.

Product list

public sealed class ProductService
{
    private readonly AppDbContext _db;
    private readonly IMemoryCache _cache;

    public ProductService(AppDbContext db, IMemoryCache cache)
    {
        _db = db;
        _cache = cache;
    }

    public async Task<List<ProductListItem>> GetProductsAsync(
        CancellationToken cancellationToken)
    {
        if (_cache.TryGetValue(ProductCacheKeys.ActiveProducts,
            out List<ProductListItem>? cachedProducts))
        {
            return cachedProducts;
        }

        var products = await _db.Products
            .AsNoTracking()
            .Where(x => x.IsActive)
            .OrderBy(x => x.Name)
            .Select(x => new ProductListItem
            {
                Id = x.Id,
                Name = x.Name,
                Price = x.Price
            })
            .ToListAsync(cancellationToken);

        var options = new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60),
            Priority = CacheItemPriority.Normal
        };

        _cache.Set(ProductCacheKeys.ActiveProducts, products, options);
        return products;
    }
}

The first request is a cache miss and executes the SQL query. Subsequent requests within the 60-second period are cache hits. After inserting a list into the cache, avoid mutating it. An in-memory cache can store a reference to an object, so changing a shared list can affect other callers. Immutable or read-only DTOs are safer cache values.

Product detail endpoint

public async Task<ProductListItem?> GetProductAsync(
    int id,
    CancellationToken cancellationToken)
{
    var key = ProductCacheKeys.ById(id);

    if (_cache.TryGetValue(key, out ProductListItem? cachedProduct))
    {
        return cachedProduct;
    }

    var product = await _db.Products
        .AsNoTracking()
        .Where(x => x.IsActive && x.Id == id)
        .Select(x => new ProductListItem
        {
            Id = x.Id,
            Name = x.Name,
            Price = x.Price
        })
        .SingleOrDefaultAsync(cancellationToken);

    if (product is not null)
    {
        _cache.Set(key, product, new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(2)
        });
    }

    return product;
}

In this simple example, a missing product is not cached. If requests for nonexistent products create excessive database traffic, short-lived negative caching can be considered. This technique requires care: if the product is created later, an old negative entry can temporarily return an incorrect result.

Controller example

[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
    private readonly ProductService _service;

    public ProductsController(ProductService service)
    {
        _service = service;
    }

    [HttpGet]
    public Task<List<ProductListItem>> GetProducts(
        CancellationToken cancellationToken)
        => _service.GetProductsAsync(cancellationToken);

    [HttpGet("{id:int}")]
    public async Task<ActionResult<ProductListItem>> GetProduct(
        int id,
        CancellationToken cancellationToken)
    {
        var product = await _service.GetProductAsync(id, cancellationToken);
        return product is null ? NotFound() : Ok(product);
    }
}

6. Measuring and Comparing Results

Adding a cache is not proof of a performance improvement by itself; the result must be measured. First, send five consecutive requests to the product list endpoint with caching disabled. Record the SQL query count. Then enable caching and repeat the same requests. The first request is expected to be a miss and execute one SQL query. Most later requests should be hits.

ScenarioExpected SQL queriesResponse behavior
Cache disabled, 5 requestsApproximately 5Every request includes database latency
Cache enabled, first request1Includes the cache population cost
Cache enabled, next 4 requests0Usually lower latency

Actual values depend on data size, database connection time, network latency, and server resources. Separate development measurements from production measurements. You can inspect response times with application logs, browser developer tools, or an API client. A more mature implementation should record hit, miss, query duration, and cache population duration through metrics or structured logs.

7. Common Mistakes

  • Treating the cache as the durable source of truth: The application must recreate data from the database when an entry disappears.
  • Leaving entries without a TTL: Permanent entries can grow memory usage and increase the risk of serving stale data.
  • Using an incomplete key: Omitting the product identifier can make different products share the same entry.
  • Not invalidating after updates: A changed product price may not appear in list and detail entries until expiration.
  • Caching overly large objects: Removing unnecessary fields from DTOs reduces memory consumption.
  • Assuming GetOrCreateAsync solves everything: Multiple factories may run during concurrent misses for the same key. Cache stampede protection will be discussed in a later lesson.
  • Using in-memory caching across multiple servers: Each server may contain different data, so distributed scenarios generally require a shared cache such as Redis.

8. Short Practice Exercise

Apply the following exercise to your product API:

  1. Send five consecutive requests to the product list endpoint without caching and record the SQL query count.
  2. Register AddMemoryCache and update the list endpoint with the cache-aside pattern.
  3. Configure a 30-second absolute expiration for the list.
  4. Create a detail key containing the product identifier and use it in the detail endpoint.
  5. Add log messages for “cache hit” and “cache miss” on the first and subsequent requests.
  6. Change a product price in the database and call the endpoint before expiration. Observe the old value and explain why it appears.
  7. Finally, add an invalidation method to remove the list and detail entries explicitly.

Conclusion

In this lesson, we saw that caching is a performance layer that can reduce database load and response latency. We covered hit, miss, TTL, and eviction concepts. We registered IMemoryCache in ASP.NET Core, designed meaningful cache keys, and applied the cache-aside pattern to product list and detail operations.

In-memory caching is a useful starting point for small, single-server, or development applications. However, entries disappear after a restart, and cache consistency is not guaranteed across multiple servers. In the next stage, we will use IDistributedCache and Redis to build a shared distributed caching layer.

Sources