In-Memory & Distributed Caching

In-Memory & Distributed Caching in .NET: Caching dramatically reduces database CPU load by storing hot query results in memory. ---

Caching dramatically reduces database CPU load by storing hot query results in memory.


1. In-Memory Caching (IMemoryCache)

app.MapGet("/api/v1/leaderboard", async (IMemoryCache cache, AppDbContext db, CancellationToken ct) =>
{
    const string cacheKey = "daily_top_learners";

    if (!cache.TryGetValue(cacheKey, out List<LeaderboardEntry>? topLearners))
    {
        topLearners = await db.Users
            .AsNoTracking()
            .OrderByDescending(u => u.TotalPoints)
            .Take(10)
            .Select(u => new LeaderboardEntry(u.Username, u.TotalPoints))
            .ToListAsync(ct);

        var cacheEntryOptions = new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
            .SetSlidingExpiration(TimeSpan.FromMinutes(2));

        cache.Set(cacheKey, topLearners, cacheEntryOptions);
    }

    return Results.Ok(topLearners);
});