Skip to main content

Lesson 2 of 8

IMemoryCache - In-Process Caching

IMemoryCache stores data in the same process as your API - zero network latency, ideal for reference data (categories, config), frequently-read entities, and computed results. The challenge: cache stampede - when the cache expires, multiple threads all hit the DB simultaneously.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Cache-Aside with Stampede Prevention

Cache-Aside with Stampede Prevention
using Microsoft.Extensions.Caching.Memory;

// ━━ Registration ━━
builder.Services.AddMemoryCache(options =>
{
    options.SizeLimit = 1024;             // cache can hold 1024 'units' (you define unit = 1 per entry)
    options.CompactionPercentage = 0.2;   // compact 20% when limit is reached
});

// ━━ Cache-aside pattern ━━
public class CategoryService(IMemoryCache cache, ICategoryRepository repo, ILogger<CategoryService> logger)
{
    private static readonly MemoryCacheEntryOptions CategoryCacheOptions = new()
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30),
        SlidingExpiration = TimeSpan.FromMinutes(5),  // reset TTL on each access
        Priority = CacheItemPriority.High,
        Size = 1
    };

    public async Task<IReadOnlyList<CategoryDto>> GetAllAsync(CancellationToken ct = default)
    {
        const string key = "categories:all";

        if (cache.TryGetValue(key, out IReadOnlyList<CategoryDto>? cached))
            return cached!; // cache hit

        logger.LogInformation("Cache miss for {CacheKey} - loading from DB", key);
        var categories = await repo.GetAllAsync(ct);
        var dtos = categories.Select(c => new CategoryDto(c.Id, c.Name)).ToList();

        cache.Set(key, (IReadOnlyList<CategoryDto>)dtos, CategoryCacheOptions);
        return dtos;
    }

    // ━━ Cache stampede prevention with SemaphoreSlim ━━
    private readonly SemaphoreSlim _lock = new(1, 1);

    public async Task<ProductStatsDto?> GetStatsAsync(Guid productId, CancellationToken ct)
    {
        var key = $"stats:{productId}";

        if (cache.TryGetValue(key, out ProductStatsDto? cached))
            return cached;

        // Only ONE thread fetches from DB - others wait
        await _lock.WaitAsync(ct);
        try
        {
            // Double-check after acquiring lock (another thread may have populated it)
            if (cache.TryGetValue(key, out cached))
                return cached;

            var stats = await repo.GetStatsAsync(productId, ct);
            if (stats is not null)
                cache.Set(key, stats, TimeSpan.FromMinutes(5));

            return stats;
        }
        finally
        {
            _lock.Release();
        }
    }

    // ━━ Cache invalidation ━━
    public async Task UpdateCategoryAsync(Guid id, UpdateCategoryRequest request, CancellationToken ct)
    {
        await repo.UpdateAsync(id, request, ct);
        cache.Remove("categories:all"); // invalidate on write
        cache.Remove($"category:{id}");
    }
}

record CategoryDto(Guid Id, string Name);
record ProductStatsDto(Guid ProductId, int Views, decimal Revenue);
record UpdateCategoryRequest(string Name);
interface ICategoryRepository { Task<System.Collections.Generic.List<Category>> GetAllAsync(CancellationToken ct); Task<ProductStatsDto?> GetStatsAsync(Guid id, CancellationToken ct); Task UpdateAsync(Guid id, UpdateCategoryRequest r, CancellationToken ct); }
class Category { public Guid Id { get; set; } public string Name { get; set; } = ""; }

Tip

Tip

Practice IMemoryCache InProcess Caching in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of IMemoryCache InProcess Caching from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with IMemoryCache InProcess Caching is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done