ASP.NET Core Interview Question #181

What is the difference between in-memory and distributed caching?

Performance, Caching & HTTP Senior Advanced

Quick Interview Answer

In-memory caching stores data inside one application process and is usually the fastest option. However, the data disappears when that process stops and is not automatically shared with other instances.

Detailed Explanation

In-memory caching stores data inside one application process and is usually the fastest option. However, the data disappears when that process stops and is not automatically shared with other instances.

Distributed caching stores cache data in an external shared system, allowing multiple application instances to use the same cached values. It is useful for horizontally scaled applications but introduces network, serialization, availability, and operational considerations.

The correct choice depends on whether cache consistency must span application instances.

Code Example

// In-memory
builder.Services.AddMemoryCache();

// Distributed example
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});