.NET Architecture & System Design Interview Question #29

When should you use IMemoryCache in ASP.NET Core?

Caching, CDN, Queues & Asynchronous Processing Junior Beginner

Quick Interview Answer

IMemoryCache is appropriate for data that can be cached independently within each application instance and does not require synchronization across servers. Examples include small reference data, computed values, or short-lived local optimizations.

Detailed Explanation

IMemoryCache is appropriate for data that can be cached independently within each application instance and does not require synchronization across servers. Examples include small reference data, computed values, or short-lived local optimizations.

It should be used carefully in multi-instance deployments because each process has different cached contents. Large or unbounded entries can also create memory pressure.

Code Example

builder.Services.AddMemoryCache();

var value = await cache.GetOrCreateAsync(
    key,
    entry =>
    {
        entry.AbsoluteExpirationRelativeToNow =
            TimeSpan.FromMinutes(5);
        return LoadAsync();
    });