LESSON 3 OF 12

3. Cache Entry Configuration: Absolute and Sliding Expiration

Learn how to configure absolute, sliding, and combined expiration policies, control cache size, and choose suitable TTL values with IMemoryCache.

35 dk 85

Introduction

Adding a value to a cache is not only about storing it in memory. You must also define how long the cache entry may live, when it should be refreshed, and how much memory it is allowed to consume. An incorrect expiration policy can expose stale data, leave unnecessary load on the database, or allow memory usage to grow over time.

In this lesson, we will examine three policies with IMemoryCache: absolute expiration, sliding expiration, and a combination of both. We will then limit cache size, select TTL values for different data types, and test expiration behavior. The examples use a product catalog API and follow the cache-aside flow introduced in the previous lessons.

A cache is always a temporary optimization layer. The application must have a reliable fallback source and must continue to work when the requested value is not available in the cache.

1. Understanding expiration types

Absolute expiration

Absolute expiration defines the maximum lifetime of an entry starting from the moment it is inserted into the cache. The entry is removed when that duration ends, regardless of how many times it has been read.

var product = await _cache.GetOrCreateAsync(key, async entry =>
{
    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
    return await _productRepository.GetByIdAsync(productId);
});

In this example, the product remains cached for at most five minutes. Frequent reads do not extend the absolute lifetime. This policy is suitable for data with a known change frequency or a clear maximum staleness requirement.

Sliding expiration

Sliding expiration represents the inactivity period after the last access. If the entry is read within the configured interval, its inactivity timer is reset.

var product = await _cache.GetOrCreateAsync(key, async entry =>
{
    entry.SlidingExpiration = TimeSpan.FromMinutes(2);
    return await _productRepository.GetByIdAsync(productId);
});

In this example, the product can remain cached while it is accessed at least once every two minutes. If it is not accessed for more than two minutes, the entry expires. Sliding expiration is useful for data that is popular for a period of time but should disappear after becoming inactive.

Using only sliding expiration can be dangerous. A frequently requested entry may never expire. With a large number of keys, this can cause unnecessary memory growth.

Combined expiration

When sliding and absolute expiration are configured together, both rules apply. The entry can be removed earlier if it is inactive for the sliding interval, but it must be removed when the absolute lifetime is reached, even if it is being accessed continuously.

var product = await _cache.GetOrCreateAsync(key, async entry =>
{
    entry.SlidingExpiration = TimeSpan.FromMinutes(2);
    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15);
    return await _productRepository.GetByIdAsync(productId);
});

This policy keeps active data available while preventing it from remaining in the cache indefinitely. Microsoft’s ASP.NET Core documentation recommends combining the two policies when an absolute upper bound is required.

2. Implementing an expiration policy in a product service

The following service first checks the cache. If the entry is missing, it loads the product from the repository and stores it with explicit cache options. This is the basic form of the cache-aside pattern.

using Microsoft.Extensions.Caching.Memory;

public sealed class ProductService
{
    private readonly IMemoryCache _cache;
    private readonly IProductRepository _repository;

    public ProductService(
        IMemoryCache cache,
        IProductRepository repository)
    {
        _cache = cache;
        _repository = repository;
    }

    public async Task<ProductDto?> GetByIdAsync(
        int productId,
        CancellationToken cancellationToken = default)
    {
        var key = $"catalog:product:{productId}";

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

        var product = await _repository.GetByIdAsync(
            productId,
            cancellationToken);

        if (product is null)
        {
            return null;
        }

        var options = new MemoryCacheEntryOptions
        {
            SlidingExpiration = TimeSpan.FromMinutes(2),
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15),
            Size = 1,
            Priority = CacheItemPriority.Normal
        };

        _cache.Set(key, product, options);
        return product;
    }
}

In this example, Size = 1 becomes important when a size limit is enabled. The unit is not bytes; it is a relative unit chosen by the application. All entries belonging to that cache must use a consistent measurement strategy.

3. Selecting TTL values for different data types

Instead of applying one global TTL, evaluate how often the data changes, how important freshness is, how large the value is, and how frequently it is read.

Data typeExample policyReason
Product details2-minute sliding, 15-minute absoluteProducts may be read frequently, but prices and stock should not remain stale for too long.
Category list30-minute absoluteCategories often change infrequently, so a fixed refresh boundary is sufficient.
Application settings5-minute absolute or explicit invalidationChanges should be reflected in a controlled manner.
User permissionsShort absolute lifetimeAuthorization changes should become effective quickly.
Reporting result10-minute sliding, 1-hour absoluteExpensive queries are reduced without keeping results stale for the entire day.

A TTL is not a correctness guarantee. It is the accepted window of possible staleness. A 15-minute TTL may be technically valid for stock data, but it is incorrect if the business requirement allows stock information to be only 30 seconds old. For important updates, do not rely on TTL alone; design an explicit key update or invalidation mechanism as well.

4. Limiting cache size

IMemoryCache should not be treated as a memory-pressure management system that automatically solves every capacity problem. Expiration should be combined with a limit on entry count or a relative size model.

Applying SizeLimit directly to the shared default IMemoryCache requires care. Once a size limit is enabled, every entry added to that cache must specify a size. If another framework or library writes to the same cache without setting a size, unexpected failures may occur. For this reason, a dedicated MemoryCache instance is safer when strict size control is required.

public sealed class ProductCache
{
    public MemoryCache Cache { get; } = new(
        new MemoryCacheOptions
        {
            SizeLimit = 10_000
        });
}

Register the dedicated cache as follows:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();
builder.Services.AddSingleton<ProductCache>();
builder.Services.AddScoped<ProductService>();

When using this cache, select one unit system for all entries. In a simple product cache, every product can have a weight of 1. For large collections, you might use an estimated item count or a normalized weight.

public sealed class ProductCatalogReader
{
    private readonly ProductCache _productCache;
    private readonly IProductRepository _repository;

    public ProductCatalogReader(
        ProductCache productCache,
        IProductRepository repository)
    {
        _productCache = productCache;
        _repository = repository;
    }

    public async Task<IReadOnlyList<ProductDto>> GetFeaturedAsync()
    {
        const string key = "catalog:featured";

        if (_productCache.Cache.TryGetValue(
            key,
            out IReadOnlyList<ProductDto>? products))
        {
            return products!;
        }

        products = await _repository.GetFeaturedAsync();

        var options = new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
            .SetSize(50)
            .SetPriority(CacheItemPriority.High);

        _productCache.Cache.Set(key, products, options);
        return products;
    }
}

Remember that SizeLimit is not expressed in bytes. It is an abstract capacity selected by the application. If you need to approximate real memory usage, you may use serialized size, collection length, or a normalized weight from your measurement system. The important requirement is that every entry follows the same rule.

5. Testing expiration behavior

Expiration should be verified with focused tests instead of being observed only in production. Abstracting time or using short TTL values in integration tests makes the behavior easier to validate.

  1. Send the first request and verify that the repository is called.
  2. Send a second request within the TTL and verify that the repository is not called again.
  3. Access the entry at intervals shorter than the sliding duration and confirm that it remains available.
  4. Wait longer than the sliding duration after the last access and confirm that the repository is called again.
  5. Read the entry continuously and verify that it is still removed when the absolute duration is reached.

For example, a test environment can use a 200-millisecond sliding duration and an 800-millisecond absolute duration. Real delays can make tests slow and fragile, so use a controllable time provider or clock abstraction when possible.

6. Common mistakes

  • Using only sliding expiration: Frequently accessed entries can live indefinitely. Add an absolute upper bound when required.
  • Applying the same TTL to every value: Products, permissions, settings, and reports have different freshness requirements.
  • Treating the cache as permanent storage: The application must be able to recover from a cache miss.
  • Creating unbounded key variation: Directly using arbitrary external input as a key can create an uncontrolled number of entries.
  • Adding SizeLimit to a shared cache without a plan: Libraries may add entries without specifying size, causing conflicts.
  • Choosing TTL without measurement: Monitor hit rate, database load, memory usage, and data freshness together.

Short practice exercise

Implement a GetByCategoryAsync method with the following policy:

  • Sliding expiration: 3 minutes
  • Absolute expiration: 20 minutes
  • Entry size: 10
  • Cache key format: catalog:category:{categoryId}:page:{pageNumber}

Test repeated access to the same page, inactivity longer than three minutes, and continuous access until the twenty-minute absolute limit. Observe repository calls and the timestamp of the returned data. Finally, explain the risks to memory usage and freshness if the absolute TTL is changed from twenty minutes to two hours.

Conclusion

Absolute expiration establishes a firm maximum lifetime for a cache entry. Sliding expiration keeps actively used entries available but may allow them to remain indefinitely when used alone. Combining both policies supports access patterns while enforcing a maximum lifetime.

Choosing the right TTL is not merely a technical setting. It is a balance among data freshness, user experience, database cost, and memory consumption. With size limits, controlled key design, a fallback path, and measurement, IMemoryCache becomes a more predictable performance layer. In the next lessons, we will move these ideas to distributed caching and Redis.

Sources